org.el 939 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851
  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 <https://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; 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-clocking-buffer "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function
  120. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  121. (declare-function org-element-at-point "org-element" ())
  122. (declare-function org-element-cache-refresh "org-element" (pos))
  123. (declare-function org-element-cache-reset "org-element" (&optional all))
  124. (declare-function org-element-contents "org-element" (element))
  125. (declare-function org-element-context "org-element" (&optional element))
  126. (declare-function org-element-copy "org-element" (datum))
  127. (declare-function org-element-interpret-data "org-element" (data))
  128. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  129. (declare-function org-element-link-parser "org-element" ())
  130. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  131. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  132. (declare-function org-element-property "org-element" (property element))
  133. (declare-function org-element-put-property "org-element" (element property value))
  134. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  135. (declare-function org-element-type "org-element" (element))
  136. (declare-function org-element-update-syntax "org-element" ())
  137. (declare-function org-id-find-id-file "org-id" (id))
  138. (declare-function org-id-get-create "org-id" (&optional force))
  139. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  140. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  141. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  142. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  143. (declare-function org-table-align "org-table" ())
  144. (declare-function org-table-begin "org-table" (&optional table-type))
  145. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  146. (declare-function org-table-blank-field "org-table" ())
  147. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  148. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  149. (declare-function org-table-cut-region "org-table" (beg end))
  150. (declare-function org-table-edit-field "org-table" (arg))
  151. (declare-function org-table-end "org-table" (&optional table-type))
  152. (declare-function org-table-end-of-field "org-table" (&optional n))
  153. (declare-function org-table-insert-row "org-table" (&optional arg))
  154. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  155. (declare-function org-table-maybe-eval-formula "org-table" ())
  156. (declare-function org-table-maybe-recalculate-line "org-table" ())
  157. (declare-function org-table-next-row "org-table" ())
  158. (declare-function org-table-paste-rectangle "org-table" ())
  159. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  160. (declare-function
  161. org-table-sort-lines "org-table"
  162. (&optional with-case sorting-type getkey-func compare-func interactive?))
  163. (declare-function org-table-shrink "org-table" (&optional begin end))
  164. (declare-function org-table-toggle-column-width "org-table" (&optional arg))
  165. (declare-function org-table-wrap-region "org-table" (arg))
  166. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  167. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  168. (declare-function orgtbl-mode "org-table" (&optional arg))
  169. (declare-function org-export-get-backend "ox" (name))
  170. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  171. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  172. (defvar ffap-url-regexp) ;Silence byte-compiler
  173. (defsubst org-uniquify (list)
  174. "Non-destructively remove duplicate elements from LIST."
  175. (let ((res (copy-sequence list))) (delete-dups res)))
  176. (defsubst org-get-at-bol (property)
  177. "Get text property PROPERTY at the beginning of line."
  178. (get-text-property (point-at-bol) property))
  179. ;; load languages based on value of `org-babel-load-languages'
  180. (defvar org-babel-load-languages)
  181. ;;;###autoload
  182. (defun org-babel-do-load-languages (sym value)
  183. "Load the languages defined in `org-babel-load-languages'."
  184. (set-default sym value)
  185. (dolist (pair org-babel-load-languages)
  186. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  187. (if active
  188. (require (intern (concat "ob-" lang)))
  189. (funcall 'fmakunbound
  190. (intern (concat "org-babel-execute:" lang)))
  191. (funcall 'fmakunbound
  192. (intern (concat "org-babel-expand-body:" lang)))))))
  193. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  194. ;;;###autoload
  195. (defun org-babel-load-file (file &optional compile)
  196. "Load Emacs Lisp source code blocks in the Org FILE.
  197. This function exports the source code using `org-babel-tangle'
  198. and then loads the resulting file using `load-file'. With prefix
  199. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  200. file to byte-code before it is loaded."
  201. (interactive "fFile to load: \nP")
  202. (let* ((age (lambda (file)
  203. (float-time
  204. (time-subtract (current-time)
  205. (nth 5 (or (file-attributes (file-truename file))
  206. (file-attributes file)))))))
  207. (base-name (file-name-sans-extension file))
  208. (exported-file (concat base-name ".el")))
  209. ;; tangle if the Org file is newer than the elisp file
  210. (unless (and (file-exists-p exported-file)
  211. (> (funcall age file) (funcall age exported-file)))
  212. ;; Tangle-file traversal returns reversed list of tangled files
  213. ;; and we want to evaluate the first target.
  214. (setq exported-file
  215. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  216. (message "%s %s"
  217. (if compile
  218. (progn (byte-compile-file exported-file 'load)
  219. "Compiled and loaded")
  220. (progn (load-file exported-file) "Loaded"))
  221. exported-file)))
  222. (defcustom org-babel-load-languages '((emacs-lisp . t))
  223. "Languages which can be evaluated in Org buffers.
  224. This list can be used to load support for any of the languages
  225. below, note that each language will depend on a different set of
  226. system executables and/or Emacs modes. When a language is
  227. \"loaded\", then code blocks in that language can be evaluated
  228. with `org-babel-execute-src-block' bound by default to C-c
  229. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  230. be set to remove code block evaluation from the C-c C-c
  231. keybinding. By default only Emacs Lisp (which has no
  232. requirements) is loaded."
  233. :group 'org-babel
  234. :set 'org-babel-do-load-languages
  235. :version "24.1"
  236. :type '(alist :tag "Babel Languages"
  237. :key-type
  238. (choice
  239. (const :tag "Awk" awk)
  240. (const :tag "C" C)
  241. (const :tag "R" R)
  242. (const :tag "Asymptote" asymptote)
  243. (const :tag "Calc" calc)
  244. (const :tag "Clojure" clojure)
  245. (const :tag "CSS" css)
  246. (const :tag "Ditaa" ditaa)
  247. (const :tag "Dot" dot)
  248. (const :tag "Ebnf2ps" ebnf2ps)
  249. (const :tag "Emacs Lisp" emacs-lisp)
  250. (const :tag "Forth" forth)
  251. (const :tag "Fortran" fortran)
  252. (const :tag "Gnuplot" gnuplot)
  253. (const :tag "Haskell" haskell)
  254. (const :tag "hledger" hledger)
  255. (const :tag "IO" io)
  256. (const :tag "J" J)
  257. (const :tag "Java" java)
  258. (const :tag "Javascript" js)
  259. (const :tag "LaTeX" latex)
  260. (const :tag "Ledger" ledger)
  261. (const :tag "Lilypond" lilypond)
  262. (const :tag "Lisp" lisp)
  263. (const :tag "Makefile" makefile)
  264. (const :tag "Maxima" maxima)
  265. (const :tag "Matlab" matlab)
  266. (const :tag "Mscgen" mscgen)
  267. (const :tag "Ocaml" ocaml)
  268. (const :tag "Octave" octave)
  269. (const :tag "Org" org)
  270. (const :tag "Perl" perl)
  271. (const :tag "Pico Lisp" picolisp)
  272. (const :tag "PlantUML" plantuml)
  273. (const :tag "Python" python)
  274. (const :tag "Ruby" ruby)
  275. (const :tag "Sass" sass)
  276. (const :tag "Scala" scala)
  277. (const :tag "Scheme" scheme)
  278. (const :tag "Screen" screen)
  279. (const :tag "Shell Script" shell)
  280. (const :tag "Shen" shen)
  281. (const :tag "Sql" sql)
  282. (const :tag "Sqlite" sqlite)
  283. (const :tag "Stan" stan)
  284. (const :tag "Vala" vala))
  285. :value-type (boolean :tag "Activate" :value t)))
  286. ;;;; Customization variables
  287. (defcustom org-clone-delete-id nil
  288. "Remove ID property of clones of a subtree.
  289. When non-nil, clones of a subtree don't inherit the ID property.
  290. Otherwise they inherit the ID property with a new unique
  291. identifier."
  292. :type 'boolean
  293. :version "24.1"
  294. :group 'org-id)
  295. ;;; Version
  296. (org-check-version)
  297. ;;;###autoload
  298. (defun org-version (&optional here full message)
  299. "Show the Org version.
  300. Interactively, or when MESSAGE is non-nil, show it in echo area.
  301. With prefix argument, or when HERE is non-nil, insert it at point.
  302. In non-interactive uses, a reduced version string is output unless
  303. FULL is given."
  304. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  305. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  306. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  307. (load-suffixes (list ".el"))
  308. (org-install-dir
  309. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  310. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  311. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  312. (let* ((load-suffixes save-load-suffixes)
  313. (release (org-release))
  314. (git-version (org-git-version))
  315. (version (format "Org mode version %s (%s @ %s)"
  316. release
  317. git-version
  318. (if org-install-dir
  319. (if (string= org-dir org-install-dir)
  320. org-install-dir
  321. (concat "mixed installation! "
  322. org-install-dir
  323. " and "
  324. org-dir))
  325. "org-loaddefs.el can not be found!")))
  326. (version1 (if full version release)))
  327. (when here (insert version1))
  328. (when message (message "%s" version1))
  329. version1)))
  330. (defconst org-version (org-version))
  331. ;;; Syntax Constants
  332. ;;;; Block
  333. (defconst org-block-regexp
  334. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  335. "Regular expression for hiding blocks.")
  336. (defconst org-dblock-start-re
  337. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  338. "Matches the start line of a dynamic block, with parameters.")
  339. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  340. "Matches the end of a dynamic block.")
  341. ;;;; Clock and Planning
  342. (defconst org-clock-string "CLOCK:"
  343. "String used as prefix for timestamps clocking work hours on an item.")
  344. (defvar org-closed-string "CLOSED:"
  345. "String used as the prefix for timestamps logging closing a TODO entry.")
  346. (defvar org-deadline-string "DEADLINE:"
  347. "String to mark deadline entries.
  348. \\<org-mode-map>
  349. A deadline is this string, followed by a time stamp. It must be
  350. a word, terminated by a colon. You can insert a schedule keyword
  351. and a timestamp with `\\[org-deadline]'.")
  352. (defvar org-scheduled-string "SCHEDULED:"
  353. "String to mark scheduled TODO entries.
  354. \\<org-mode-map>
  355. A schedule is this string, followed by a time stamp. It must be
  356. a word, terminated by a colon. You can insert a schedule keyword
  357. and a timestamp with `\\[org-schedule]'.")
  358. (defconst org-ds-keyword-length
  359. (+ 2
  360. (apply #'max
  361. (mapcar #'length
  362. (list org-deadline-string org-scheduled-string
  363. org-clock-string org-closed-string))))
  364. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  365. (defconst org-planning-line-re
  366. (concat "^[ \t]*"
  367. (regexp-opt
  368. (list org-closed-string org-deadline-string org-scheduled-string)
  369. t))
  370. "Matches a line with planning info.
  371. Matched keyword is in group 1.")
  372. (defconst org-clock-line-re
  373. (concat "^[ \t]*" org-clock-string)
  374. "Matches a line with clock info.")
  375. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  376. "Matches the DEADLINE keyword.")
  377. (defconst org-deadline-time-regexp
  378. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  379. "Matches the DEADLINE keyword together with a time stamp.")
  380. (defconst org-deadline-time-hour-regexp
  381. (concat "\\<" org-deadline-string
  382. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  383. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  384. (defconst org-deadline-line-regexp
  385. (concat "\\<\\(" org-deadline-string "\\).*")
  386. "Matches the DEADLINE keyword and the rest of the line.")
  387. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  388. "Matches the SCHEDULED keyword.")
  389. (defconst org-scheduled-time-regexp
  390. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  391. "Matches the SCHEDULED keyword together with a time stamp.")
  392. (defconst org-scheduled-time-hour-regexp
  393. (concat "\\<" org-scheduled-string
  394. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  395. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  396. (defconst org-closed-time-regexp
  397. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  398. "Matches the CLOSED keyword together with a time stamp.")
  399. (defconst org-keyword-time-regexp
  400. (concat "\\<"
  401. (regexp-opt
  402. (list org-scheduled-string org-deadline-string org-closed-string
  403. org-clock-string)
  404. t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 4 keywords, together with the time stamp.")
  407. (defconst org-keyword-time-not-clock-regexp
  408. (concat
  409. "\\<"
  410. (regexp-opt
  411. (list org-scheduled-string org-deadline-string org-closed-string) t)
  412. " *[[<]\\([^]>]+\\)[]>]")
  413. "Matches any of the 3 keywords, together with the time stamp.")
  414. (defconst org-maybe-keyword-time-regexp
  415. (concat "\\(\\<"
  416. (regexp-opt
  417. (list org-scheduled-string org-deadline-string org-closed-string
  418. org-clock-string)
  419. t)
  420. "\\)?"
  421. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  422. "\\|"
  423. "<%%([^\r\n>]*>\\)")
  424. "Matches a timestamp, possibly preceded by a keyword.")
  425. (defconst org-all-time-keywords
  426. (mapcar (lambda (w) (substring w 0 -1))
  427. (list org-scheduled-string org-deadline-string
  428. org-clock-string org-closed-string))
  429. "List of time keywords.")
  430. ;;;; Drawer
  431. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  432. "Matches first or last line of a hidden block.
  433. Group 1 contains drawer's name or \"END\".")
  434. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  435. "Regular expression matching the first line of a property drawer.")
  436. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  437. "Regular expression matching the last line of a property drawer.")
  438. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  439. "Regular expression matching the first line of a clock drawer.")
  440. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  441. "Regular expression matching the last line of a clock drawer.")
  442. (defconst org-property-drawer-re
  443. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  444. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  445. "[ \t]*:END:[ \t]*$")
  446. "Matches an entire property drawer.")
  447. (defconst org-clock-drawer-re
  448. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  449. org-clock-drawer-end-re "\\)\n?")
  450. "Matches an entire clock drawer.")
  451. ;;;; Headline
  452. (defconst org-heading-keyword-regexp-format
  453. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  454. "Printf format for a regexp matching a headline with some keyword.
  455. This regexp will match the headline of any node which has the
  456. exact keyword that is put into the format. The keyword isn't in
  457. any group by default, but the stars and the body are.")
  458. (defconst org-heading-keyword-maybe-regexp-format
  459. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  460. "Printf format for a regexp matching a headline, possibly with some keyword.
  461. This regexp can match any headline with the specified keyword, or
  462. without a keyword. The keyword isn't in any group by default,
  463. but the stars and the body are.")
  464. (defconst org-archive-tag "ARCHIVE"
  465. "The tag that marks a subtree as archived.
  466. An archived subtree does not open during visibility cycling, and does
  467. not contribute to the agenda listings.")
  468. (eval-and-compile
  469. (defconst org-comment-string "COMMENT"
  470. "Entries starting with this keyword will never be exported.
  471. \\<org-mode-map>
  472. An entry can be toggled between COMMENT and normal with
  473. `\\[org-toggle-comment]'."))
  474. ;;;; LaTeX Environments and Fragments
  475. (defconst org-latex-regexps
  476. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  477. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  478. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  479. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  480. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  481. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  482. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  483. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  484. "Regular expressions for matching embedded LaTeX.")
  485. ;;;; Node Property
  486. (defconst org-effort-property "Effort"
  487. "The property that is being used to keep track of effort estimates.
  488. Effort estimates given in this property need to have the format H:MM.")
  489. ;;;; Table
  490. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  491. "Detect an org-type or table-type table.")
  492. (defconst org-table-line-regexp "^[ \t]*|"
  493. "Detect an org-type table line.")
  494. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  495. "Detect an org-type table line.")
  496. (defconst org-table-hline-regexp "^[ \t]*|-"
  497. "Detect an org-type table hline.")
  498. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  499. "Detect a table-type table hline.")
  500. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  501. "Detect the first line outside a table when searching from within it.
  502. This works for both table types.")
  503. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  504. "Detect a #+TBLFM line.")
  505. ;;;; Timestamp
  506. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  507. "Regular expression for fast time stamp matching.")
  508. (defconst org-ts-regexp-inactive
  509. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  510. "Regular expression for fast inactive time stamp matching.")
  511. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  512. "Regular expression for fast time stamp matching.")
  513. (defconst org-ts-regexp0
  514. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  515. "Regular expression matching time strings for analysis.
  516. This one does not require the space after the date, so it can be used
  517. on a string that terminates immediately after the date.")
  518. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  519. "Regular expression matching time strings for analysis.")
  520. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  521. "Regular expression matching time stamps, with groups.")
  522. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  523. "Regular expression matching time stamps (also [..]), with groups.")
  524. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  525. "Regular expression matching a time stamp range.")
  526. (defconst org-tr-regexp-both
  527. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  528. "Regular expression matching a time stamp range.")
  529. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  530. org-ts-regexp "\\)?")
  531. "Regular expression matching a time stamp or time stamp range.")
  532. (defconst org-tsr-regexp-both
  533. (concat org-ts-regexp-both "\\(--?-?"
  534. org-ts-regexp-both "\\)?")
  535. "Regular expression matching a time stamp or time stamp range.
  536. The time stamps may be either active or inactive.")
  537. (defconst org-repeat-re
  538. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  539. "Regular expression for specifying repeated events.
  540. After a match, group 1 contains the repeat expression.")
  541. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  542. "Formats for `format-time-string' which are used for time stamps.")
  543. ;;; The custom variables
  544. (defgroup org nil
  545. "Outline-based notes management and organizer."
  546. :tag "Org"
  547. :group 'outlines
  548. :group 'calendar)
  549. (defcustom org-mode-hook nil
  550. "Mode hook for Org mode, run after the mode was turned on."
  551. :group 'org
  552. :type 'hook)
  553. (defcustom org-load-hook nil
  554. "Hook that is run after org.el has been loaded."
  555. :group 'org
  556. :type 'hook)
  557. (defcustom org-log-buffer-setup-hook nil
  558. "Hook that is run after an Org log buffer is created."
  559. :group 'org
  560. :version "24.1"
  561. :type 'hook)
  562. (defvar org-modules) ; defined below
  563. (defvar org-modules-loaded nil
  564. "Have the modules been loaded already?")
  565. (defun org-load-modules-maybe (&optional force)
  566. "Load all extensions listed in `org-modules'."
  567. (when (or force (not org-modules-loaded))
  568. (dolist (ext org-modules)
  569. (condition-case nil (require ext)
  570. (error (message "Problems while trying to load feature `%s'" ext))))
  571. (setq org-modules-loaded t)))
  572. (defun org-set-modules (var value)
  573. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  574. (set var value)
  575. (when (featurep 'org)
  576. (org-load-modules-maybe 'force)
  577. (org-element-cache-reset 'all)))
  578. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  579. "Modules that should always be loaded together with org.el.
  580. If a description starts with <C>, the file is not part of Emacs
  581. and loading it will require that you have downloaded and properly
  582. installed the Org mode distribution.
  583. You can also use this system to load external packages (i.e. neither Org
  584. core modules, nor modules from the CONTRIB directory). Just add symbols
  585. to the end of the list. If the package is called org-xyz.el, then you need
  586. to add the symbol `xyz', and the package must have a call to:
  587. (provide \\='org-xyz)
  588. For export specific modules, see also `org-export-backends'."
  589. :group 'org
  590. :set 'org-set-modules
  591. :version "24.4"
  592. :package-version '(Org . "8.0")
  593. :type
  594. '(set :greedy t
  595. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  596. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  597. (const :tag " crypt: Encryption of subtrees" org-crypt)
  598. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  599. (const :tag " docview: Links to doc-view buffers" org-docview)
  600. (const :tag " eww: Store link to url of eww" org-eww)
  601. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  602. (const :tag " habit: Track your consistency with habits" org-habit)
  603. (const :tag " id: Global IDs for identifying entries" org-id)
  604. (const :tag " info: Links to Info nodes" org-info)
  605. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  606. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  607. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  608. (const :tag " mouse: Additional mouse support" org-mouse)
  609. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  610. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  611. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  612. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  613. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  614. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  615. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  616. (const :tag "C collector: Collect properties into tables" org-collector)
  617. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  618. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  619. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  620. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  621. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  622. (const :tag "C eval: Include command output as text" org-eval)
  623. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  624. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  625. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  626. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  627. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  628. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  629. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  630. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  631. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  632. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  633. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  634. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  635. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  636. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  637. (const :tag "C registry: A registry for Org links" org-registry)
  638. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  639. (const :tag "C secretary: Team management with org-mode" org-secretary)
  640. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  641. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  642. (const :tag "C track: Keep up with Org mode development" org-track)
  643. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  644. (const :tag "C vm: Links to VM folders/messages" org-vm)
  645. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  646. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  647. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  648. (defvar org-export-registered-backends) ; From ox.el.
  649. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  650. (declare-function org-export-backend-name "ox" (backend) t)
  651. (defcustom org-export-backends '(ascii html icalendar latex odt)
  652. "List of export back-ends that should be always available.
  653. If a description starts with <C>, the file is not part of Emacs
  654. and loading it will require that you have downloaded and properly
  655. installed the Org mode distribution.
  656. Unlike to `org-modules', libraries in this list will not be
  657. loaded along with Org, but only once the export framework is
  658. needed.
  659. This variable needs to be set before org.el is loaded. If you
  660. need to make a change while Emacs is running, use the customize
  661. interface or run the following code, where VAL stands for the new
  662. value of the variable, after updating it:
  663. (progn
  664. (setq org-export-registered-backends
  665. (cl-remove-if-not
  666. (lambda (backend)
  667. (let ((name (org-export-backend-name backend)))
  668. (or (memq name val)
  669. (catch \\='parentp
  670. (dolist (b val)
  671. (and (org-export-derived-backend-p b name)
  672. (throw \\='parentp t)))))))
  673. org-export-registered-backends))
  674. (let ((new-list (mapcar #\\='org-export-backend-name
  675. org-export-registered-backends)))
  676. (dolist (backend val)
  677. (cond
  678. ((not (load (format \"ox-%s\" backend) t t))
  679. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  680. backend))
  681. ((not (memq backend new-list)) (push backend new-list))))
  682. (set-default \\='org-export-backends new-list)))
  683. Adding a back-end to this list will also pull the back-end it
  684. depends on, if any."
  685. :group 'org
  686. :group 'org-export
  687. :version "26.1"
  688. :package-version '(Org . "9.0")
  689. :initialize 'custom-initialize-set
  690. :set (lambda (var val)
  691. (if (not (featurep 'ox)) (set-default var val)
  692. ;; Any back-end not required anymore (not present in VAL and not
  693. ;; a parent of any back-end in the new value) is removed from the
  694. ;; list of registered back-ends.
  695. (setq org-export-registered-backends
  696. (cl-remove-if-not
  697. (lambda (backend)
  698. (let ((name (org-export-backend-name backend)))
  699. (or (memq name val)
  700. (catch 'parentp
  701. (dolist (b val)
  702. (and (org-export-derived-backend-p b name)
  703. (throw 'parentp t)))))))
  704. org-export-registered-backends))
  705. ;; Now build NEW-LIST of both new back-ends and required
  706. ;; parents.
  707. (let ((new-list (mapcar #'org-export-backend-name
  708. org-export-registered-backends)))
  709. (dolist (backend val)
  710. (cond
  711. ((not (load (format "ox-%s" backend) t t))
  712. (message "Problems while trying to load export back-end `%s'"
  713. backend))
  714. ((not (memq backend new-list)) (push backend new-list))))
  715. ;; Set VAR to that list with fixed dependencies.
  716. (set-default var new-list))))
  717. :type '(set :greedy t
  718. (const :tag " ascii Export buffer to ASCII format" ascii)
  719. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  720. (const :tag " html Export buffer to HTML format" html)
  721. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  722. (const :tag " latex Export buffer to LaTeX format" latex)
  723. (const :tag " man Export buffer to MAN format" man)
  724. (const :tag " md Export buffer to Markdown format" md)
  725. (const :tag " odt Export buffer to ODT format" odt)
  726. (const :tag " org Export buffer to Org format" org)
  727. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  728. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  729. (const :tag "C deck Export buffer to deck.js presentations" deck)
  730. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  731. (const :tag "C groff Export buffer to Groff format" groff)
  732. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  733. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  734. (const :tag "C s5 Export buffer to s5 presentations" s5)
  735. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  736. (eval-after-load 'ox
  737. '(dolist (backend org-export-backends)
  738. (condition-case nil (require (intern (format "ox-%s" backend)))
  739. (error (message "Problems while trying to load export back-end `%s'"
  740. backend)))))
  741. (defcustom org-support-shift-select nil
  742. "Non-nil means make shift-cursor commands select text when possible.
  743. \\<org-mode-map>\
  744. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  745. start selecting a region, or enlarge regions started in this way.
  746. In Org mode, in special contexts, these same keys are used for
  747. other purposes, important enough to compete with shift selection.
  748. Org tries to balance these needs by supporting `shift-select-mode'
  749. outside these special contexts, under control of this variable.
  750. The default of this variable is nil, to avoid confusing behavior. Shifted
  751. cursor keys will then execute Org commands in the following contexts:
  752. - on a headline, changing TODO state (left/right) and priority (up/down)
  753. - on a time stamp, changing the time
  754. - in a plain list item, changing the bullet type
  755. - in a property definition line, switching between allowed values
  756. - in the BEGIN line of a clock table (changing the time block).
  757. Outside these contexts, the commands will throw an error.
  758. When this variable is t and the cursor is not in a special
  759. context, Org mode will support shift-selection for making and
  760. enlarging regions. To make this more effective, the bullet
  761. cycling will no longer happen anywhere in an item line, but only
  762. if the cursor is exactly on the bullet.
  763. If you set this variable to the symbol `always', then the keys
  764. will not be special in headlines, property lines, and item lines,
  765. to make shift selection work there as well. If this is what you
  766. want, you can use the following alternative commands:
  767. `\\[org-todo]' and `\\[org-priority]' \
  768. to change TODO state and priority,
  769. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  770. can be used to switch TODO sets,
  771. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  772. and properties can be edited by hand or in column view.
  773. However, when the cursor is on a timestamp, shift-cursor commands
  774. will still edit the time stamp - this is just too good to give up."
  775. :group 'org
  776. :type '(choice
  777. (const :tag "Never" nil)
  778. (const :tag "When outside special context" t)
  779. (const :tag "Everywhere except timestamps" always)))
  780. (defcustom org-loop-over-headlines-in-active-region nil
  781. "Shall some commands act upon headlines in the active region?
  782. When set to t, some commands will be performed in all headlines
  783. within the active region.
  784. When set to `start-level', some commands will be performed in all
  785. headlines within the active region, provided that these headlines
  786. are of the same level than the first one.
  787. When set to a string, those commands will be performed on the
  788. matching headlines within the active region. Such string must be
  789. a tags/property/todo match as it is used in the agenda tags view.
  790. The list of commands is: `org-schedule', `org-deadline',
  791. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  792. `org-archive-to-archive-sibling'. The archiving commands skip
  793. already archived entries."
  794. :type '(choice (const :tag "Don't loop" nil)
  795. (const :tag "All headlines in active region" t)
  796. (const :tag "In active region, headlines at the same level than the first one" start-level)
  797. (string :tag "Tags/Property/Todo matcher"))
  798. :version "24.1"
  799. :group 'org-todo
  800. :group 'org-archive)
  801. (defgroup org-startup nil
  802. "Options concerning startup of Org mode."
  803. :tag "Org Startup"
  804. :group 'org)
  805. (defcustom org-startup-folded t
  806. "Non-nil means entering Org mode will switch to OVERVIEW.
  807. This can also be configured on a per-file basis by adding one of
  808. the following lines anywhere in the buffer:
  809. #+STARTUP: fold (or `overview', this is equivalent)
  810. #+STARTUP: nofold (or `showall', this is equivalent)
  811. #+STARTUP: content
  812. #+STARTUP: showeverything
  813. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  814. to ignore this option when Org opens agenda files for the first
  815. time."
  816. :group 'org-startup
  817. :type '(choice
  818. (const :tag "nofold: show all" nil)
  819. (const :tag "fold: overview" t)
  820. (const :tag "content: all headlines" content)
  821. (const :tag "show everything, even drawers" showeverything)))
  822. (defcustom org-startup-truncated t
  823. "Non-nil means entering Org mode will set `truncate-lines'.
  824. This is useful since some lines containing links can be very long and
  825. uninteresting. Also tables look terrible when wrapped.
  826. The variable `org-startup-truncated' allows to configure
  827. truncation for Org mode different to the other modes that use the
  828. variable `truncate-lines' and as a shortcut instead of putting
  829. the variable `truncate-lines' into the `org-mode-hook'. If one
  830. wants to configure truncation for Org mode not statically but
  831. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  832. the variable `truncate-lines' has to be used because in such a
  833. case it is too late to set the variable `org-startup-truncated'."
  834. :group 'org-startup
  835. :type 'boolean)
  836. (defcustom org-startup-indented nil
  837. "Non-nil means turn on `org-indent-mode' on startup.
  838. This can also be configured on a per-file basis by adding one of
  839. the following lines anywhere in the buffer:
  840. #+STARTUP: indent
  841. #+STARTUP: noindent"
  842. :group 'org-structure
  843. :type '(choice
  844. (const :tag "Not" nil)
  845. (const :tag "Globally (slow on startup in large files)" t)))
  846. (defcustom org-use-sub-superscripts t
  847. "Non-nil means interpret \"_\" and \"^\" for display.
  848. If you want to control how Org exports those characters, see
  849. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  850. used to be an alias for `org-export-with-sub-superscripts' in
  851. Org <8.0, it is not anymore.
  852. When this option is turned on, you can use TeX-like syntax for
  853. sub- and superscripts within the buffer. Several characters after
  854. \"_\" or \"^\" will be considered as a single item - so grouping
  855. with {} is normally not needed. For example, the following things
  856. will be parsed as single sub- or superscripts:
  857. 10^24 or 10^tau several digits will be considered 1 item.
  858. 10^-12 or 10^-tau a leading sign with digits or a word
  859. x^2-y^3 will be read as x^2 - y^3, because items are
  860. terminated by almost any nonword/nondigit char.
  861. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  862. Still, ambiguity is possible. So when in doubt, use {} to enclose
  863. the sub/superscript. If you set this variable to the symbol `{}',
  864. the braces are *required* in order to trigger interpretations as
  865. sub/superscript. This can be helpful in documents that need \"_\"
  866. frequently in plain text."
  867. :group 'org-startup
  868. :version "24.4"
  869. :package-version '(Org . "8.0")
  870. :type '(choice
  871. (const :tag "Always interpret" t)
  872. (const :tag "Only with braces" {})
  873. (const :tag "Never interpret" nil)))
  874. (defcustom org-startup-with-beamer-mode nil
  875. "Non-nil means turn on `org-beamer-mode' on startup.
  876. This can also be configured on a per-file basis by adding one of
  877. the following lines anywhere in the buffer:
  878. #+STARTUP: beamer"
  879. :group 'org-startup
  880. :version "24.1"
  881. :type 'boolean)
  882. (defcustom org-startup-align-all-tables nil
  883. "Non-nil means align all tables when visiting a file.
  884. This can also be configured on a per-file basis by adding one of
  885. the following lines anywhere in the buffer:
  886. #+STARTUP: align
  887. #+STARTUP: noalign"
  888. :group 'org-startup
  889. :type 'boolean)
  890. (defcustom org-startup-shrink-all-tables nil
  891. "Non-nil means shrink all table columns with a width cookie.
  892. This can also be configured on a per-file basis by adding one of
  893. the following lines anywhere in the buffer:
  894. #+STARTUP: shrink"
  895. :group 'org-startup
  896. :type 'boolean
  897. :version "26.1"
  898. :package-version '(Org . "9.1")
  899. :safe #'booleanp)
  900. (defcustom org-startup-with-inline-images nil
  901. "Non-nil means show inline images when loading a new Org file.
  902. This can also be configured on a per-file basis by adding one of
  903. the following lines anywhere in the buffer:
  904. #+STARTUP: inlineimages
  905. #+STARTUP: noinlineimages"
  906. :group 'org-startup
  907. :version "24.1"
  908. :type 'boolean)
  909. (defcustom org-startup-with-latex-preview nil
  910. "Non-nil means preview LaTeX fragments when loading a new Org file.
  911. This can also be configured on a per-file basis by adding one of
  912. the following lines anywhere in the buffer:
  913. #+STARTUP: latexpreview
  914. #+STARTUP: nolatexpreview"
  915. :group 'org-startup
  916. :version "24.4"
  917. :package-version '(Org . "8.0")
  918. :type 'boolean)
  919. (defcustom org-insert-mode-line-in-empty-file nil
  920. "Non-nil means insert the first line setting Org mode in empty files.
  921. When the function `org-mode' is called interactively in an empty file, this
  922. normally means that the file name does not automatically trigger Org mode.
  923. To ensure that the file will always be in Org mode in the future, a
  924. line enforcing Org mode will be inserted into the buffer, if this option
  925. has been set."
  926. :group 'org-startup
  927. :type 'boolean)
  928. (defcustom org-replace-disputed-keys nil
  929. "Non-nil means use alternative key bindings for some keys.
  930. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  931. These keys are also used by other packages like shift-selection-mode'
  932. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  933. If you want to use Org mode together with one of these other modes,
  934. or more generally if you would like to move some Org mode commands to
  935. other keys, set this variable and configure the keys with the variable
  936. `org-disputed-keys'.
  937. This option is only relevant at load-time of Org mode, and must be set
  938. *before* org.el is loaded. Changing it requires a restart of Emacs to
  939. become effective."
  940. :group 'org-startup
  941. :type 'boolean)
  942. (defcustom org-use-extra-keys nil
  943. "Non-nil means use extra key sequence definitions for certain commands.
  944. This happens automatically if `window-system' is nil. This
  945. variable lets you do the same manually. You must set it before
  946. loading Org."
  947. :group 'org-startup
  948. :type 'boolean)
  949. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  950. (defcustom org-disputed-keys
  951. '(([(shift up)] . [(meta p)])
  952. ([(shift down)] . [(meta n)])
  953. ([(shift left)] . [(meta -)])
  954. ([(shift right)] . [(meta +)])
  955. ([(control shift right)] . [(meta shift +)])
  956. ([(control shift left)] . [(meta shift -)]))
  957. "Keys for which Org mode and other modes compete.
  958. This is an alist, cars are the default keys, second element specifies
  959. the alternative to use when `org-replace-disputed-keys' is t.
  960. Keys can be specified in any syntax supported by `define-key'.
  961. The value of this option takes effect only at Org mode startup,
  962. therefore you'll have to restart Emacs to apply it after changing."
  963. :group 'org-startup
  964. :type 'alist)
  965. (defun org-key (key)
  966. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  967. Or return the original if not disputed."
  968. (when org-replace-disputed-keys
  969. (let* ((nkey (key-description key))
  970. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  971. org-disputed-keys)))
  972. (setq key (if x (cdr x) key))))
  973. key)
  974. (defun org-defkey (keymap key def)
  975. "Define a key, possibly translated, as returned by `org-key'."
  976. (define-key keymap (org-key key) def))
  977. (defcustom org-ellipsis nil
  978. "The ellipsis to use in the Org mode outline.
  979. When nil, just use the standard three dots. When a non-empty string,
  980. use that string instead.
  981. The change affects only Org mode (which will then use its own display table).
  982. Changing this requires executing `\\[org-mode]' in a buffer to become
  983. effective."
  984. :group 'org-startup
  985. :type '(choice (const :tag "Default" nil)
  986. (string :tag "String" :value "...#"))
  987. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  988. (defvar org-display-table nil
  989. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  990. (defgroup org-keywords nil
  991. "Keywords in Org mode."
  992. :tag "Org Keywords"
  993. :group 'org)
  994. (defcustom org-closed-keep-when-no-todo nil
  995. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  996. :group 'org-todo
  997. :group 'org-keywords
  998. :version "24.4"
  999. :package-version '(Org . "8.0")
  1000. :type 'boolean)
  1001. (defgroup org-structure nil
  1002. "Options concerning the general structure of Org files."
  1003. :tag "Org Structure"
  1004. :group 'org)
  1005. (defgroup org-reveal-location nil
  1006. "Options about how to make context of a location visible."
  1007. :tag "Org Reveal Location"
  1008. :group 'org-structure)
  1009. (defcustom org-show-context-detail '((agenda . local)
  1010. (bookmark-jump . lineage)
  1011. (isearch . lineage)
  1012. (default . ancestors))
  1013. "Alist between context and visibility span when revealing a location.
  1014. \\<org-mode-map>Some actions may move point into invisible
  1015. locations. As a consequence, Org always expose a neighborhood
  1016. around point. How much is shown depends on the initial action,
  1017. or context. Valid contexts are
  1018. agenda when exposing an entry from the agenda
  1019. org-goto when using the command `org-goto' (`\\[org-goto]')
  1020. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1021. tags-tree when constructing a sparse tree based on tags matches
  1022. link-search when exposing search matches associated with a link
  1023. mark-goto when exposing the jump goal of a mark
  1024. bookmark-jump when exposing a bookmark location
  1025. isearch when exiting from an incremental search
  1026. default default for all contexts not set explicitly
  1027. Allowed visibility spans are
  1028. minimal show current headline; if point is not on headline,
  1029. also show entry
  1030. local show current headline, entry and next headline
  1031. ancestors show current headline and its direct ancestors; if
  1032. point is not on headline, also show entry
  1033. lineage show current headline, its direct ancestors and all
  1034. their children; if point is not on headline, also show
  1035. entry and first child
  1036. tree show current headline, its direct ancestors and all
  1037. their children; if point is not on headline, also show
  1038. entry and all children
  1039. canonical show current headline, its direct ancestors along with
  1040. their entries and children; if point is not located on
  1041. the headline, also show current entry and all children
  1042. As special cases, a nil or t value means show all contexts in
  1043. `minimal' or `canonical' view, respectively.
  1044. Some views can make displayed information very compact, but also
  1045. make it harder to edit the location of the match. In such
  1046. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1047. more context."
  1048. :group 'org-reveal-location
  1049. :version "26.1"
  1050. :package-version '(Org . "9.0")
  1051. :type '(choice
  1052. (const :tag "Canonical" t)
  1053. (const :tag "Minimal" nil)
  1054. (repeat :greedy t :tag "Individual contexts"
  1055. (cons
  1056. (choice :tag "Context"
  1057. (const agenda)
  1058. (const org-goto)
  1059. (const occur-tree)
  1060. (const tags-tree)
  1061. (const link-search)
  1062. (const mark-goto)
  1063. (const bookmark-jump)
  1064. (const isearch)
  1065. (const default))
  1066. (choice :tag "Detail level"
  1067. (const minimal)
  1068. (const local)
  1069. (const ancestors)
  1070. (const lineage)
  1071. (const tree)
  1072. (const canonical))))))
  1073. (defcustom org-indirect-buffer-display 'other-window
  1074. "How should indirect tree buffers be displayed?
  1075. This applies to indirect buffers created with the commands
  1076. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1077. Valid values are:
  1078. current-window Display in the current window
  1079. other-window Just display in another window.
  1080. dedicated-frame Create one new frame, and re-use it each time.
  1081. new-frame Make a new frame each time. Note that in this case
  1082. previously-made indirect buffers are kept, and you need to
  1083. kill these buffers yourself."
  1084. :group 'org-structure
  1085. :group 'org-agenda-windows
  1086. :type '(choice
  1087. (const :tag "In current window" current-window)
  1088. (const :tag "In current frame, other window" other-window)
  1089. (const :tag "Each time a new frame" new-frame)
  1090. (const :tag "One dedicated frame" dedicated-frame)))
  1091. (defcustom org-use-speed-commands nil
  1092. "Non-nil means activate single letter commands at beginning of a headline.
  1093. This may also be a function to test for appropriate locations where speed
  1094. commands should be active.
  1095. For example, to activate speed commands when the point is on any
  1096. star at the beginning of the headline, you can do this:
  1097. (setq org-use-speed-commands
  1098. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1099. :group 'org-structure
  1100. :type '(choice
  1101. (const :tag "Never" nil)
  1102. (const :tag "At beginning of headline stars" t)
  1103. (function)))
  1104. (defcustom org-speed-commands-user nil
  1105. "Alist of additional speed commands.
  1106. This list will be checked before `org-speed-commands-default'
  1107. when the variable `org-use-speed-commands' is non-nil
  1108. and when the cursor is at the beginning of a headline.
  1109. The car if each entry is a string with a single letter, which must
  1110. be assigned to `self-insert-command' in the global map.
  1111. The cdr is either a command to be called interactively, a function
  1112. to be called, or a form to be evaluated.
  1113. An entry that is just a list with a single string will be interpreted
  1114. as a descriptive headline that will be added when listing the speed
  1115. commands in the Help buffer using the `?' speed command."
  1116. :group 'org-structure
  1117. :type '(repeat :value ("k" . ignore)
  1118. (choice :value ("k" . ignore)
  1119. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1120. (cons :tag "Letter and Command"
  1121. (string :tag "Command letter")
  1122. (choice
  1123. (function)
  1124. (sexp))))))
  1125. (defcustom org-bookmark-names-plist
  1126. '(:last-capture "org-capture-last-stored"
  1127. :last-refile "org-refile-last-stored"
  1128. :last-capture-marker "org-capture-last-stored-marker")
  1129. "Names for bookmarks automatically set by some Org commands.
  1130. This can provide strings as names for a number of bookmarks Org sets
  1131. automatically. The following keys are currently implemented:
  1132. :last-capture
  1133. :last-capture-marker
  1134. :last-refile
  1135. When a key does not show up in the property list, the corresponding bookmark
  1136. is not set."
  1137. :group 'org-structure
  1138. :type 'plist)
  1139. (defgroup org-cycle nil
  1140. "Options concerning visibility cycling in Org mode."
  1141. :tag "Org Cycle"
  1142. :group 'org-structure)
  1143. (defcustom org-cycle-skip-children-state-if-no-children t
  1144. "Non-nil means skip CHILDREN state in entries that don't have any."
  1145. :group 'org-cycle
  1146. :type 'boolean)
  1147. (defcustom org-cycle-max-level nil
  1148. "Maximum level which should still be subject to visibility cycling.
  1149. Levels higher than this will, for cycling, be treated as text, not a headline.
  1150. When `org-odd-levels-only' is set, a value of N in this variable actually
  1151. means 2N-1 stars as the limiting headline.
  1152. When nil, cycle all levels.
  1153. Note that the limiting level of cycling is also influenced by
  1154. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1155. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1156. than its value."
  1157. :group 'org-cycle
  1158. :type '(choice
  1159. (const :tag "No limit" nil)
  1160. (integer :tag "Maximum level")))
  1161. (defcustom org-hide-block-startup nil
  1162. "Non-nil means entering Org mode will fold all blocks.
  1163. This can also be set in on a per-file basis with
  1164. #+STARTUP: hideblocks
  1165. #+STARTUP: showblocks"
  1166. :group 'org-startup
  1167. :group 'org-cycle
  1168. :type 'boolean)
  1169. (defcustom org-cycle-global-at-bob nil
  1170. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1171. This makes it possible to do global cycling without having to use `S-TAB'
  1172. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1173. line of the buffer
  1174. must not be a headline -- it may be empty or some other text.
  1175. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1176. sure the cursor stays at the beginning of the buffer.
  1177. When this option is nil, don't do anything special at the beginning of
  1178. the buffer."
  1179. :group 'org-cycle
  1180. :type 'boolean)
  1181. (defcustom org-cycle-level-after-item/entry-creation t
  1182. "Non-nil means cycle entry level or item indentation in new empty entries.
  1183. When the cursor is at the end of an empty headline, i.e., with only stars
  1184. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1185. and then all possible ancestor states, before returning to the original state.
  1186. This makes data entry extremely fast: M-RET to create a new headline,
  1187. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1188. When the cursor is at the end of an empty plain list item, one TAB will
  1189. make it a subitem, two or more tabs will back up to make this an item
  1190. higher up in the item hierarchy."
  1191. :group 'org-cycle
  1192. :type 'boolean)
  1193. (defcustom org-cycle-emulate-tab t
  1194. "Where should `org-cycle' emulate TAB.
  1195. nil Never
  1196. white Only in completely white lines
  1197. whitestart Only at the beginning of lines, before the first non-white char
  1198. t Everywhere except in headlines
  1199. exc-hl-bol Everywhere except at the start of a headline
  1200. If TAB is used in a place where it does not emulate TAB, the current subtree
  1201. visibility is cycled."
  1202. :group 'org-cycle
  1203. :type '(choice (const :tag "Never" nil)
  1204. (const :tag "Only in completely white lines" white)
  1205. (const :tag "Before first char in a line" whitestart)
  1206. (const :tag "Everywhere except in headlines" t)
  1207. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1208. (defcustom org-cycle-separator-lines 2
  1209. "Number of empty lines needed to keep an empty line between collapsed trees.
  1210. If you leave an empty line between the end of a subtree and the following
  1211. headline, this empty line is hidden when the subtree is folded.
  1212. Org mode will leave (exactly) one empty line visible if the number of
  1213. empty lines is equal or larger to the number given in this variable.
  1214. So the default 2 means at least 2 empty lines after the end of a subtree
  1215. are needed to produce free space between a collapsed subtree and the
  1216. following headline.
  1217. If the number is negative, and the number of empty lines is at least -N,
  1218. all empty lines are shown.
  1219. Special case: when 0, never leave empty lines in collapsed view."
  1220. :group 'org-cycle
  1221. :type 'integer)
  1222. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1223. (defcustom org-pre-cycle-hook nil
  1224. "Hook that is run before visibility cycling is happening.
  1225. The function(s) in this hook must accept a single argument which indicates
  1226. the new state that will be set right after running this hook. The
  1227. argument is a symbol. Before a global state change, it can have the values
  1228. `overview', `content', or `all'. Before a local state change, it can have
  1229. the values `folded', `children', or `subtree'."
  1230. :group 'org-cycle
  1231. :type 'hook)
  1232. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1233. org-cycle-hide-drawers
  1234. org-cycle-show-empty-lines
  1235. org-optimize-window-after-visibility-change)
  1236. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1237. The function(s) in this hook must accept a single argument which indicates
  1238. the new state that was set by the most recent `org-cycle' command. The
  1239. argument is a symbol. After a global state change, it can have the values
  1240. `overview', `contents', or `all'. After a local state change, it can have
  1241. the values `folded', `children', or `subtree'."
  1242. :group 'org-cycle
  1243. :type 'hook
  1244. :version "26.1"
  1245. :package-version '(Org . "8.3"))
  1246. (defgroup org-edit-structure nil
  1247. "Options concerning structure editing in Org mode."
  1248. :tag "Org Edit Structure"
  1249. :group 'org-structure)
  1250. (defcustom org-odd-levels-only nil
  1251. "Non-nil means skip even levels and only use odd levels for the outline.
  1252. This has the effect that two stars are being added/taken away in
  1253. promotion/demotion commands. It also influences how levels are
  1254. handled by the exporters.
  1255. Changing it requires restart of `font-lock-mode' to become effective
  1256. for fontification also in regions already fontified.
  1257. You may also set this on a per-file basis by adding one of the following
  1258. lines to the buffer:
  1259. #+STARTUP: odd
  1260. #+STARTUP: oddeven"
  1261. :group 'org-edit-structure
  1262. :group 'org-appearance
  1263. :type 'boolean)
  1264. (defcustom org-adapt-indentation t
  1265. "Non-nil means adapt indentation to outline node level.
  1266. When this variable is set, Org assumes that you write outlines by
  1267. indenting text in each node to align with the headline (after the
  1268. stars). The following issues are influenced by this variable:
  1269. - The indentation is increased by one space in a demotion
  1270. command, and decreased by one in a promotion command. However,
  1271. in the latter case, if shifting some line in the entry body
  1272. would alter document structure (e.g., insert a new headline),
  1273. indentation is not changed at all.
  1274. - Property drawers and planning information is inserted indented
  1275. when this variable is set. When nil, they will not be indented.
  1276. - TAB indents a line relative to current level. The lines below
  1277. a headline will be indented when this variable is set.
  1278. Note that this is all about true indentation, by adding and
  1279. removing space characters. See also `org-indent.el' which does
  1280. level-dependent indentation in a virtual way, i.e. at display
  1281. time in Emacs."
  1282. :group 'org-edit-structure
  1283. :type 'boolean)
  1284. (defcustom org-special-ctrl-a/e nil
  1285. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1286. When t, `C-a' will bring back the cursor to the beginning of the
  1287. headline text, i.e. after the stars and after a possible TODO
  1288. keyword. In an item, this will be the position after bullet and
  1289. check-box, if any. When the cursor is already at that position,
  1290. another `C-a' will bring it to the beginning of the line.
  1291. `C-e' will jump to the end of the headline, ignoring the presence
  1292. of tags in the headline. A second `C-e' will then jump to the
  1293. true end of the line, after any tags. This also means that, when
  1294. this variable is non-nil, `C-e' also will never jump beyond the
  1295. end of the heading of a folded section, i.e. not after the
  1296. ellipses.
  1297. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1298. normally, going to the true line boundary first. Only a directly
  1299. following, identical keypress will bring the cursor to the
  1300. special positions.
  1301. This may also be a cons cell where the behavior for `C-a' and
  1302. `C-e' is set separately."
  1303. :group 'org-edit-structure
  1304. :type '(choice
  1305. (const :tag "off" nil)
  1306. (const :tag "on: after stars/bullet and before tags first" t)
  1307. (const :tag "reversed: true line boundary first" reversed)
  1308. (cons :tag "Set C-a and C-e separately"
  1309. (choice :tag "Special C-a"
  1310. (const :tag "off" nil)
  1311. (const :tag "on: after stars/bullet first" t)
  1312. (const :tag "reversed: before stars/bullet first" reversed))
  1313. (choice :tag "Special C-e"
  1314. (const :tag "off" nil)
  1315. (const :tag "on: before tags first" t)
  1316. (const :tag "reversed: after tags first" reversed)))))
  1317. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1318. (defcustom org-special-ctrl-k nil
  1319. "Non-nil means `C-k' will behave specially in headlines.
  1320. When nil, `C-k' will call the default `kill-line' command.
  1321. When t, the following will happen while the cursor is in the headline:
  1322. - When the cursor is at the beginning of a headline, kill the entire
  1323. line and possible the folded subtree below the line.
  1324. - When in the middle of the headline text, kill the headline up to the tags.
  1325. - When after the headline text, kill the tags."
  1326. :group 'org-edit-structure
  1327. :type 'boolean)
  1328. (defcustom org-ctrl-k-protect-subtree nil
  1329. "Non-nil means, do not delete a hidden subtree with C-k.
  1330. When set to the symbol `error', simply throw an error when C-k is
  1331. used to kill (part-of) a headline that has hidden text behind it.
  1332. Any other non-nil value will result in a query to the user, if it is
  1333. OK to kill that hidden subtree. When nil, kill without remorse."
  1334. :group 'org-edit-structure
  1335. :version "24.1"
  1336. :type '(choice
  1337. (const :tag "Do not protect hidden subtrees" nil)
  1338. (const :tag "Protect hidden subtrees with a security query" t)
  1339. (const :tag "Never kill a hidden subtree with C-k" error)))
  1340. (defcustom org-special-ctrl-o t
  1341. "Non-nil means, make `C-o' insert a row in tables."
  1342. :group 'org-edit-structure
  1343. :type 'boolean)
  1344. (defcustom org-catch-invisible-edits nil
  1345. "Check if in invisible region before inserting or deleting a character.
  1346. Valid values are:
  1347. nil Do not check, so just do invisible edits.
  1348. error Throw an error and do nothing.
  1349. show Make point visible, and do the requested edit.
  1350. show-and-error Make point visible, then throw an error and abort the edit.
  1351. smart Make point visible, and do insertion/deletion if it is
  1352. adjacent to visible text and the change feels predictable.
  1353. Never delete a previously invisible character or add in the
  1354. middle or right after an invisible region. Basically, this
  1355. allows insertion and backward-delete right before ellipses.
  1356. FIXME: maybe in this case we should not even show?"
  1357. :group 'org-edit-structure
  1358. :version "24.1"
  1359. :type '(choice
  1360. (const :tag "Do not check" nil)
  1361. (const :tag "Throw error when trying to edit" error)
  1362. (const :tag "Unhide, but do not do the edit" show-and-error)
  1363. (const :tag "Show invisible part and do the edit" show)
  1364. (const :tag "Be smart and do the right thing" smart)))
  1365. (defcustom org-yank-folded-subtrees t
  1366. "Non-nil means when yanking subtrees, fold them.
  1367. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1368. it starts with a heading and all other headings in it are either children
  1369. or siblings, then fold all the subtrees. However, do this only if no
  1370. text after the yank would be swallowed into a folded tree by this action."
  1371. :group 'org-edit-structure
  1372. :type 'boolean)
  1373. (defcustom org-yank-adjusted-subtrees nil
  1374. "Non-nil means when yanking subtrees, adjust the level.
  1375. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1376. this function for details."
  1377. :group 'org-edit-structure
  1378. :type 'boolean)
  1379. (defcustom org-M-RET-may-split-line '((default . t))
  1380. "Non-nil means M-RET will split the line at the cursor position.
  1381. When nil, it will go to the end of the line before making a
  1382. new line.
  1383. You may also set this option in a different way for different
  1384. contexts. Valid contexts are:
  1385. headline when creating a new headline
  1386. item when creating a new item
  1387. table in a table field
  1388. default the value to be used for all contexts not explicitly
  1389. customized"
  1390. :group 'org-structure
  1391. :group 'org-table
  1392. :type '(choice
  1393. (const :tag "Always" t)
  1394. (const :tag "Never" nil)
  1395. (repeat :greedy t :tag "Individual contexts"
  1396. (cons
  1397. (choice :tag "Context"
  1398. (const headline)
  1399. (const item)
  1400. (const table)
  1401. (const default))
  1402. (boolean)))))
  1403. (defcustom org-insert-heading-respect-content nil
  1404. "Non-nil means insert new headings after the current subtree.
  1405. \\<org-mode-map>
  1406. When nil, the new heading is created directly after the current line.
  1407. The commands `\\[org-insert-heading-respect-content]' and \
  1408. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1409. for the duration of the command."
  1410. :group 'org-structure
  1411. :type 'boolean)
  1412. (defcustom org-blank-before-new-entry '((heading . auto)
  1413. (plain-list-item . auto))
  1414. "Should `org-insert-heading' leave a blank line before new heading/item?
  1415. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1416. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1417. which case Org will look at the surrounding headings/items and try to
  1418. make an intelligent decision whether to insert a blank line or not."
  1419. :group 'org-edit-structure
  1420. :type '(list
  1421. (cons (const heading)
  1422. (choice (const :tag "Never" nil)
  1423. (const :tag "Always" t)
  1424. (const :tag "Auto" auto)))
  1425. (cons (const plain-list-item)
  1426. (choice (const :tag "Never" nil)
  1427. (const :tag "Always" t)
  1428. (const :tag "Auto" auto)))))
  1429. (defcustom org-insert-heading-hook nil
  1430. "Hook being run after inserting a new heading."
  1431. :group 'org-edit-structure
  1432. :type 'hook)
  1433. (defcustom org-enable-fixed-width-editor t
  1434. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1435. This currently only means they are never auto-wrapped.
  1436. When nil, such lines will be treated like ordinary lines."
  1437. :group 'org-edit-structure
  1438. :type 'boolean)
  1439. (defcustom org-goto-auto-isearch t
  1440. "Non-nil means typing characters in `org-goto' starts incremental search.
  1441. When nil, you can use these keybindings to navigate the buffer:
  1442. q Quit the org-goto interface
  1443. n Go to the next visible heading
  1444. p Go to the previous visible heading
  1445. f Go one heading forward on same level
  1446. b Go one heading backward on same level
  1447. u Go one heading up"
  1448. :group 'org-edit-structure
  1449. :type 'boolean)
  1450. (defgroup org-sparse-trees nil
  1451. "Options concerning sparse trees in Org mode."
  1452. :tag "Org Sparse Trees"
  1453. :group 'org-structure)
  1454. (defcustom org-highlight-sparse-tree-matches t
  1455. "Non-nil means highlight all matches that define a sparse tree.
  1456. The highlights will automatically disappear the next time the buffer is
  1457. changed by an edit command."
  1458. :group 'org-sparse-trees
  1459. :type 'boolean)
  1460. (defcustom org-remove-highlights-with-change t
  1461. "Non-nil means any change to the buffer will remove temporary highlights.
  1462. \\<org-mode-map>\
  1463. Such highlights are created by `org-occur' and `org-clock-display'.
  1464. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1465. to get rid of the highlights.
  1466. The highlights created by `org-toggle-latex-fragment' always need
  1467. `\\[org-toggle-latex-fragment]' to be removed."
  1468. :group 'org-sparse-trees
  1469. :group 'org-time
  1470. :type 'boolean)
  1471. (defcustom org-occur-case-fold-search t
  1472. "Non-nil means `org-occur' should be case-insensitive.
  1473. If set to `smart' the search will be case-insensitive only if it
  1474. doesn't specify any upper case character."
  1475. :group 'org-sparse-trees
  1476. :version "26.1"
  1477. :type '(choice
  1478. (const :tag "Case-sensitive" nil)
  1479. (const :tag "Case-insensitive" t)
  1480. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1481. (defcustom org-occur-hook '(org-first-headline-recenter)
  1482. "Hook that is run after `org-occur' has constructed a sparse tree.
  1483. This can be used to recenter the window to show as much of the structure
  1484. as possible."
  1485. :group 'org-sparse-trees
  1486. :type 'hook)
  1487. (defgroup org-imenu-and-speedbar nil
  1488. "Options concerning imenu and speedbar in Org mode."
  1489. :tag "Org Imenu and Speedbar"
  1490. :group 'org-structure)
  1491. (defcustom org-imenu-depth 2
  1492. "The maximum level for Imenu access to Org headlines.
  1493. This also applied for speedbar access."
  1494. :group 'org-imenu-and-speedbar
  1495. :type 'integer)
  1496. (defgroup org-table nil
  1497. "Options concerning tables in Org mode."
  1498. :tag "Org Table"
  1499. :group 'org)
  1500. (defcustom org-self-insert-cluster-for-undo nil
  1501. "Non-nil means cluster self-insert commands for undo when possible.
  1502. If this is set, then, like in the Emacs command loop, 20 consecutive
  1503. characters will be undone together.
  1504. This is configurable, because there is some impact on typing performance."
  1505. :group 'org-table
  1506. :type 'boolean)
  1507. (defcustom org-table-tab-recognizes-table.el t
  1508. "Non-nil means TAB will automatically notice a table.el table.
  1509. When it sees such a table, it moves point into it and - if necessary -
  1510. calls `table-recognize-table'."
  1511. :group 'org-table-editing
  1512. :type 'boolean)
  1513. (defgroup org-link nil
  1514. "Options concerning links in Org mode."
  1515. :tag "Org Link"
  1516. :group 'org)
  1517. (defvar-local org-link-abbrev-alist-local nil
  1518. "Buffer-local version of `org-link-abbrev-alist', which see.
  1519. The value of this is taken from the #+LINK lines.")
  1520. (defcustom org-link-parameters
  1521. '(("doi" :follow org--open-doi-link)
  1522. ("elisp" :follow org--open-elisp-link)
  1523. ("file" :complete org-file-complete-link)
  1524. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1525. ("help" :follow org--open-help-link)
  1526. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1527. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1528. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1529. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1530. ("shell" :follow org--open-shell-link))
  1531. "An alist of properties that defines all the links in Org mode.
  1532. The key in each association is a string of the link type.
  1533. Subsequent optional elements make up a p-list of link properties.
  1534. :follow - A function that takes the link path as an argument.
  1535. :export - A function that takes the link path, description and
  1536. export-backend as arguments.
  1537. :store - A function responsible for storing the link. See the
  1538. function `org-store-link-functions'.
  1539. :complete - A function that inserts a link with completion. The
  1540. function takes one optional prefix arg.
  1541. :face - A face for the link, or a function that returns a face.
  1542. The function takes one argument which is the link path. The
  1543. default face is `org-link'.
  1544. :mouse-face - The mouse-face. The default is `highlight'.
  1545. :display - `full' will not fold the link in descriptive
  1546. display. Default is `org-link'.
  1547. :help-echo - A string or function that takes (window object position)
  1548. as arguments and returns a string.
  1549. :keymap - A keymap that is active on the link. The default is
  1550. `org-mouse-map'.
  1551. :htmlize-link - A function for the htmlize-link. Defaults
  1552. to (list :uri \"type:path\")
  1553. :activate-func - A function to run at the end of font-lock
  1554. activation. The function must accept (link-start link-end path bracketp)
  1555. as arguments."
  1556. :group 'org-link
  1557. :type '(alist :tag "Link display parameters"
  1558. :value-type plist)
  1559. :version "26.1"
  1560. :package-version '(Org . "9.1"))
  1561. (defun org-link-get-parameter (type key)
  1562. "Get TYPE link property for KEY.
  1563. TYPE is a string and KEY is a plist keyword."
  1564. (plist-get
  1565. (cdr (assoc type org-link-parameters))
  1566. key))
  1567. (defun org-link-set-parameters (type &rest parameters)
  1568. "Set link TYPE properties to PARAMETERS.
  1569. PARAMETERS should be :key val pairs."
  1570. (let ((data (assoc type org-link-parameters)))
  1571. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1572. (push (cons type parameters) org-link-parameters)
  1573. (org-make-link-regexps)
  1574. (org-element-update-syntax))))
  1575. (defun org-link-types ()
  1576. "Return a list of known link types."
  1577. (mapcar #'car org-link-parameters))
  1578. (defcustom org-link-abbrev-alist nil
  1579. "Alist of link abbreviations.
  1580. The car of each element is a string, to be replaced at the start of a link.
  1581. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1582. links in Org buffers can have an optional tag after a double colon, e.g.,
  1583. [[linkkey:tag][description]]
  1584. The `linkkey' must be a single word, starting with a letter, followed
  1585. by letters, numbers, `-' or `_'.
  1586. If REPLACE is a string, the tag will simply be appended to create the link.
  1587. If the string contains \"%s\", the tag will be inserted there. If the string
  1588. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1589. at that point (see the function `url-hexify-string'). If the string contains
  1590. the specifier \"%(my-function)\", then the custom function `my-function' will
  1591. be invoked: this function takes the tag as its only argument and must return
  1592. a string.
  1593. REPLACE may also be a function that will be called with the tag as the
  1594. only argument to create the link, which should be returned as a string.
  1595. See the manual for examples."
  1596. :group 'org-link
  1597. :type '(repeat
  1598. (cons
  1599. (string :tag "Protocol")
  1600. (choice
  1601. (string :tag "Format")
  1602. (function)))))
  1603. (defcustom org-descriptive-links t
  1604. "Non-nil means Org will display descriptive links.
  1605. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1606. \"Org Website\", hiding the link itself and just displaying its
  1607. description. When set to nil, Org will display the full links
  1608. literally.
  1609. You can interactively set the value of this variable by calling
  1610. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1611. :group 'org-link
  1612. :type 'boolean)
  1613. (defcustom org-link-file-path-type 'adaptive
  1614. "How the path name in file links should be stored.
  1615. Valid values are:
  1616. relative Relative to the current directory, i.e. the directory of the file
  1617. into which the link is being inserted.
  1618. absolute Absolute path, if possible with ~ for home directory.
  1619. noabbrev Absolute path, no abbreviation of home directory.
  1620. adaptive Use relative path for files in the current directory and sub-
  1621. directories of it. For other files, use an absolute path."
  1622. :group 'org-link
  1623. :type '(choice
  1624. (const relative)
  1625. (const absolute)
  1626. (const noabbrev)
  1627. (const adaptive)))
  1628. (defvaralias 'org-activate-links 'org-highlight-links)
  1629. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1630. "Types of links that should be highlighted in Org files.
  1631. This is a list of symbols, each one of them leading to the
  1632. highlighting of a certain link type.
  1633. You can still open links that are not highlighted.
  1634. In principle, it does not hurt to turn on highlighting for all
  1635. link types. There may be a small gain when turning off unused
  1636. link types. The types are:
  1637. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1638. angle Links in angular brackets that may contain whitespace like
  1639. <bbdb:Carsten Dominik>.
  1640. plain Plain links in normal text, no whitespace, like http://google.com.
  1641. radio Text that is matched by a radio target, see manual for details.
  1642. tag Tag settings in a headline (link to tag search).
  1643. date Time stamps (link to calendar).
  1644. footnote Footnote labels.
  1645. If you set this variable during an Emacs session, use `org-mode-restart'
  1646. in the Org buffer so that the change takes effect."
  1647. :group 'org-link
  1648. :group 'org-appearance
  1649. :type '(set :greedy t
  1650. (const :tag "Double bracket links" bracket)
  1651. (const :tag "Angular bracket links" angle)
  1652. (const :tag "Plain text links" plain)
  1653. (const :tag "Radio target matches" radio)
  1654. (const :tag "Tags" tag)
  1655. (const :tag "Timestamps" date)
  1656. (const :tag "Footnotes" footnote)))
  1657. (defcustom org-make-link-description-function nil
  1658. "Function to use for generating link descriptions from links.
  1659. This function must take two parameters: the first one is the
  1660. link, the second one is the description generated by
  1661. `org-insert-link'. The function should return the description to
  1662. use."
  1663. :group 'org-link
  1664. :type '(choice (const nil) (function)))
  1665. (defgroup org-link-store nil
  1666. "Options concerning storing links in Org mode."
  1667. :tag "Org Store Link"
  1668. :group 'org-link)
  1669. (defcustom org-url-hexify-p t
  1670. "When non-nil, hexify URL when creating a link."
  1671. :type 'boolean
  1672. :version "24.3"
  1673. :group 'org-link-store)
  1674. (defcustom org-email-link-description-format "Email %c: %.30s"
  1675. "Format of the description part of a link to an email or usenet message.
  1676. The following %-escapes will be replaced by corresponding information:
  1677. %F full \"From\" field
  1678. %f name, taken from \"From\" field, address if no name
  1679. %T full \"To\" field
  1680. %t first name in \"To\" field, address if no name
  1681. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1682. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1683. %s subject
  1684. %d date
  1685. %m message-id.
  1686. You may use normal field width specification between the % and the letter.
  1687. This is for example useful to limit the length of the subject.
  1688. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1689. :group 'org-link-store
  1690. :type 'string)
  1691. (defcustom org-from-is-user-regexp
  1692. (let (r1 r2)
  1693. (when (and user-mail-address (not (string= user-mail-address "")))
  1694. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1695. (when (and user-full-name (not (string= user-full-name "")))
  1696. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1697. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1698. "Regexp matched against the \"From:\" header of an email or usenet message.
  1699. It should match if the message is from the user him/herself."
  1700. :group 'org-link-store
  1701. :type 'regexp)
  1702. (defcustom org-context-in-file-links t
  1703. "Non-nil means file links from `org-store-link' contain context.
  1704. \\<org-mode-map>
  1705. A search string will be added to the file name with :: as separator
  1706. and used to find the context when the link is activated by the command
  1707. `org-open-at-point'. When this option is t, the entire active region
  1708. will be placed in the search string of the file link. If set to a
  1709. positive integer, only the first n lines of context will be stored.
  1710. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1711. \\[org-store-link]')
  1712. negates this setting for the duration of the command."
  1713. :group 'org-link-store
  1714. :type '(choice boolean integer))
  1715. (defcustom org-keep-stored-link-after-insertion nil
  1716. "Non-nil means keep link in list for entire session.
  1717. \\<org-mode-map>
  1718. The command `org-store-link' adds a link pointing to the current
  1719. location to an internal list. These links accumulate during a session.
  1720. The command `org-insert-link' can be used to insert links into any
  1721. Org file (offering completion for all stored links).
  1722. When this option is nil, every link which has been inserted once using
  1723. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1724. unused
  1725. links more efficient."
  1726. :group 'org-link-store
  1727. :type 'boolean)
  1728. (defgroup org-link-follow nil
  1729. "Options concerning following links in Org mode."
  1730. :tag "Org Follow Link"
  1731. :group 'org-link)
  1732. (defcustom org-link-translation-function nil
  1733. "Function to translate links with different syntax to Org syntax.
  1734. This can be used to translate links created for example by the Planner
  1735. or emacs-wiki packages to Org syntax.
  1736. The function must accept two parameters, a TYPE containing the link
  1737. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1738. which is everything after the link protocol. It should return a cons
  1739. with possibly modified values of type and path.
  1740. Org contains a function for this, so if you set this variable to
  1741. `org-translate-link-from-planner', you should be able follow many
  1742. links created by planner."
  1743. :group 'org-link-follow
  1744. :type '(choice (const nil) (function)))
  1745. (defcustom org-follow-link-hook nil
  1746. "Hook that is run after a link has been followed."
  1747. :group 'org-link-follow
  1748. :type 'hook)
  1749. (defcustom org-tab-follows-link nil
  1750. "Non-nil means on links TAB will follow the link.
  1751. Needs to be set before org.el is loaded.
  1752. This really should not be used, it does not make sense, and the
  1753. implementation is bad."
  1754. :group 'org-link-follow
  1755. :type 'boolean)
  1756. (defcustom org-return-follows-link nil
  1757. "Non-nil means on links RET will follow the link.
  1758. In tables, the special behavior of RET has precedence."
  1759. :group 'org-link-follow
  1760. :type 'boolean)
  1761. (defcustom org-mouse-1-follows-link
  1762. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1763. "Non-nil means mouse-1 on a link will follow the link.
  1764. A longer mouse click will still set point. Needs to be set
  1765. before org.el is loaded."
  1766. :group 'org-link-follow
  1767. :version "26.1"
  1768. :package-version '(Org . "8.3")
  1769. :type '(choice
  1770. (const :tag "A double click follows the link" double)
  1771. (const :tag "Unconditionally follow the link with mouse-1" t)
  1772. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1773. (defcustom org-mark-ring-length 4
  1774. "Number of different positions to be recorded in the ring.
  1775. Changing this requires a restart of Emacs to work correctly."
  1776. :group 'org-link-follow
  1777. :type 'integer)
  1778. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1779. "Non-nil means internal fuzzy links can only match headlines.
  1780. When nil, the a fuzzy link may point to a target or a named
  1781. construct in the document. When set to the special value
  1782. `query-to-create', offer to create a new headline when none
  1783. matched.
  1784. Spaces and statistics cookies are ignored during heading searches."
  1785. :group 'org-link-follow
  1786. :version "24.1"
  1787. :type '(choice
  1788. (const :tag "Use fuzzy text search" nil)
  1789. (const :tag "Match only exact headline" t)
  1790. (const :tag "Match exact headline or query to create it"
  1791. query-to-create))
  1792. :safe #'symbolp)
  1793. (defcustom org-link-frame-setup
  1794. '((vm . vm-visit-folder-other-frame)
  1795. (vm-imap . vm-visit-imap-folder-other-frame)
  1796. (gnus . org-gnus-no-new-news)
  1797. (file . find-file-other-window)
  1798. (wl . wl-other-frame))
  1799. "Setup the frame configuration for following links.
  1800. When following a link with Emacs, it may often be useful to display
  1801. this link in another window or frame. This variable can be used to
  1802. set this up for the different types of links.
  1803. For VM, use any of
  1804. `vm-visit-folder'
  1805. `vm-visit-folder-other-window'
  1806. `vm-visit-folder-other-frame'
  1807. For Gnus, use any of
  1808. `gnus'
  1809. `gnus-other-frame'
  1810. `org-gnus-no-new-news'
  1811. For FILE, use any of
  1812. `find-file'
  1813. `find-file-other-window'
  1814. `find-file-other-frame'
  1815. For Wanderlust use any of
  1816. `wl'
  1817. `wl-other-frame'
  1818. For the calendar, use the variable `calendar-setup'.
  1819. For BBDB, it is currently only possible to display the matches in
  1820. another window."
  1821. :group 'org-link-follow
  1822. :type '(list
  1823. (cons (const vm)
  1824. (choice
  1825. (const vm-visit-folder)
  1826. (const vm-visit-folder-other-window)
  1827. (const vm-visit-folder-other-frame)))
  1828. (cons (const vm-imap)
  1829. (choice
  1830. (const vm-visit-imap-folder)
  1831. (const vm-visit-imap-folder-other-window)
  1832. (const vm-visit-imap-folder-other-frame)))
  1833. (cons (const gnus)
  1834. (choice
  1835. (const gnus)
  1836. (const gnus-other-frame)
  1837. (const org-gnus-no-new-news)))
  1838. (cons (const file)
  1839. (choice
  1840. (const find-file)
  1841. (const find-file-other-window)
  1842. (const find-file-other-frame)))
  1843. (cons (const wl)
  1844. (choice
  1845. (const wl)
  1846. (const wl-other-frame)))))
  1847. (defcustom org-display-internal-link-with-indirect-buffer nil
  1848. "Non-nil means use indirect buffer to display infile links.
  1849. Activating internal links (from one location in a file to another location
  1850. in the same file) normally just jumps to the location. When the link is
  1851. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1852. is displayed in
  1853. another window. When this option is set, the other window actually displays
  1854. an indirect buffer clone of the current buffer, to avoid any visibility
  1855. changes to the current buffer."
  1856. :group 'org-link-follow
  1857. :type 'boolean)
  1858. (defcustom org-open-non-existing-files nil
  1859. "Non-nil means `org-open-file' will open non-existing files.
  1860. When nil, an error will be generated.
  1861. This variable applies only to external applications because they
  1862. might choke on non-existing files. If the link is to a file that
  1863. will be opened in Emacs, the variable is ignored."
  1864. :group 'org-link-follow
  1865. :type 'boolean)
  1866. (defcustom org-open-directory-means-index-dot-org nil
  1867. "Non-nil means a link to a directory really means to index.org.
  1868. When nil, following a directory link will run dired or open a finder/explorer
  1869. window on that directory."
  1870. :group 'org-link-follow
  1871. :type 'boolean)
  1872. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1873. "Non-nil means ask for confirmation before executing shell links.
  1874. Shell links can be dangerous: just think about a link
  1875. [[shell:rm -rf ~/*][Google Search]]
  1876. This link would show up in your Org document as \"Google Search\",
  1877. but really it would remove your entire home directory.
  1878. Therefore we advise against setting this variable to nil.
  1879. Just change it to `y-or-n-p' if you want to confirm with a
  1880. single keystroke rather than having to type \"yes\"."
  1881. :group 'org-link-follow
  1882. :type '(choice
  1883. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1884. (const :tag "with y-or-n (faster)" y-or-n-p)
  1885. (const :tag "no confirmation (dangerous)" nil)))
  1886. (put 'org-confirm-shell-link-function
  1887. 'safe-local-variable
  1888. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1889. (defcustom org-confirm-shell-link-not-regexp ""
  1890. "A regexp to skip confirmation for shell links."
  1891. :group 'org-link-follow
  1892. :version "24.1"
  1893. :type 'regexp)
  1894. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1895. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1896. Elisp links can be dangerous: just think about a link
  1897. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1898. This link would show up in your Org document as \"Google Search\",
  1899. but really it would remove your entire home directory.
  1900. Therefore we advise against setting this variable to nil.
  1901. Just change it to `y-or-n-p' if you want to confirm with a
  1902. single keystroke rather than having to type \"yes\"."
  1903. :group 'org-link-follow
  1904. :type '(choice
  1905. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1906. (const :tag "with y-or-n (faster)" y-or-n-p)
  1907. (const :tag "no confirmation (dangerous)" nil)))
  1908. (put 'org-confirm-shell-link-function
  1909. 'safe-local-variable
  1910. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1911. (defcustom org-confirm-elisp-link-not-regexp ""
  1912. "A regexp to skip confirmation for Elisp links."
  1913. :group 'org-link-follow
  1914. :version "24.1"
  1915. :type 'regexp)
  1916. (defconst org-file-apps-defaults-gnu
  1917. '((remote . emacs)
  1918. (system . mailcap)
  1919. (t . mailcap))
  1920. "Default file applications on a UNIX or GNU/Linux system.
  1921. See `org-file-apps'.")
  1922. (defconst org-file-apps-defaults-macosx
  1923. '((remote . emacs)
  1924. (system . "open %s")
  1925. ("ps.gz" . "gv %s")
  1926. ("eps.gz" . "gv %s")
  1927. ("dvi" . "xdvi %s")
  1928. ("fig" . "xfig %s")
  1929. (t . "open %s"))
  1930. "Default file applications on a macOS system.
  1931. The system \"open\" is known as a default, but we use X11 applications
  1932. for some files for which the OS does not have a good default.
  1933. See `org-file-apps'.")
  1934. (defconst org-file-apps-defaults-windowsnt
  1935. (list '(remote . emacs)
  1936. (cons 'system (lambda (file _path)
  1937. (with-no-warnings (w32-shell-execute "open" file))))
  1938. (cons t (lambda (file _path)
  1939. (with-no-warnings (w32-shell-execute "open" file)))))
  1940. "Default file applications on a Windows NT system.
  1941. The system \"open\" is used for most files.
  1942. See `org-file-apps'.")
  1943. (defcustom org-file-apps
  1944. '((auto-mode . emacs)
  1945. ("\\.mm\\'" . default)
  1946. ("\\.x?html?\\'" . default)
  1947. ("\\.pdf\\'" . default))
  1948. "External applications for opening `file:path' items in a document.
  1949. \\<org-mode-map>\
  1950. Org mode uses system defaults for different file types, but
  1951. you can use this variable to set the application for a given file
  1952. extension. The entries in this list are cons cells where the car identifies
  1953. files and the cdr the corresponding command.
  1954. Possible values for the file identifier are:
  1955. \"string\" A string as a file identifier can be interpreted in different
  1956. ways, depending on its contents:
  1957. - Alphanumeric characters only:
  1958. Match links with this file extension.
  1959. Example: (\"pdf\" . \"evince %s\")
  1960. to open PDFs with evince.
  1961. - Regular expression: Match links where the
  1962. filename matches the regexp. If you want to
  1963. use groups here, use shy groups.
  1964. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1965. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1966. to open *.html and *.xhtml with firefox.
  1967. - Regular expression which contains (non-shy) groups:
  1968. Match links where the whole link, including \"::\", and
  1969. anything after that, matches the regexp.
  1970. In a custom command string, %1, %2, etc. are replaced with
  1971. the parts of the link that were matched by the groups.
  1972. For backwards compatibility, if a command string is given
  1973. that does not use any of the group matches, this case is
  1974. handled identically to the second one (i.e. match against
  1975. file name only).
  1976. In a custom function, you can access the group matches with
  1977. (match-string n link).
  1978. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1979. \"evince -p %1 %s\")
  1980. to open [[file:document.pdf::5]] with evince at page 5.
  1981. `directory' Matches a directory
  1982. `remote' Matches a remote file, accessible through tramp or efs.
  1983. Remote files most likely should be visited through Emacs
  1984. because external applications cannot handle such paths.
  1985. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1986. so all files Emacs knows how to handle. Using this with
  1987. command `emacs' will open most files in Emacs. Beware that this
  1988. will also open html files inside Emacs, unless you add
  1989. (\"html\" . default) to the list as well.
  1990. `system' The system command to open files, like `open' on Windows
  1991. and macOS, and mailcap under GNU/Linux. This is the command
  1992. that will be selected if you call `org-open-at-point' with a
  1993. double prefix argument (`\\[universal-argument] \
  1994. \\[universal-argument] \\[org-open-at-point]').
  1995. t Default for files not matched by any of the other options.
  1996. Possible values for the command are:
  1997. `emacs' The file will be visited by the current Emacs process.
  1998. `default' Use the default application for this file type, which is the
  1999. association for t in the list, most likely in the system-specific
  2000. part. This can be used to overrule an unwanted setting in the
  2001. system-specific variable.
  2002. `system' Use the system command for opening files, like \"open\".
  2003. This command is specified by the entry whose car is `system'.
  2004. Most likely, the system-specific version of this variable
  2005. does define this command, but you can overrule/replace it
  2006. here.
  2007. `mailcap' Use command specified in the mailcaps.
  2008. string A command to be executed by a shell; %s will be replaced
  2009. by the path to the file.
  2010. function A Lisp function, which will be called with two arguments:
  2011. the file path and the original link string, without the
  2012. \"file:\" prefix.
  2013. For more examples, see the system specific constants
  2014. `org-file-apps-defaults-macosx'
  2015. `org-file-apps-defaults-windowsnt'
  2016. `org-file-apps-defaults-gnu'."
  2017. :group 'org-link-follow
  2018. :type '(repeat
  2019. (cons (choice :value ""
  2020. (string :tag "Extension")
  2021. (const :tag "System command to open files" system)
  2022. (const :tag "Default for unrecognized files" t)
  2023. (const :tag "Remote file" remote)
  2024. (const :tag "Links to a directory" directory)
  2025. (const :tag "Any files that have Emacs modes"
  2026. auto-mode))
  2027. (choice :value ""
  2028. (const :tag "Visit with Emacs" emacs)
  2029. (const :tag "Use default" default)
  2030. (const :tag "Use the system command" system)
  2031. (string :tag "Command")
  2032. (function :tag "Function")))))
  2033. (defcustom org-doi-server-url "http://dx.doi.org/"
  2034. "The URL of the DOI server."
  2035. :type 'string
  2036. :version "24.3"
  2037. :group 'org-link-follow)
  2038. (defgroup org-refile nil
  2039. "Options concerning refiling entries in Org mode."
  2040. :tag "Org Refile"
  2041. :group 'org)
  2042. (defcustom org-directory "~/org"
  2043. "Directory with Org files.
  2044. This is just a default location to look for Org files. There is no need
  2045. at all to put your files into this directory. It is used in the
  2046. following situations:
  2047. 1. When a capture template specifies a target file that is not an
  2048. absolute path. The path will then be interpreted relative to
  2049. `org-directory'
  2050. 2. When the value of variable `org-agenda-files' is a single file, any
  2051. relative paths in this file will be taken as relative to
  2052. `org-directory'."
  2053. :group 'org-refile
  2054. :group 'org-capture
  2055. :type 'directory)
  2056. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2057. "Default target for storing notes.
  2058. Used as a fall back file for org-capture.el, for templates that
  2059. do not specify a target file."
  2060. :group 'org-refile
  2061. :group 'org-capture
  2062. :type 'file)
  2063. (defcustom org-goto-interface 'outline
  2064. "The default interface to be used for `org-goto'.
  2065. Allowed values are:
  2066. outline The interface shows an outline of the relevant file
  2067. and the correct heading is found by moving through
  2068. the outline or by searching with incremental search.
  2069. outline-path-completion Headlines in the current buffer are offered via
  2070. completion. This is the interface also used by
  2071. the refile command."
  2072. :group 'org-refile
  2073. :type '(choice
  2074. (const :tag "Outline" outline)
  2075. (const :tag "Outline-path-completion" outline-path-completion)))
  2076. (defcustom org-goto-max-level 5
  2077. "Maximum target level when running `org-goto' with refile interface."
  2078. :group 'org-refile
  2079. :type 'integer)
  2080. (defcustom org-reverse-note-order nil
  2081. "Non-nil means store new notes at the beginning of a file or entry.
  2082. When nil, new notes will be filed to the end of a file or entry.
  2083. This can also be a list with cons cells of regular expressions that
  2084. are matched against file names, and values."
  2085. :group 'org-capture
  2086. :group 'org-refile
  2087. :type '(choice
  2088. (const :tag "Reverse always" t)
  2089. (const :tag "Reverse never" nil)
  2090. (repeat :tag "By file name regexp"
  2091. (cons regexp boolean))))
  2092. (defcustom org-log-refile nil
  2093. "Information to record when a task is refiled.
  2094. Possible values are:
  2095. nil Don't add anything
  2096. time Add a time stamp to the task
  2097. note Prompt for a note and add it with template `org-log-note-headings'
  2098. This option can also be set with on a per-file-basis with
  2099. #+STARTUP: nologrefile
  2100. #+STARTUP: logrefile
  2101. #+STARTUP: lognoterefile
  2102. You can have local logging settings for a subtree by setting the LOGGING
  2103. property to one or more of these keywords.
  2104. When bulk-refiling from the agenda, the value `note' is forbidden and
  2105. will temporarily be changed to `time'."
  2106. :group 'org-refile
  2107. :group 'org-progress
  2108. :version "24.1"
  2109. :type '(choice
  2110. (const :tag "No logging" nil)
  2111. (const :tag "Record timestamp" time)
  2112. (const :tag "Record timestamp with note." note)))
  2113. (defcustom org-refile-targets nil
  2114. "Targets for refiling entries with `\\[org-refile]'.
  2115. This is a list of cons cells. Each cell contains:
  2116. - a specification of the files to be considered, either a list of files,
  2117. or a symbol whose function or variable value will be used to retrieve
  2118. a file name or a list of file names. If you use `org-agenda-files' for
  2119. that, all agenda files will be scanned for targets. Nil means consider
  2120. headings in the current buffer.
  2121. - A specification of how to find candidate refile targets. This may be
  2122. any of:
  2123. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2124. This tag has to be present in all target headlines, inheritance will
  2125. not be considered.
  2126. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2127. todo keyword.
  2128. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2129. headlines that are refiling targets.
  2130. - a cons cell (:level . N). Any headline of level N is considered a target.
  2131. Note that, when `org-odd-levels-only' is set, level corresponds to
  2132. order in hierarchy, not to the number of stars.
  2133. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2134. Note that, when `org-odd-levels-only' is set, level corresponds to
  2135. order in hierarchy, not to the number of stars.
  2136. Each element of this list generates a set of possible targets.
  2137. The union of these sets is presented (with completion) to
  2138. the user by `org-refile'.
  2139. You can set the variable `org-refile-target-verify-function' to a function
  2140. to verify each headline found by the simple criteria above.
  2141. When this variable is nil, all top-level headlines in the current buffer
  2142. are used, equivalent to the value `((nil . (:level . 1))'."
  2143. :group 'org-refile
  2144. :type '(repeat
  2145. (cons
  2146. (choice :value org-agenda-files
  2147. (const :tag "All agenda files" org-agenda-files)
  2148. (const :tag "Current buffer" nil)
  2149. (function) (variable) (file))
  2150. (choice :tag "Identify target headline by"
  2151. (cons :tag "Specific tag" (const :value :tag) (string))
  2152. (cons :tag "TODO keyword" (const :value :todo) (string))
  2153. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2154. (cons :tag "Level number" (const :value :level) (integer))
  2155. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2156. (defcustom org-refile-target-verify-function nil
  2157. "Function to verify if the headline at point should be a refile target.
  2158. The function will be called without arguments, with point at the
  2159. beginning of the headline. It should return t and leave point
  2160. where it is if the headline is a valid target for refiling.
  2161. If the target should not be selected, the function must return nil.
  2162. In addition to this, it may move point to a place from where the search
  2163. should be continued. For example, the function may decide that the entire
  2164. subtree of the current entry should be excluded and move point to the end
  2165. of the subtree."
  2166. :group 'org-refile
  2167. :type '(choice
  2168. (const nil)
  2169. (function)))
  2170. (defcustom org-refile-use-cache nil
  2171. "Non-nil means cache refile targets to speed up the process.
  2172. \\<org-mode-map>\
  2173. The cache for a particular file will be updated automatically when
  2174. the buffer has been killed, or when any of the marker used for flagging
  2175. refile targets no longer points at a live buffer.
  2176. If you have added new entries to a buffer that might themselves be targets,
  2177. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2178. if you find that easier, \
  2179. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2180. \\[org-refile]'."
  2181. :group 'org-refile
  2182. :version "24.1"
  2183. :type 'boolean)
  2184. (defcustom org-refile-use-outline-path nil
  2185. "Non-nil means provide refile targets as paths.
  2186. So a level 3 headline will be available as level1/level2/level3.
  2187. When the value is `file', also include the file name (without directory)
  2188. into the path. In this case, you can also stop the completion after
  2189. the file name, to get entries inserted as top level in the file.
  2190. When `full-file-path', include the full file path.
  2191. When `buffer-name', use the buffer name."
  2192. :group 'org-refile
  2193. :type '(choice
  2194. (const :tag "Not" nil)
  2195. (const :tag "Yes" t)
  2196. (const :tag "Start with file name" file)
  2197. (const :tag "Start with full file path" full-file-path)
  2198. (const :tag "Start with buffer name" buffer-name)))
  2199. (defcustom org-outline-path-complete-in-steps t
  2200. "Non-nil means complete the outline path in hierarchical steps.
  2201. When Org uses the refile interface to select an outline path (see
  2202. `org-refile-use-outline-path'), the completion of the path can be
  2203. done in a single go, or it can be done in steps down the headline
  2204. hierarchy. Going in steps is probably the best if you do not use
  2205. a special completion package like `ido' or `icicles'. However,
  2206. when using these packages, going in one step can be very fast,
  2207. while still showing the whole path to the entry."
  2208. :group 'org-refile
  2209. :type 'boolean)
  2210. (defcustom org-refile-allow-creating-parent-nodes nil
  2211. "Non-nil means allow the creation of new nodes as refile targets.
  2212. New nodes are then created by adding \"/new node name\" to the completion
  2213. of an existing node. When the value of this variable is `confirm',
  2214. new node creation must be confirmed by the user (recommended).
  2215. When nil, the completion must match an existing entry.
  2216. Note that, if the new heading is not seen by the criteria
  2217. listed in `org-refile-targets', multiple instances of the same
  2218. heading would be created by trying again to file under the new
  2219. heading."
  2220. :group 'org-refile
  2221. :type '(choice
  2222. (const :tag "Never" nil)
  2223. (const :tag "Always" t)
  2224. (const :tag "Prompt for confirmation" confirm)))
  2225. (defcustom org-refile-active-region-within-subtree nil
  2226. "Non-nil means also refile active region within a subtree.
  2227. By default `org-refile' doesn't allow refiling regions if they
  2228. don't contain a set of subtrees, but it might be convenient to
  2229. do so sometimes: in that case, the first line of the region is
  2230. converted to a headline before refiling."
  2231. :group 'org-refile
  2232. :version "24.1"
  2233. :type 'boolean)
  2234. (defgroup org-todo nil
  2235. "Options concerning TODO items in Org mode."
  2236. :tag "Org TODO"
  2237. :group 'org)
  2238. (defgroup org-progress nil
  2239. "Options concerning Progress logging in Org mode."
  2240. :tag "Org Progress"
  2241. :group 'org-time)
  2242. (defvar org-todo-interpretation-widgets
  2243. '((:tag "Sequence (cycling hits every state)" sequence)
  2244. (:tag "Type (cycling directly to DONE)" type))
  2245. "The available interpretation symbols for customizing `org-todo-keywords'.
  2246. Interested libraries should add to this list.")
  2247. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2248. "List of TODO entry keyword sequences and their interpretation.
  2249. \\<org-mode-map>This is a list of sequences.
  2250. Each sequence starts with a symbol, either `sequence' or `type',
  2251. indicating if the keywords should be interpreted as a sequence of
  2252. action steps, or as different types of TODO items. The first
  2253. keywords are states requiring action - these states will select a headline
  2254. for inclusion into the global TODO list Org produces. If one of the
  2255. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2256. signify that no further action is necessary. If \"|\" is not found,
  2257. the last keyword is treated as the only DONE state of the sequence.
  2258. The command `\\[org-todo]' cycles an entry through these states, and one
  2259. additional state where no keyword is present. For details about this
  2260. cycling, see the manual.
  2261. TODO keywords and interpretation can also be set on a per-file basis with
  2262. the special #+SEQ_TODO and #+TYP_TODO lines.
  2263. Each keyword can optionally specify a character for fast state selection
  2264. \(in combination with the variable `org-use-fast-todo-selection')
  2265. and specifiers for state change logging, using the same syntax that
  2266. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2267. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2268. indicates to record a time stamp each time this state is selected.
  2269. Each keyword may also specify if a timestamp or a note should be
  2270. recorded when entering or leaving the state, by adding additional
  2271. characters in the parenthesis after the keyword. This looks like this:
  2272. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2273. record only the time of the state change. With X and Y being either
  2274. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2275. Y when leaving the state if and only if the *target* state does not
  2276. define X. You may omit any of the fast-selection key or X or /Y,
  2277. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2278. For backward compatibility, this variable may also be just a list
  2279. of keywords. In this case the interpretation (sequence or type) will be
  2280. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2281. :group 'org-todo
  2282. :group 'org-keywords
  2283. :type '(choice
  2284. (repeat :tag "Old syntax, just keywords"
  2285. (string :tag "Keyword"))
  2286. (repeat :tag "New syntax"
  2287. (cons
  2288. (choice
  2289. :tag "Interpretation"
  2290. ;;Quick and dirty way to see
  2291. ;;`org-todo-interpretations'. This takes the
  2292. ;;place of item arguments
  2293. :convert-widget
  2294. (lambda (widget)
  2295. (widget-put widget
  2296. :args (mapcar
  2297. (lambda (x)
  2298. (widget-convert
  2299. (cons 'const x)))
  2300. org-todo-interpretation-widgets))
  2301. widget))
  2302. (repeat
  2303. (string :tag "Keyword"))))))
  2304. (defvar-local org-todo-keywords-1 nil
  2305. "All TODO and DONE keywords active in a buffer.")
  2306. (defvar org-todo-keywords-for-agenda nil)
  2307. (defvar org-done-keywords-for-agenda nil)
  2308. (defvar org-todo-keyword-alist-for-agenda nil)
  2309. (defvar org-tag-alist-for-agenda nil
  2310. "Alist of all tags from all agenda files.")
  2311. (defvar org-tag-groups-alist-for-agenda nil
  2312. "Alist of all groups tags from all current agenda files.")
  2313. (defvar-local org-tag-groups-alist nil)
  2314. (defvar org-agenda-contributing-files nil)
  2315. (defvar-local org-current-tag-alist nil
  2316. "Alist of all tag groups in current buffer.
  2317. This variable takes into consideration `org-tag-alist',
  2318. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2319. (defvar-local org-not-done-keywords nil)
  2320. (defvar-local org-done-keywords nil)
  2321. (defvar-local org-todo-heads nil)
  2322. (defvar-local org-todo-sets nil)
  2323. (defvar-local org-todo-log-states nil)
  2324. (defvar-local org-todo-kwd-alist nil)
  2325. (defvar-local org-todo-key-alist nil)
  2326. (defvar-local org-todo-key-trigger nil)
  2327. (defcustom org-todo-interpretation 'sequence
  2328. "Controls how TODO keywords are interpreted.
  2329. This variable is in principle obsolete and is only used for
  2330. backward compatibility, if the interpretation of todo keywords is
  2331. not given already in `org-todo-keywords'. See that variable for
  2332. more information."
  2333. :group 'org-todo
  2334. :group 'org-keywords
  2335. :type '(choice (const sequence)
  2336. (const type)))
  2337. (defcustom org-use-fast-todo-selection t
  2338. "\\<org-mode-map>\
  2339. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2340. This variable describes if and under what circumstances the cycling
  2341. mechanism for TODO keywords will be replaced by a single-key, direct
  2342. selection scheme.
  2343. When nil, fast selection is never used.
  2344. When the symbol `prefix', it will be used when `org-todo' is called
  2345. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2346. in an Org buffer, and
  2347. `\\[universal-argument] t' in an agenda buffer.
  2348. When t, fast selection is used by default. In this case, the prefix
  2349. argument forces cycling instead.
  2350. In all cases, the special interface is only used if access keys have
  2351. actually been assigned by the user, i.e. if keywords in the configuration
  2352. are followed by a letter in parenthesis, like TODO(t)."
  2353. :group 'org-todo
  2354. :type '(choice
  2355. (const :tag "Never" nil)
  2356. (const :tag "By default" t)
  2357. (const :tag "Only with C-u C-c C-t" prefix)))
  2358. (defcustom org-provide-todo-statistics t
  2359. "Non-nil means update todo statistics after insert and toggle.
  2360. ALL-HEADLINES means update todo statistics by including headlines
  2361. with no TODO keyword as well, counting them as not done.
  2362. A list of TODO keywords means the same, but skip keywords that are
  2363. not in this list.
  2364. When set to a list of two lists, the first list contains keywords
  2365. to consider as TODO keywords, the second list contains keywords
  2366. to consider as DONE keywords.
  2367. When this is set, todo statistics is updated in the parent of the
  2368. current entry each time a todo state is changed."
  2369. :group 'org-todo
  2370. :type '(choice
  2371. (const :tag "Yes, only for TODO entries" t)
  2372. (const :tag "Yes, including all entries" all-headlines)
  2373. (repeat :tag "Yes, for TODOs in this list"
  2374. (string :tag "TODO keyword"))
  2375. (list :tag "Yes, for TODOs and DONEs in these lists"
  2376. (repeat (string :tag "TODO keyword"))
  2377. (repeat (string :tag "DONE keyword")))
  2378. (other :tag "No TODO statistics" nil)))
  2379. (defcustom org-hierarchical-todo-statistics t
  2380. "Non-nil means TODO statistics covers just direct children.
  2381. When nil, all entries in the subtree are considered.
  2382. This has only an effect if `org-provide-todo-statistics' is set.
  2383. To set this to nil for only a single subtree, use a COOKIE_DATA
  2384. property and include the word \"recursive\" into the value."
  2385. :group 'org-todo
  2386. :type 'boolean)
  2387. (defcustom org-after-todo-state-change-hook nil
  2388. "Hook which is run after the state of a TODO item was changed.
  2389. The new state (a string with a TODO keyword, or nil) is available in the
  2390. Lisp variable `org-state'."
  2391. :group 'org-todo
  2392. :type 'hook)
  2393. (defvar org-blocker-hook nil
  2394. "Hook for functions that are allowed to block a state change.
  2395. Functions in this hook should not modify the buffer.
  2396. Each function gets as its single argument a property list,
  2397. see `org-trigger-hook' for more information about this list.
  2398. If any of the functions in this hook returns nil, the state change
  2399. is blocked.")
  2400. (defvar org-trigger-hook nil
  2401. "Hook for functions that are triggered by a state change.
  2402. Each function gets as its single argument a property list with at
  2403. least the following elements:
  2404. (:type type-of-change :position pos-at-entry-start
  2405. :from old-state :to new-state)
  2406. Depending on the type, more properties may be present.
  2407. This mechanism is currently implemented for:
  2408. TODO state changes
  2409. ------------------
  2410. :type todo-state-change
  2411. :from previous state (keyword as a string), or nil, or a symbol
  2412. `todo' or `done', to indicate the general type of state.
  2413. :to new state, like in :from")
  2414. (defcustom org-enforce-todo-dependencies nil
  2415. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2416. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2417. be blocked if any prior sibling is not yet done.
  2418. Finally, if the parent is blocked because of ordered siblings of its own,
  2419. the child will also be blocked."
  2420. :set (lambda (var val)
  2421. (set var val)
  2422. (if val
  2423. (add-hook 'org-blocker-hook
  2424. 'org-block-todo-from-children-or-siblings-or-parent)
  2425. (remove-hook 'org-blocker-hook
  2426. 'org-block-todo-from-children-or-siblings-or-parent)))
  2427. :group 'org-todo
  2428. :type 'boolean)
  2429. (defcustom org-enforce-todo-checkbox-dependencies nil
  2430. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2431. When this is nil, checkboxes have no influence on switching TODO states.
  2432. When non-nil, you first need to check off all check boxes before the TODO
  2433. entry can be switched to DONE.
  2434. This variable needs to be set before org.el is loaded, and you need to
  2435. restart Emacs after a change to make the change effective. The only way
  2436. to change is while Emacs is running is through the customize interface."
  2437. :set (lambda (var val)
  2438. (set var val)
  2439. (if val
  2440. (add-hook 'org-blocker-hook
  2441. 'org-block-todo-from-checkboxes)
  2442. (remove-hook 'org-blocker-hook
  2443. 'org-block-todo-from-checkboxes)))
  2444. :group 'org-todo
  2445. :type 'boolean)
  2446. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2447. "Non-nil means inserting a TODO heading is treated as state change.
  2448. So when the command `\\[org-insert-todo-heading]' is used, state change
  2449. logging will apply if appropriate. When nil, the new TODO item will
  2450. be inserted directly, and no logging will take place."
  2451. :group 'org-todo
  2452. :type 'boolean)
  2453. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2454. "Non-nil means switching TODO states with S-cursor counts as state change.
  2455. This is the default behavior. However, setting this to nil allows a
  2456. convenient way to select a TODO state and bypass any logging associated
  2457. with that."
  2458. :group 'org-todo
  2459. :type 'boolean)
  2460. (defcustom org-todo-state-tags-triggers nil
  2461. "Tag changes that should be triggered by TODO state changes.
  2462. This is a list. Each entry is
  2463. (state-change (tag . flag) .......)
  2464. State-change can be a string with a state, and empty string to indicate the
  2465. state that has no TODO keyword, or it can be one of the symbols `todo'
  2466. or `done', meaning any not-done or done state, respectively."
  2467. :group 'org-todo
  2468. :group 'org-tags
  2469. :type '(repeat
  2470. (cons (choice :tag "When changing to"
  2471. (const :tag "Not-done state" todo)
  2472. (const :tag "Done state" done)
  2473. (string :tag "State"))
  2474. (repeat
  2475. (cons :tag "Tag action"
  2476. (string :tag "Tag")
  2477. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2478. (defcustom org-log-done nil
  2479. "Information to record when a task moves to the DONE state.
  2480. Possible values are:
  2481. nil Don't add anything, just change the keyword
  2482. time Add a time stamp to the task
  2483. note Prompt for a note and add it with template `org-log-note-headings'
  2484. This option can also be set with on a per-file-basis with
  2485. #+STARTUP: nologdone
  2486. #+STARTUP: logdone
  2487. #+STARTUP: lognotedone
  2488. You can have local logging settings for a subtree by setting the LOGGING
  2489. property to one or more of these keywords."
  2490. :group 'org-todo
  2491. :group 'org-progress
  2492. :type '(choice
  2493. (const :tag "No logging" nil)
  2494. (const :tag "Record CLOSED timestamp" time)
  2495. (const :tag "Record CLOSED timestamp with note." note)))
  2496. ;; Normalize old uses of org-log-done.
  2497. (cond
  2498. ((eq org-log-done t) (setq org-log-done 'time))
  2499. ((and (listp org-log-done) (memq 'done org-log-done))
  2500. (setq org-log-done 'note)))
  2501. (defcustom org-log-reschedule nil
  2502. "Information to record when the scheduling date of a tasks is modified.
  2503. Possible values are:
  2504. nil Don't add anything, just change the date
  2505. time Add a time stamp to the task
  2506. note Prompt for a note and add it with template `org-log-note-headings'
  2507. This option can also be set with on a per-file-basis with
  2508. #+STARTUP: nologreschedule
  2509. #+STARTUP: logreschedule
  2510. #+STARTUP: lognotereschedule"
  2511. :group 'org-todo
  2512. :group 'org-progress
  2513. :type '(choice
  2514. (const :tag "No logging" nil)
  2515. (const :tag "Record timestamp" time)
  2516. (const :tag "Record timestamp with note." note)))
  2517. (defcustom org-log-redeadline nil
  2518. "Information to record when the deadline date of a tasks is modified.
  2519. Possible values are:
  2520. nil Don't add anything, just change the date
  2521. time Add a time stamp to the task
  2522. note Prompt for a note and add it with template `org-log-note-headings'
  2523. This option can also be set with on a per-file-basis with
  2524. #+STARTUP: nologredeadline
  2525. #+STARTUP: logredeadline
  2526. #+STARTUP: lognoteredeadline
  2527. You can have local logging settings for a subtree by setting the LOGGING
  2528. property to one or more of these keywords."
  2529. :group 'org-todo
  2530. :group 'org-progress
  2531. :type '(choice
  2532. (const :tag "No logging" nil)
  2533. (const :tag "Record timestamp" time)
  2534. (const :tag "Record timestamp with note." note)))
  2535. (defcustom org-log-note-clock-out nil
  2536. "Non-nil means record a note when clocking out of an item.
  2537. This can also be configured on a per-file basis by adding one of
  2538. the following lines anywhere in the buffer:
  2539. #+STARTUP: lognoteclock-out
  2540. #+STARTUP: nolognoteclock-out"
  2541. :group 'org-todo
  2542. :group 'org-progress
  2543. :type 'boolean)
  2544. (defcustom org-log-done-with-time t
  2545. "Non-nil means the CLOSED time stamp will contain date and time.
  2546. When nil, only the date will be recorded."
  2547. :group 'org-progress
  2548. :type 'boolean)
  2549. (defcustom org-log-note-headings
  2550. '((done . "CLOSING NOTE %t")
  2551. (state . "State %-12s from %-12S %t")
  2552. (note . "Note taken on %t")
  2553. (reschedule . "Rescheduled from %S on %t")
  2554. (delschedule . "Not scheduled, was %S on %t")
  2555. (redeadline . "New deadline from %S on %t")
  2556. (deldeadline . "Removed deadline, was %S on %t")
  2557. (refile . "Refiled on %t")
  2558. (clock-out . ""))
  2559. "Headings for notes added to entries.
  2560. The value is an alist, with the car being a symbol indicating the
  2561. note context, and the cdr is the heading to be used. The heading
  2562. may also be the empty string. The following placeholders can be
  2563. used:
  2564. %t a time stamp.
  2565. %T an active time stamp instead the default inactive one
  2566. %d a short-format time stamp.
  2567. %D an active short-format time stamp.
  2568. %s the new TODO state or time stamp (inactive), in double quotes.
  2569. %S the old TODO state or time stamp (inactive), in double quotes.
  2570. %u the user name.
  2571. %U full user name.
  2572. In fact, it is not a good idea to change the `state' entry,
  2573. because Agenda Log mode depends on the format of these entries."
  2574. :group 'org-todo
  2575. :group 'org-progress
  2576. :type '(list :greedy t
  2577. (cons (const :tag "Heading when closing an item" done) string)
  2578. (cons (const :tag
  2579. "Heading when changing todo state (todo sequence only)"
  2580. state) string)
  2581. (cons (const :tag "Heading when just taking a note" note) string)
  2582. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2583. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2584. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2585. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2586. (cons (const :tag "Heading when refiling" refile) string)
  2587. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2588. (unless (assq 'note org-log-note-headings)
  2589. (push '(note . "%t") org-log-note-headings))
  2590. (defcustom org-log-into-drawer nil
  2591. "Non-nil means insert state change notes and time stamps into a drawer.
  2592. When nil, state changes notes will be inserted after the headline and
  2593. any scheduling and clock lines, but not inside a drawer.
  2594. The value of this variable should be the name of the drawer to use.
  2595. LOGBOOK is proposed as the default drawer for this purpose, you can
  2596. also set this to a string to define the drawer of your choice.
  2597. A value of t is also allowed, representing \"LOGBOOK\".
  2598. A value of t or nil can also be set with on a per-file-basis with
  2599. #+STARTUP: logdrawer
  2600. #+STARTUP: nologdrawer
  2601. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2602. will be ignored.
  2603. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2604. a subtree.
  2605. Do not check directly this variable in a Lisp program. Call
  2606. function `org-log-into-drawer' instead."
  2607. :group 'org-todo
  2608. :group 'org-progress
  2609. :type '(choice
  2610. (const :tag "Not into a drawer" nil)
  2611. (const :tag "LOGBOOK" t)
  2612. (string :tag "Other")))
  2613. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2614. (defun org-log-into-drawer ()
  2615. "Name of the log drawer, as a string, or nil.
  2616. This is the value of `org-log-into-drawer'. However, if the
  2617. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2618. be used instead of the default value."
  2619. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2620. (cond ((equal p "nil") nil)
  2621. ((equal p "t") "LOGBOOK")
  2622. ((stringp p) p)
  2623. (p "LOGBOOK")
  2624. ((stringp org-log-into-drawer) org-log-into-drawer)
  2625. (org-log-into-drawer "LOGBOOK"))))
  2626. (defcustom org-log-state-notes-insert-after-drawers nil
  2627. "Non-nil means insert state change notes after any drawers in entry.
  2628. Only the drawers that *immediately* follow the headline and the
  2629. deadline/scheduled line are skipped.
  2630. When nil, insert notes right after the heading and perhaps the line
  2631. with deadline/scheduling if present.
  2632. This variable will have no effect if `org-log-into-drawer' is
  2633. set."
  2634. :group 'org-todo
  2635. :group 'org-progress
  2636. :type 'boolean)
  2637. (defcustom org-log-states-order-reversed t
  2638. "Non-nil means the latest state note will be directly after heading.
  2639. When nil, the state change notes will be ordered according to time.
  2640. This option can also be set with on a per-file-basis with
  2641. #+STARTUP: logstatesreversed
  2642. #+STARTUP: nologstatesreversed"
  2643. :group 'org-todo
  2644. :group 'org-progress
  2645. :type 'boolean)
  2646. (defcustom org-todo-repeat-to-state nil
  2647. "The TODO state to which a repeater should return the repeating task.
  2648. By default this is the first task in a TODO sequence, or the previous state
  2649. in a TODO_TYP set. But you can specify another task here.
  2650. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2651. :group 'org-todo
  2652. :version "24.1"
  2653. :type '(choice (const :tag "Head of sequence" nil)
  2654. (string :tag "Specific state")))
  2655. (defcustom org-log-repeat 'time
  2656. "Non-nil means record moving through the DONE state when triggering repeat.
  2657. An auto-repeating task is immediately switched back to TODO when
  2658. marked DONE. If you are not logging state changes (by adding \"@\"
  2659. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2660. record a closing note, there will be no record of the task moving
  2661. through DONE. This variable forces taking a note anyway.
  2662. nil Don't force a record
  2663. time Record a time stamp
  2664. note Prompt for a note and add it with template `org-log-note-headings'
  2665. This option can also be set with on a per-file-basis with
  2666. #+STARTUP: nologrepeat
  2667. #+STARTUP: logrepeat
  2668. #+STARTUP: lognoterepeat
  2669. You can have local logging settings for a subtree by setting the LOGGING
  2670. property to one or more of these keywords."
  2671. :group 'org-todo
  2672. :group 'org-progress
  2673. :type '(choice
  2674. (const :tag "Don't force a record" nil)
  2675. (const :tag "Force recording the DONE state" time)
  2676. (const :tag "Force recording a note with the DONE state" note)))
  2677. (defgroup org-priorities nil
  2678. "Priorities in Org mode."
  2679. :tag "Org Priorities"
  2680. :group 'org-todo)
  2681. (defcustom org-enable-priority-commands t
  2682. "Non-nil means priority commands are active.
  2683. When nil, these commands will be disabled, so that you never accidentally
  2684. set a priority."
  2685. :group 'org-priorities
  2686. :type 'boolean)
  2687. (defcustom org-highest-priority ?A
  2688. "The highest priority of TODO items. A character like ?A, ?B etc.
  2689. Must have a smaller ASCII number than `org-lowest-priority'."
  2690. :group 'org-priorities
  2691. :type 'character)
  2692. (defcustom org-lowest-priority ?C
  2693. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2694. Must have a larger ASCII number than `org-highest-priority'."
  2695. :group 'org-priorities
  2696. :type 'character)
  2697. (defcustom org-default-priority ?B
  2698. "The default priority of TODO items.
  2699. This is the priority an item gets if no explicit priority is given.
  2700. When starting to cycle on an empty priority the first step in the cycle
  2701. depends on `org-priority-start-cycle-with-default'. The resulting first
  2702. step priority must not exceed the range from `org-highest-priority' to
  2703. `org-lowest-priority' which means that `org-default-priority' has to be
  2704. in this range exclusive or inclusive the range boundaries. Else the
  2705. first step refuses to set the default and the second will fall back
  2706. to (depending on the command used) the highest or lowest priority."
  2707. :group 'org-priorities
  2708. :type 'character)
  2709. (defcustom org-priority-start-cycle-with-default t
  2710. "Non-nil means start with default priority when starting to cycle.
  2711. When this is nil, the first step in the cycle will be (depending on the
  2712. command used) one higher or lower than the default priority.
  2713. See also `org-default-priority'."
  2714. :group 'org-priorities
  2715. :type 'boolean)
  2716. (defcustom org-get-priority-function nil
  2717. "Function to extract the priority from a string.
  2718. The string is normally the headline. If this is nil Org computes the
  2719. priority from the priority cookie like [#A] in the headline. It returns
  2720. an integer, increasing by 1000 for each priority level.
  2721. The user can set a different function here, which should take a string
  2722. as an argument and return the numeric priority."
  2723. :group 'org-priorities
  2724. :version "24.1"
  2725. :type '(choice
  2726. (const nil)
  2727. (function)))
  2728. (defgroup org-time nil
  2729. "Options concerning time stamps and deadlines in Org mode."
  2730. :tag "Org Time"
  2731. :group 'org)
  2732. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2733. "Number of minutes to round time stamps to.
  2734. \\<org-mode-map>\
  2735. These are two values, the first applies when first creating a time stamp.
  2736. The second applies when changing it with the commands `S-up' and `S-down'.
  2737. When changing the time stamp, this means that it will change in steps
  2738. of N minutes, as given by the second value.
  2739. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2740. numbers should be factors of 60, so for example 5, 10, 15.
  2741. When this is larger than 1, you can still force an exact time stamp by using
  2742. a double prefix argument to a time stamp command like \
  2743. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2744. and by using a prefix arg to `S-up/down' to specify the exact number
  2745. of minutes to shift."
  2746. :group 'org-time
  2747. :get (lambda (var) ; Make sure both elements are there
  2748. (if (integerp (default-value var))
  2749. (list (default-value var) 5)
  2750. (default-value var)))
  2751. :type '(list
  2752. (integer :tag "when inserting times")
  2753. (integer :tag "when modifying times")))
  2754. ;; Normalize old customizations of this variable.
  2755. (when (integerp org-time-stamp-rounding-minutes)
  2756. (setq org-time-stamp-rounding-minutes
  2757. (list org-time-stamp-rounding-minutes
  2758. org-time-stamp-rounding-minutes)))
  2759. (defcustom org-display-custom-times nil
  2760. "Non-nil means overlay custom formats over all time stamps.
  2761. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2762. To turn this on on a per-file basis, insert anywhere in the file:
  2763. #+STARTUP: customtime"
  2764. :group 'org-time
  2765. :set 'set-default
  2766. :type 'sexp)
  2767. (make-variable-buffer-local 'org-display-custom-times)
  2768. (defcustom org-time-stamp-custom-formats
  2769. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2770. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2771. These are overlaid over the default ISO format if the variable
  2772. `org-display-custom-times' is set. Time like %H:%M should be at the
  2773. end of the second format. The custom formats are also honored by export
  2774. commands, if custom time display is turned on at the time of export."
  2775. :group 'org-time
  2776. :type 'sexp)
  2777. (defun org-time-stamp-format (&optional long inactive)
  2778. "Get the right format for a time string."
  2779. (let ((f (if long (cdr org-time-stamp-formats)
  2780. (car org-time-stamp-formats))))
  2781. (if inactive
  2782. (concat "[" (substring f 1 -1) "]")
  2783. f)))
  2784. (defcustom org-deadline-warning-days 14
  2785. "Number of days before expiration during which a deadline becomes active.
  2786. This variable governs the display in sparse trees and in the agenda.
  2787. When 0 or negative, it means use this number (the absolute value of it)
  2788. even if a deadline has a different individual lead time specified.
  2789. Custom commands can set this variable in the options section."
  2790. :group 'org-time
  2791. :group 'org-agenda-daily/weekly
  2792. :type 'integer)
  2793. (defcustom org-scheduled-delay-days 0
  2794. "Number of days before a scheduled item becomes active.
  2795. This variable governs the display in sparse trees and in the agenda.
  2796. The default value (i.e. 0) means: don't delay scheduled item.
  2797. When negative, it means use this number (the absolute value of it)
  2798. even if a scheduled item has a different individual delay time
  2799. specified.
  2800. Custom commands can set this variable in the options section."
  2801. :group 'org-time
  2802. :group 'org-agenda-daily/weekly
  2803. :version "24.4"
  2804. :package-version '(Org . "8.0")
  2805. :type 'integer)
  2806. (defcustom org-read-date-prefer-future t
  2807. "Non-nil means assume future for incomplete date input from user.
  2808. This affects the following situations:
  2809. 1. The user gives a month but not a year.
  2810. For example, if it is April and you enter \"feb 2\", this will be read
  2811. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2812. 2. The user gives a day, but no month.
  2813. For example, if today is the 15th, and you enter \"3\", Org will read
  2814. this as the third of *next* month. However, if you enter \"17\",
  2815. it will be considered as *this* month.
  2816. If you set this variable to the symbol `time', then also the following
  2817. will work:
  2818. 3. If the user gives a time.
  2819. If the time is before now, it will be interpreted as tomorrow.
  2820. Currently none of this works for ISO week specifications.
  2821. When this option is nil, the current day, month and year will always be
  2822. used as defaults.
  2823. See also `org-agenda-jump-prefer-future'."
  2824. :group 'org-time
  2825. :type '(choice
  2826. (const :tag "Never" nil)
  2827. (const :tag "Check month and day" t)
  2828. (const :tag "Check month, day, and time" time)))
  2829. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2830. "Should the agenda jump command prefer the future for incomplete dates?
  2831. The default is to do the same as configured in `org-read-date-prefer-future'.
  2832. But you can also set a deviating value here.
  2833. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2834. :group 'org-agenda
  2835. :group 'org-time
  2836. :version "24.1"
  2837. :type '(choice
  2838. (const :tag "Use org-read-date-prefer-future"
  2839. org-read-date-prefer-future)
  2840. (const :tag "Never" nil)
  2841. (const :tag "Always" t)))
  2842. (defcustom org-read-date-force-compatible-dates t
  2843. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2844. Depending on the system Emacs is running on, certain dates cannot
  2845. be represented with the type used internally to represent time.
  2846. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2847. correctly. Some systems allow for earlier dates, some for later,
  2848. some for both. One way to find out it to insert any date into an
  2849. Org buffer, putting the cursor on the year and hitting S-up and
  2850. S-down to test the range.
  2851. When this variable is set to t, the date/time prompt will not let
  2852. you specify dates outside the 1970-2037 range, so it is certain that
  2853. these dates will work in whatever version of Emacs you are
  2854. running, and also that you can move a file from one Emacs implementation
  2855. to another. WHenever Org is forcing the year for you, it will display
  2856. a message and beep.
  2857. When this variable is nil, Org will check if the date is
  2858. representable in the specific Emacs implementation you are using.
  2859. If not, it will force a year, usually the current year, and beep
  2860. to remind you. Currently this setting is not recommended because
  2861. the likelihood that you will open your Org files in an Emacs that
  2862. has limited date range is not negligible.
  2863. A workaround for this problem is to use diary sexp dates for time
  2864. stamps outside of this range."
  2865. :group 'org-time
  2866. :version "24.1"
  2867. :type 'boolean)
  2868. (defcustom org-read-date-display-live t
  2869. "Non-nil means display current interpretation of date prompt live.
  2870. This display will be in an overlay, in the minibuffer."
  2871. :group 'org-time
  2872. :type 'boolean)
  2873. (defcustom org-read-date-popup-calendar t
  2874. "Non-nil means pop up a calendar when prompting for a date.
  2875. In the calendar, the date can be selected with mouse-1. However, the
  2876. minibuffer will also be active, and you can simply enter the date as well.
  2877. When nil, only the minibuffer will be available."
  2878. :group 'org-time
  2879. :type 'boolean)
  2880. (defvaralias 'org-popup-calendar-for-date-prompt
  2881. 'org-read-date-popup-calendar)
  2882. (defcustom org-extend-today-until 0
  2883. "The hour when your day really ends. Must be an integer.
  2884. This has influence for the following applications:
  2885. - When switching the agenda to \"today\". It it is still earlier than
  2886. the time given here, the day recognized as TODAY is actually yesterday.
  2887. - When a date is read from the user and it is still before the time given
  2888. here, the current date and time will be assumed to be yesterday, 23:59.
  2889. Also, timestamps inserted in capture templates follow this rule.
  2890. IMPORTANT: This is a feature whose implementation is and likely will
  2891. remain incomplete. Really, it is only here because past midnight seems to
  2892. be the favorite working time of John Wiegley :-)"
  2893. :group 'org-time
  2894. :type 'integer)
  2895. (defcustom org-use-effective-time nil
  2896. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2897. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2898. \"effective time\" of any timestamps between midnight and 8am will be
  2899. 23:59 of the previous day."
  2900. :group 'org-time
  2901. :version "24.1"
  2902. :type 'boolean)
  2903. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2904. "When non-nil, use the last clock out time for `org-todo'.
  2905. Note that this option has precedence over the combined use of
  2906. `org-use-effective-time' and `org-extend-today-until'."
  2907. :group 'org-time
  2908. :version "24.4"
  2909. :package-version '(Org . "8.0")
  2910. :type 'boolean)
  2911. (defcustom org-edit-timestamp-down-means-later nil
  2912. "Non-nil means S-down will increase the time in a time stamp.
  2913. When nil, S-up will increase."
  2914. :group 'org-time
  2915. :type 'boolean)
  2916. (defcustom org-calendar-follow-timestamp-change t
  2917. "Non-nil means make the calendar window follow timestamp changes.
  2918. When a timestamp is modified and the calendar window is visible, it will be
  2919. moved to the new date."
  2920. :group 'org-time
  2921. :type 'boolean)
  2922. (defgroup org-tags nil
  2923. "Options concerning tags in Org mode."
  2924. :tag "Org Tags"
  2925. :group 'org)
  2926. (defcustom org-tag-alist nil
  2927. "Default tags available in Org files.
  2928. The value of this variable is an alist. Associations either:
  2929. (TAG)
  2930. (TAG . SELECT)
  2931. (SPECIAL)
  2932. where TAG is a tag as a string, SELECT is character, used to
  2933. select that tag through the fast tag selection interface, and
  2934. SPECIAL is one of the following keywords: `:startgroup',
  2935. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2936. `:newline'. These keywords are used to define a hierarchy of
  2937. tags. See manual for details.
  2938. When this variable is nil, Org mode bases tag input on what is
  2939. already in the buffer. The value can be overridden locally by
  2940. using a TAGS keyword, e.g.,
  2941. #+TAGS: tag1 tag2
  2942. See also `org-tag-persistent-alist' to sidestep this behavior."
  2943. :group 'org-tags
  2944. :type '(repeat
  2945. (choice
  2946. (cons :tag "Tag with key"
  2947. (string :tag "Tag name")
  2948. (character :tag "Access char"))
  2949. (list :tag "Tag" (string :tag "Tag name"))
  2950. (const :tag "Start radio group" (:startgroup))
  2951. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2952. (const :tag "Group tags delimiter" (:grouptags))
  2953. (const :tag "End radio group" (:endgroup))
  2954. (const :tag "End tag group, non distinct" (:endgrouptag))
  2955. (const :tag "New line" (:newline)))))
  2956. (defcustom org-tag-persistent-alist nil
  2957. "Tags always available in Org files.
  2958. The value of this variable is an alist. Associations either:
  2959. (TAG)
  2960. (TAG . SELECT)
  2961. (SPECIAL)
  2962. where TAG is a tag as a string, SELECT is a character, used to
  2963. select that tag through the fast tag selection interface, and
  2964. SPECIAL is one of the following keywords: `:startgroup',
  2965. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2966. `:newline'. These keywords are used to define a hierarchy of
  2967. tags. See manual for details.
  2968. Unlike to `org-tag-alist', tags defined in this variable do not
  2969. depend on a local TAGS keyword. Instead, to disable these tags
  2970. on a per-file basis, insert anywhere in the file:
  2971. #+STARTUP: noptag"
  2972. :group 'org-tags
  2973. :type '(repeat
  2974. (choice
  2975. (cons :tag "Tag with key"
  2976. (string :tag "Tag name")
  2977. (character :tag "Access char"))
  2978. (list :tag "Tag" (string :tag "Tag name"))
  2979. (const :tag "Start radio group" (:startgroup))
  2980. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2981. (const :tag "Group tags delimiter" (:grouptags))
  2982. (const :tag "End radio group" (:endgroup))
  2983. (const :tag "End tag group, non distinct" (:endgrouptag))
  2984. (const :tag "New line" (:newline)))))
  2985. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2986. "If non-nil, always offer completion for all tags of all agenda files.
  2987. Instead of customizing this variable directly, you might want to
  2988. set it locally for capture buffers, because there no list of
  2989. tags in that file can be created dynamically (there are none).
  2990. (add-hook \\='org-capture-mode-hook
  2991. (lambda ()
  2992. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2993. :group 'org-tags
  2994. :version "24.1"
  2995. :type 'boolean)
  2996. (defvar org-file-tags nil
  2997. "List of tags that can be inherited by all entries in the file.
  2998. The tags will be inherited if the variable `org-use-tag-inheritance'
  2999. says they should be.
  3000. This variable is populated from #+FILETAGS lines.")
  3001. (defcustom org-use-fast-tag-selection 'auto
  3002. "Non-nil means use fast tag selection scheme.
  3003. This is a special interface to select and deselect tags with single keys.
  3004. When nil, fast selection is never used.
  3005. When the symbol `auto', fast selection is used if and only if selection
  3006. characters for tags have been configured, either through the variable
  3007. `org-tag-alist' or through a #+TAGS line in the buffer.
  3008. When t, fast selection is always used and selection keys are assigned
  3009. automatically if necessary."
  3010. :group 'org-tags
  3011. :type '(choice
  3012. (const :tag "Always" t)
  3013. (const :tag "Never" nil)
  3014. (const :tag "When selection characters are configured" auto)))
  3015. (defcustom org-fast-tag-selection-single-key nil
  3016. "Non-nil means fast tag selection exits after first change.
  3017. When nil, you have to press RET to exit it.
  3018. During fast tag selection, you can toggle this flag with `C-c'.
  3019. This variable can also have the value `expert'. In this case, the window
  3020. displaying the tags menu is not even shown, until you press C-c again."
  3021. :group 'org-tags
  3022. :type '(choice
  3023. (const :tag "No" nil)
  3024. (const :tag "Yes" t)
  3025. (const :tag "Expert" expert)))
  3026. (defvar org-fast-tag-selection-include-todo nil
  3027. "Non-nil means fast tags selection interface will also offer TODO states.
  3028. This is an undocumented feature, you should not rely on it.")
  3029. (defcustom org-tags-column -77
  3030. "The column to which tags should be indented in a headline.
  3031. If this number is positive, it specifies the column. If it is negative,
  3032. it means that the tags should be flushright to that column. For example,
  3033. -80 works well for a normal 80 character screen.
  3034. When 0, place tags directly after headline text, with only one space in
  3035. between."
  3036. :group 'org-tags
  3037. :type 'integer)
  3038. (defcustom org-auto-align-tags t
  3039. "Non-nil keeps tags aligned when modifying headlines.
  3040. Some operations (i.e. demoting) change the length of a headline and
  3041. therefore shift the tags around. With this option turned on, after
  3042. each such operation the tags are again aligned to `org-tags-column'."
  3043. :group 'org-tags
  3044. :type 'boolean)
  3045. (defcustom org-use-tag-inheritance t
  3046. "Non-nil means tags in levels apply also for sublevels.
  3047. When nil, only the tags directly given in a specific line apply there.
  3048. This may also be a list of tags that should be inherited, or a regexp that
  3049. matches tags that should be inherited. Additional control is possible
  3050. with the variable `org-tags-exclude-from-inheritance' which gives an
  3051. explicit list of tags to be excluded from inheritance, even if the value of
  3052. `org-use-tag-inheritance' would select it for inheritance.
  3053. If this option is t, a match early-on in a tree can lead to a large
  3054. number of matches in the subtree when constructing the agenda or creating
  3055. a sparse tree. If you only want to see the first match in a tree during
  3056. a search, check out the variable `org-tags-match-list-sublevels'."
  3057. :group 'org-tags
  3058. :type '(choice
  3059. (const :tag "Not" nil)
  3060. (const :tag "Always" t)
  3061. (repeat :tag "Specific tags" (string :tag "Tag"))
  3062. (regexp :tag "Tags matched by regexp")))
  3063. (defcustom org-tags-exclude-from-inheritance nil
  3064. "List of tags that should never be inherited.
  3065. This is a way to exclude a few tags from inheritance. For way to do
  3066. the opposite, to actively allow inheritance for selected tags,
  3067. see the variable `org-use-tag-inheritance'."
  3068. :group 'org-tags
  3069. :type '(repeat (string :tag "Tag")))
  3070. (defun org-tag-inherit-p (tag)
  3071. "Check if TAG is one that should be inherited."
  3072. (cond
  3073. ((member tag org-tags-exclude-from-inheritance) nil)
  3074. ((eq org-use-tag-inheritance t) t)
  3075. ((not org-use-tag-inheritance) nil)
  3076. ((stringp org-use-tag-inheritance)
  3077. (string-match org-use-tag-inheritance tag))
  3078. ((listp org-use-tag-inheritance)
  3079. (member tag org-use-tag-inheritance))
  3080. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3081. (defcustom org-tags-match-list-sublevels t
  3082. "Non-nil means list also sublevels of headlines matching a search.
  3083. This variable applies to tags/property searches, and also to stuck
  3084. projects because this search is based on a tags match as well.
  3085. When set to the symbol `indented', sublevels are indented with
  3086. leading dots.
  3087. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3088. the sublevels of a headline matching a tag search often also match
  3089. the same search. Listing all of them can create very long lists.
  3090. Setting this variable to nil causes subtrees of a match to be skipped.
  3091. This variable is semi-obsolete and probably should always be true. It
  3092. is better to limit inheritance to certain tags using the variables
  3093. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3094. :group 'org-tags
  3095. :type '(choice
  3096. (const :tag "No, don't list them" nil)
  3097. (const :tag "Yes, do list them" t)
  3098. (const :tag "List them, indented with leading dots" indented)))
  3099. (defcustom org-tags-sort-function nil
  3100. "When set, tags are sorted using this function as a comparator."
  3101. :group 'org-tags
  3102. :type '(choice
  3103. (const :tag "No sorting" nil)
  3104. (const :tag "Alphabetical" string<)
  3105. (const :tag "Reverse alphabetical" string>)
  3106. (function :tag "Custom function" nil)))
  3107. (defvar org-tags-history nil
  3108. "History of minibuffer reads for tags.")
  3109. (defvar org-last-tags-completion-table nil
  3110. "The last used completion table for tags.")
  3111. (defvar org-after-tags-change-hook nil
  3112. "Hook that is run after the tags in a line have changed.")
  3113. (defgroup org-properties nil
  3114. "Options concerning properties in Org mode."
  3115. :tag "Org Properties"
  3116. :group 'org)
  3117. (defcustom org-property-format "%-10s %s"
  3118. "How property key/value pairs should be formatted by `indent-line'.
  3119. When `indent-line' hits a property definition, it will format the line
  3120. according to this format, mainly to make sure that the values are
  3121. lined-up with respect to each other."
  3122. :group 'org-properties
  3123. :type 'string)
  3124. (defcustom org-properties-postprocess-alist nil
  3125. "Alist of properties and functions to adjust inserted values.
  3126. Elements of this alist must be of the form
  3127. ([string] [function])
  3128. where [string] must be a property name and [function] must be a
  3129. lambda expression: this lambda expression must take one argument,
  3130. the value to adjust, and return the new value as a string.
  3131. For example, this element will allow the property \"Remaining\"
  3132. to be updated wrt the relation between the \"Effort\" property
  3133. and the clock summary:
  3134. ((\"Remaining\" (lambda(value)
  3135. (let ((clocksum (org-clock-sum-current-item))
  3136. (effort (org-duration-to-minutes
  3137. (org-entry-get (point) \"Effort\"))))
  3138. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3139. :group 'org-properties
  3140. :version "24.1"
  3141. :type '(alist :key-type (string :tag "Property")
  3142. :value-type (function :tag "Function")))
  3143. (defcustom org-use-property-inheritance nil
  3144. "Non-nil means properties apply also for sublevels.
  3145. This setting is chiefly used during property searches. Turning it on can
  3146. cause significant overhead when doing a search, which is why it is not
  3147. on by default.
  3148. When nil, only the properties directly given in the current entry count.
  3149. When t, every property is inherited. The value may also be a list of
  3150. properties that should have inheritance, or a regular expression matching
  3151. properties that should be inherited.
  3152. However, note that some special properties use inheritance under special
  3153. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3154. and the properties ending in \"_ALL\" when they are used as descriptor
  3155. for valid values of a property.
  3156. Note for programmers:
  3157. When querying an entry with `org-entry-get', you can control if inheritance
  3158. should be used. By default, `org-entry-get' looks only at the local
  3159. properties. You can request inheritance by setting the inherit argument
  3160. to t (to force inheritance) or to `selective' (to respect the setting
  3161. in this variable)."
  3162. :group 'org-properties
  3163. :type '(choice
  3164. (const :tag "Not" nil)
  3165. (const :tag "Always" t)
  3166. (repeat :tag "Specific properties" (string :tag "Property"))
  3167. (regexp :tag "Properties matched by regexp")))
  3168. (defun org-property-inherit-p (property)
  3169. "Return a non-nil value if PROPERTY should be inherited."
  3170. (cond
  3171. ((eq org-use-property-inheritance t) t)
  3172. ((not org-use-property-inheritance) nil)
  3173. ((stringp org-use-property-inheritance)
  3174. (string-match org-use-property-inheritance property))
  3175. ((listp org-use-property-inheritance)
  3176. (member-ignore-case property org-use-property-inheritance))
  3177. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3178. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3179. "The default column format, if no other format has been defined.
  3180. This variable can be set on the per-file basis by inserting a line
  3181. #+COLUMNS: %25ITEM ....."
  3182. :group 'org-properties
  3183. :type 'string)
  3184. (defcustom org-columns-ellipses ".."
  3185. "The ellipses to be used when a field in column view is truncated.
  3186. When this is the empty string, as many characters as possible are shown,
  3187. but then there will be no visual indication that the field has been truncated.
  3188. When this is a string of length N, the last N characters of a truncated
  3189. field are replaced by this string. If the column is narrower than the
  3190. ellipses string, only part of the ellipses string will be shown."
  3191. :group 'org-properties
  3192. :type 'string)
  3193. (defconst org-global-properties-fixed
  3194. '(("VISIBILITY_ALL" . "folded children content all")
  3195. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3196. "List of property/value pairs that can be inherited by any entry.
  3197. These are fixed values, for the preset properties. The user variable
  3198. that can be used to add to this list is `org-global-properties'.
  3199. The entries in this list are cons cells where the car is a property
  3200. name and cdr is a string with the value. If the value represents
  3201. multiple items like an \"_ALL\" property, separate the items by
  3202. spaces.")
  3203. (defcustom org-global-properties nil
  3204. "List of property/value pairs that can be inherited by any entry.
  3205. This list will be combined with the constant `org-global-properties-fixed'.
  3206. The entries in this list are cons cells where the car is a property
  3207. name and cdr is a string with the value.
  3208. You can set buffer-local values for the same purpose in the variable
  3209. `org-file-properties' this by adding lines like
  3210. #+PROPERTY: NAME VALUE"
  3211. :group 'org-properties
  3212. :type '(repeat
  3213. (cons (string :tag "Property")
  3214. (string :tag "Value"))))
  3215. (defvar-local org-file-properties nil
  3216. "List of property/value pairs that can be inherited by any entry.
  3217. Valid for the current buffer.
  3218. This variable is populated from #+PROPERTY lines.")
  3219. (defgroup org-agenda nil
  3220. "Options concerning agenda views in Org mode."
  3221. :tag "Org Agenda"
  3222. :group 'org)
  3223. (defvar-local org-category nil
  3224. "Variable used by org files to set a category for agenda display.
  3225. Such files should use a file variable to set it, for example
  3226. # -*- mode: org; org-category: \"ELisp\"
  3227. or contain a special line
  3228. #+CATEGORY: ELisp
  3229. If the file does not specify a category, then file's base name
  3230. is used instead.")
  3231. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3232. (defcustom org-agenda-files nil
  3233. "The files to be used for agenda display.
  3234. If an entry is a directory, all files in that directory that are matched
  3235. by `org-agenda-file-regexp' will be part of the file list.
  3236. If the value of the variable is not a list but a single file name, then
  3237. the list of agenda files is actually stored and maintained in that file,
  3238. one agenda file per line. In this file paths can be given relative to
  3239. `org-directory'. Tilde expansion and environment variable substitution
  3240. are also made.
  3241. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3242. and removed with `\\[org-remove-file]'."
  3243. :group 'org-agenda
  3244. :type '(choice
  3245. (repeat :tag "List of files and directories" file)
  3246. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3247. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3248. "Regular expression to match files for `org-agenda-files'.
  3249. If any element in the list in that variable contains a directory instead
  3250. of a normal file, all files in that directory that are matched by this
  3251. regular expression will be included."
  3252. :group 'org-agenda
  3253. :type 'regexp)
  3254. (defcustom org-agenda-text-search-extra-files nil
  3255. "List of extra files to be searched by text search commands.
  3256. These files will be searched in addition to the agenda files by the
  3257. commands `org-search-view' (`\\[org-agenda] s') \
  3258. and `org-occur-in-agenda-files'.
  3259. Note that these files will only be searched for text search commands,
  3260. not for the other agenda views like todo lists, tag searches or the weekly
  3261. agenda. This variable is intended to list notes and possibly archive files
  3262. that should also be searched by these two commands.
  3263. In fact, if the first element in the list is the symbol `agenda-archives',
  3264. then all archive files of all agenda files will be added to the search
  3265. scope."
  3266. :group 'org-agenda
  3267. :type '(set :greedy t
  3268. (const :tag "Agenda Archives" agenda-archives)
  3269. (repeat :inline t (file))))
  3270. (defvaralias 'org-agenda-multi-occur-extra-files
  3271. 'org-agenda-text-search-extra-files)
  3272. (defcustom org-agenda-skip-unavailable-files nil
  3273. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3274. A nil value means to remove them, after a query, from the list."
  3275. :group 'org-agenda
  3276. :type 'boolean)
  3277. (defcustom org-calendar-to-agenda-key [?c]
  3278. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3279. The command `org-calendar-goto-agenda' will be bound to this key. The
  3280. default is the character `c' because then `c' can be used to switch back and
  3281. forth between agenda and calendar."
  3282. :group 'org-agenda
  3283. :type 'sexp)
  3284. (defcustom org-calendar-insert-diary-entry-key [?i]
  3285. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3286. This option is irrelevant until `org-agenda-diary-file' has been configured
  3287. to point to an Org file. When that is the case, the command
  3288. `org-agenda-diary-entry' will be bound to the key given here, by default
  3289. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3290. if you want to continue doing this, you need to change this to a different
  3291. key."
  3292. :group 'org-agenda
  3293. :type 'sexp)
  3294. (defcustom org-agenda-diary-file 'diary-file
  3295. "File to which to add new entries with the `i' key in agenda and calendar.
  3296. When this is the symbol `diary-file', the functionality in the Emacs
  3297. calendar will be used to add entries to the `diary-file'. But when this
  3298. points to a file, `org-agenda-diary-entry' will be used instead."
  3299. :group 'org-agenda
  3300. :type '(choice
  3301. (const :tag "The standard Emacs diary file" diary-file)
  3302. (file :tag "Special Org file diary entries")))
  3303. (eval-after-load "calendar"
  3304. '(progn
  3305. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3306. 'org-calendar-goto-agenda)
  3307. (add-hook 'calendar-mode-hook
  3308. (lambda ()
  3309. (unless (eq org-agenda-diary-file 'diary-file)
  3310. (define-key calendar-mode-map
  3311. org-calendar-insert-diary-entry-key
  3312. 'org-agenda-diary-entry))))))
  3313. (defgroup org-latex nil
  3314. "Options for embedding LaTeX code into Org mode."
  3315. :tag "Org LaTeX"
  3316. :group 'org)
  3317. (defcustom org-format-latex-options
  3318. '(:foreground default :background default :scale 1.0
  3319. :html-foreground "Black" :html-background "Transparent"
  3320. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3321. "Options for creating images from LaTeX fragments.
  3322. This is a property list with the following properties:
  3323. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3324. `default' means use the foreground of the default face.
  3325. `auto' means use the foreground from the text face.
  3326. :background the background color, or \"Transparent\".
  3327. `default' means use the background of the default face.
  3328. `auto' means use the background from the text face.
  3329. :scale a scaling factor for the size of the images, to get more pixels
  3330. :html-foreground, :html-background, :html-scale
  3331. the same numbers for HTML export.
  3332. :matchers a list indicating which matchers should be used to
  3333. find LaTeX fragments. Valid members of this list are:
  3334. \"begin\" find environments
  3335. \"$1\" find single characters surrounded by $.$
  3336. \"$\" find math expressions surrounded by $...$
  3337. \"$$\" find math expressions surrounded by $$....$$
  3338. \"\\(\" find math expressions surrounded by \\(...\\)
  3339. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3340. :group 'org-latex
  3341. :type 'plist)
  3342. (defcustom org-format-latex-signal-error t
  3343. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3344. When nil, just push out a message."
  3345. :group 'org-latex
  3346. :version "24.1"
  3347. :type 'boolean)
  3348. (defcustom org-latex-to-mathml-jar-file nil
  3349. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3350. Use this to specify additional executable file say a jar file.
  3351. When using MathToWeb as the converter, specify the full-path to
  3352. your mathtoweb.jar file."
  3353. :group 'org-latex
  3354. :version "24.1"
  3355. :type '(choice
  3356. (const :tag "None" nil)
  3357. (file :tag "JAR file" :must-match t)))
  3358. (defcustom org-latex-to-mathml-convert-command nil
  3359. "Command to convert LaTeX fragments to MathML.
  3360. Replace format-specifiers in the command as noted below and use
  3361. `shell-command' to convert LaTeX to MathML.
  3362. %j: Executable file in fully expanded form as specified by
  3363. `org-latex-to-mathml-jar-file'.
  3364. %I: Input LaTeX file in fully expanded form.
  3365. %i: The latex fragment to be converted.
  3366. %o: Output MathML file.
  3367. This command is used by `org-create-math-formula'.
  3368. When using MathToWeb as the converter, set this option to
  3369. \"java -jar %j -unicode -force -df %o %I\".
  3370. When using LaTeXML set this option to
  3371. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3372. :group 'org-latex
  3373. :version "24.1"
  3374. :type '(choice
  3375. (const :tag "None" nil)
  3376. (string :tag "\nShell command")))
  3377. (defcustom org-preview-latex-default-process 'dvipng
  3378. "The default process to convert LaTeX fragments to image files.
  3379. All available processes and theirs documents can be found in
  3380. `org-preview-latex-process-alist', which see."
  3381. :group 'org-latex
  3382. :version "26.1"
  3383. :package-version '(Org . "9.0")
  3384. :type 'symbol)
  3385. (defcustom org-preview-latex-process-alist
  3386. '((dvipng
  3387. :programs ("latex" "dvipng")
  3388. :description "dvi > png"
  3389. :message "you need to install the programs: latex and dvipng."
  3390. :image-input-type "dvi"
  3391. :image-output-type "png"
  3392. :image-size-adjust (1.0 . 1.0)
  3393. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3394. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3395. (dvisvgm
  3396. :programs ("latex" "dvisvgm")
  3397. :description "dvi > svg"
  3398. :message "you need to install the programs: latex and dvisvgm."
  3399. :use-xcolor t
  3400. :image-input-type "dvi"
  3401. :image-output-type "svg"
  3402. :image-size-adjust (1.7 . 1.5)
  3403. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3404. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3405. (imagemagick
  3406. :programs ("latex" "convert")
  3407. :description "pdf > png"
  3408. :message "you need to install the programs: latex and imagemagick."
  3409. :use-xcolor t
  3410. :image-input-type "pdf"
  3411. :image-output-type "png"
  3412. :image-size-adjust (1.0 . 1.0)
  3413. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3414. :image-converter
  3415. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3416. "Definitions of external processes for LaTeX previewing.
  3417. Org mode can use some external commands to generate TeX snippet's images for
  3418. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3419. `org-create-formula-image' how to call them.
  3420. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3421. PROPERTIES accepts the following attributes:
  3422. :programs list of strings, required programs.
  3423. :description string, describe the process.
  3424. :message string, message it when required programs cannot be found.
  3425. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3426. :image-output-type string, output file type of image converter (e.g., \"png\").
  3427. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3428. deal with background and foreground color of image.
  3429. Otherwise, dvipng style background and foreground color
  3430. format are generated. You may then refer to them in
  3431. command options with \"%F\" and \"%B\".
  3432. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3433. image size showed in buffer and the cdr element is for
  3434. HTML file. This option is only useful for process
  3435. developers, users should use variable
  3436. `org-format-latex-options' instead.
  3437. :post-clean list of strings, files matched are to be cleaned up once
  3438. the image is generated. When nil, the files with \".dvi\",
  3439. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3440. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3441. be cleaned up.
  3442. :latex-header list of strings, the LaTeX header of the snippet file.
  3443. When nil, the fallback value is used instead, which is
  3444. controlled by `org-format-latex-header',
  3445. `org-latex-default-packages-alist' and
  3446. `org-latex-packages-alist', which see.
  3447. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3448. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3449. replaced with values defined below.
  3450. :image-converter list of image converter commands strings. Each of them is
  3451. given to the shell and supports any of the following
  3452. place-holders defined below.
  3453. Place-holders used by `:image-converter' and `:latex-compiler':
  3454. %f input file name
  3455. %b base name of input file
  3456. %o base directory of input file
  3457. %O absolute output file name
  3458. Place-holders only used by `:image-converter':
  3459. %F foreground of image
  3460. %B background of image
  3461. %D dpi, which is used to adjust image size by some processing commands.
  3462. %S the image size scale ratio, which is used to adjust image size by some
  3463. processing commands."
  3464. :group 'org-latex
  3465. :version "26.1"
  3466. :package-version '(Org . "9.0")
  3467. :type '(alist :tag "LaTeX to image backends"
  3468. :value-type (plist)))
  3469. (defcustom org-preview-latex-image-directory "ltximg/"
  3470. "Path to store latex preview images.
  3471. A relative path here creates many directories relative to the
  3472. processed org files paths. An absolute path puts all preview
  3473. images at the same place."
  3474. :group 'org-latex
  3475. :version "26.1"
  3476. :package-version '(Org . "9.0")
  3477. :type 'string)
  3478. (defun org-format-latex-mathml-available-p ()
  3479. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3480. (save-match-data
  3481. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3482. org-latex-to-mathml-convert-command)
  3483. (let ((executable (car (split-string
  3484. org-latex-to-mathml-convert-command))))
  3485. (when (executable-find executable)
  3486. (if (string-match
  3487. "%j" org-latex-to-mathml-convert-command)
  3488. (file-readable-p org-latex-to-mathml-jar-file)
  3489. t))))))
  3490. (defcustom org-format-latex-header "\\documentclass{article}
  3491. \\usepackage[usenames]{color}
  3492. \[PACKAGES]
  3493. \[DEFAULT-PACKAGES]
  3494. \\pagestyle{empty} % do not remove
  3495. % The settings below are copied from fullpage.sty
  3496. \\setlength{\\textwidth}{\\paperwidth}
  3497. \\addtolength{\\textwidth}{-3cm}
  3498. \\setlength{\\oddsidemargin}{1.5cm}
  3499. \\addtolength{\\oddsidemargin}{-2.54cm}
  3500. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3501. \\setlength{\\textheight}{\\paperheight}
  3502. \\addtolength{\\textheight}{-\\headheight}
  3503. \\addtolength{\\textheight}{-\\headsep}
  3504. \\addtolength{\\textheight}{-\\footskip}
  3505. \\addtolength{\\textheight}{-3cm}
  3506. \\setlength{\\topmargin}{1.5cm}
  3507. \\addtolength{\\topmargin}{-2.54cm}"
  3508. "The document header used for processing LaTeX fragments.
  3509. It is imperative that this header make sure that no page number
  3510. appears on the page. The package defined in the variables
  3511. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3512. will either replace the placeholder \"[PACKAGES]\" in this
  3513. header, or they will be appended."
  3514. :group 'org-latex
  3515. :type 'string)
  3516. (defun org-set-packages-alist (var val)
  3517. "Set the packages alist and make sure it has 3 elements per entry."
  3518. (set var (mapcar (lambda (x)
  3519. (if (and (consp x) (= (length x) 2))
  3520. (list (car x) (nth 1 x) t)
  3521. x))
  3522. val)))
  3523. (defun org-get-packages-alist (var)
  3524. "Get the packages alist and make sure it has 3 elements per entry."
  3525. (mapcar (lambda (x)
  3526. (if (and (consp x) (= (length x) 2))
  3527. (list (car x) (nth 1 x) t)
  3528. x))
  3529. (default-value var)))
  3530. (defcustom org-latex-default-packages-alist
  3531. '(("AUTO" "inputenc" t ("pdflatex"))
  3532. ("T1" "fontenc" t ("pdflatex"))
  3533. ("" "graphicx" t)
  3534. ("" "grffile" t)
  3535. ("" "longtable" nil)
  3536. ("" "wrapfig" nil)
  3537. ("" "rotating" nil)
  3538. ("normalem" "ulem" t)
  3539. ("" "amsmath" t)
  3540. ("" "textcomp" t)
  3541. ("" "amssymb" t)
  3542. ("" "capt-of" nil)
  3543. ("" "hyperref" nil))
  3544. "Alist of default packages to be inserted in the header.
  3545. Change this only if one of the packages here causes an
  3546. incompatibility with another package you are using.
  3547. The packages in this list are needed by one part or another of
  3548. Org mode to function properly:
  3549. - inputenc, fontenc: for basic font and character selection
  3550. - graphicx: for including images
  3551. - grffile: allow periods and spaces in graphics file names
  3552. - longtable: For multipage tables
  3553. - wrapfig: for figure placement
  3554. - rotating: for sideways figures and tables
  3555. - ulem: for underline and strike-through
  3556. - amsmath: for subscript and superscript and math environments
  3557. - textcomp, amssymb: for various symbols used
  3558. for interpreting the entities in `org-entities'. You can skip
  3559. some of these packages if you don't use any of their symbols.
  3560. - capt-of: for captions outside of floats
  3561. - hyperref: for cross references
  3562. Therefore you should not modify this variable unless you know
  3563. what you are doing. The one reason to change it anyway is that
  3564. you might be loading some other package that conflicts with one
  3565. of the default packages. Each element is either a cell or
  3566. a string.
  3567. A cell is of the format
  3568. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3569. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3570. when compiling LaTeX snippets into images for inclusion into
  3571. non-LaTeX output. COMPILERS is a list of compilers that should
  3572. include the package, see `org-latex-compiler'. If the document
  3573. compiler is not in the list, and the list is non-nil, the package
  3574. will not be inserted in the final document.
  3575. A string will be inserted as-is in the header of the document."
  3576. :group 'org-latex
  3577. :group 'org-export-latex
  3578. :set 'org-set-packages-alist
  3579. :get 'org-get-packages-alist
  3580. :version "26.1"
  3581. :package-version '(Org . "8.3")
  3582. :type '(repeat
  3583. (choice
  3584. (list :tag "options/package pair"
  3585. (string :tag "options")
  3586. (string :tag "package")
  3587. (boolean :tag "Snippet"))
  3588. (string :tag "A line of LaTeX"))))
  3589. (defcustom org-latex-packages-alist nil
  3590. "Alist of packages to be inserted in every LaTeX header.
  3591. These will be inserted after `org-latex-default-packages-alist'.
  3592. Each element is either a cell or a string.
  3593. A cell is of the format:
  3594. (\"options\" \"package\" SNIPPET-FLAG)
  3595. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3596. needed when turning LaTeX snippets into images for inclusion into
  3597. non-LaTeX output.
  3598. A string will be inserted as-is in the header of the document.
  3599. Make sure that you only list packages here which:
  3600. - you want in every file;
  3601. - do not conflict with the setup in `org-format-latex-header';
  3602. - do not conflict with the default packages in
  3603. `org-latex-default-packages-alist'."
  3604. :group 'org-latex
  3605. :group 'org-export-latex
  3606. :set 'org-set-packages-alist
  3607. :get 'org-get-packages-alist
  3608. :type '(repeat
  3609. (choice
  3610. (list :tag "options/package pair"
  3611. (string :tag "options")
  3612. (string :tag "package")
  3613. (boolean :tag "Snippet"))
  3614. (string :tag "A line of LaTeX"))))
  3615. (defgroup org-appearance nil
  3616. "Settings for Org mode appearance."
  3617. :tag "Org Appearance"
  3618. :group 'org)
  3619. (defcustom org-level-color-stars-only nil
  3620. "Non-nil means fontify only the stars in each headline.
  3621. When nil, the entire headline is fontified.
  3622. Changing it requires restart of `font-lock-mode' to become effective
  3623. also in regions already fontified."
  3624. :group 'org-appearance
  3625. :type 'boolean)
  3626. (defcustom org-hide-leading-stars nil
  3627. "Non-nil means hide the first N-1 stars in a headline.
  3628. This works by using the face `org-hide' for these stars. This
  3629. face is white for a light background, and black for a dark
  3630. background. You may have to customize the face `org-hide' to
  3631. make this work.
  3632. Changing it requires restart of `font-lock-mode' to become effective
  3633. also in regions already fontified.
  3634. You may also set this on a per-file basis by adding one of the following
  3635. lines to the buffer:
  3636. #+STARTUP: hidestars
  3637. #+STARTUP: showstars"
  3638. :group 'org-appearance
  3639. :type 'boolean)
  3640. (defcustom org-hidden-keywords nil
  3641. "List of symbols corresponding to keywords to be hidden the org buffer.
  3642. For example, a value \\='(title) for this list will make the document's title
  3643. appear in the buffer without the initial #+TITLE: keyword."
  3644. :group 'org-appearance
  3645. :version "24.1"
  3646. :type '(set (const :tag "#+AUTHOR" author)
  3647. (const :tag "#+DATE" date)
  3648. (const :tag "#+EMAIL" email)
  3649. (const :tag "#+TITLE" title)))
  3650. (defcustom org-custom-properties nil
  3651. "List of properties (as strings) with a special meaning.
  3652. The default use of these custom properties is to let the user
  3653. hide them with `org-toggle-custom-properties-visibility'."
  3654. :group 'org-properties
  3655. :group 'org-appearance
  3656. :version "24.3"
  3657. :type '(repeat (string :tag "Property Name")))
  3658. (defcustom org-fontify-done-headline nil
  3659. "Non-nil means change the face of a headline if it is marked DONE.
  3660. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3661. When this is non-nil, the headline after the keyword is set to the
  3662. `org-headline-done' as an additional indication."
  3663. :group 'org-appearance
  3664. :type 'boolean)
  3665. (defcustom org-fontify-emphasized-text t
  3666. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3667. Changing this variable requires a restart of Emacs to take effect."
  3668. :group 'org-appearance
  3669. :type 'boolean)
  3670. (defcustom org-fontify-whole-heading-line nil
  3671. "Non-nil means fontify the whole line for headings.
  3672. This is useful when setting a background color for the
  3673. org-level-* faces."
  3674. :group 'org-appearance
  3675. :type 'boolean)
  3676. (defcustom org-highlight-latex-and-related nil
  3677. "Non-nil means highlight LaTeX related syntax in the buffer.
  3678. When non nil, the value should be a list containing any of the
  3679. following symbols:
  3680. `latex' Highlight LaTeX snippets and environments.
  3681. `script' Highlight subscript and superscript.
  3682. `entities' Highlight entities."
  3683. :group 'org-appearance
  3684. :version "24.4"
  3685. :package-version '(Org . "8.0")
  3686. :type '(choice
  3687. (const :tag "No highlighting" nil)
  3688. (set :greedy t :tag "Highlight"
  3689. (const :tag "LaTeX snippets and environments" latex)
  3690. (const :tag "Subscript and superscript" script)
  3691. (const :tag "Entities" entities))))
  3692. (defcustom org-hide-emphasis-markers nil
  3693. "Non-nil mean font-lock should hide the emphasis marker characters."
  3694. :group 'org-appearance
  3695. :type 'boolean)
  3696. (defcustom org-hide-macro-markers nil
  3697. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3698. :group 'org-appearance
  3699. :type 'boolean)
  3700. (defcustom org-pretty-entities nil
  3701. "Non-nil means show entities as UTF8 characters.
  3702. When nil, the \\name form remains in the buffer."
  3703. :group 'org-appearance
  3704. :version "24.1"
  3705. :type 'boolean)
  3706. (defcustom org-pretty-entities-include-sub-superscripts t
  3707. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3708. :group 'org-appearance
  3709. :version "24.1"
  3710. :type 'boolean)
  3711. (defvar org-emph-re nil
  3712. "Regular expression for matching emphasis.
  3713. After a match, the match groups contain these elements:
  3714. 0 The match of the full regular expression, including the characters
  3715. before and after the proper match
  3716. 1 The character before the proper match, or empty at beginning of line
  3717. 2 The proper match, including the leading and trailing markers
  3718. 3 The leading marker like * or /, indicating the type of highlighting
  3719. 4 The text between the emphasis markers, not including the markers
  3720. 5 The character after the match, empty at the end of a line")
  3721. (defvar org-verbatim-re nil
  3722. "Regular expression for matching verbatim text.")
  3723. (defvar org-emphasis-regexp-components) ; defined just below
  3724. (defvar org-emphasis-alist) ; defined just below
  3725. (defun org-set-emph-re (var val)
  3726. "Set variable and compute the emphasis regular expression."
  3727. (set var val)
  3728. (when (and (boundp 'org-emphasis-alist)
  3729. (boundp 'org-emphasis-regexp-components)
  3730. org-emphasis-alist org-emphasis-regexp-components)
  3731. (pcase-let*
  3732. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3733. (body (if (<= nl 0) body
  3734. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3735. (template
  3736. (format (concat "\\([%s]\\|^\\)" ;before markers
  3737. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3738. "\\([%s]\\|$\\)") ;after markers
  3739. pre border border body border post)))
  3740. (setq org-emph-re (format template "*/_+"))
  3741. (setq org-verbatim-re (format template "=~")))))
  3742. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3743. ;; set this option proved cumbersome. See this message/thread:
  3744. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3745. (defvar org-emphasis-regexp-components
  3746. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3747. "Components used to build the regular expression for emphasis.
  3748. This is a list with five entries. Terminology: In an emphasis string
  3749. like \" *strong word* \", we call the initial space PREMATCH, the final
  3750. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3751. and \"trong wor\" is the body. The different components in this variable
  3752. specify what is allowed/forbidden in each part:
  3753. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3754. post Chars allowed as postmatch. End of line will be allowed too.
  3755. border The chars *forbidden* as border characters.
  3756. body-regexp A regexp like \".\" to match a body character. Don't use
  3757. non-shy groups here, and don't allow newline here.
  3758. newline The maximum number of newlines allowed in an emphasis exp.
  3759. You need to reload Org or to restart Emacs after setting this.")
  3760. (defcustom org-emphasis-alist
  3761. '(("*" bold)
  3762. ("/" italic)
  3763. ("_" underline)
  3764. ("=" org-verbatim verbatim)
  3765. ("~" org-code verbatim)
  3766. ("+" (:strike-through t)))
  3767. "Alist of characters and faces to emphasize text.
  3768. Text starting and ending with a special character will be emphasized,
  3769. for example *bold*, _underlined_ and /italic/. This variable sets the
  3770. marker characters and the face to be used by font-lock for highlighting
  3771. in Org buffers.
  3772. You need to reload Org or to restart Emacs after customizing this."
  3773. :group 'org-appearance
  3774. :set 'org-set-emph-re
  3775. :version "24.4"
  3776. :package-version '(Org . "8.0")
  3777. :type '(repeat
  3778. (list
  3779. (string :tag "Marker character")
  3780. (choice
  3781. (face :tag "Font-lock-face")
  3782. (plist :tag "Face property list"))
  3783. (option (const verbatim)))))
  3784. (defvar org-protecting-blocks '("src" "example" "export")
  3785. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3786. This is needed for font-lock setup.")
  3787. ;;; Functions and variables from their packages
  3788. ;; Declared here to avoid compiler warnings
  3789. (defvar mark-active)
  3790. ;; Various packages
  3791. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3792. (declare-function calendar-forward-day "cal-move" (arg))
  3793. (declare-function calendar-goto-date "cal-move" (date))
  3794. (declare-function calendar-goto-today "cal-move" ())
  3795. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3796. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3797. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3798. (declare-function cdlatex-tab "ext:cdlatex" ())
  3799. (declare-function dired-get-filename
  3800. "dired"
  3801. (&optional localp no-error-if-not-filep))
  3802. (declare-function iswitchb-read-buffer
  3803. "iswitchb"
  3804. (prompt &optional
  3805. default require-match _predicate start matches-set))
  3806. (declare-function org-agenda-change-all-lines
  3807. "org-agenda"
  3808. (newhead hdmarker &optional fixface just-this))
  3809. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3810. "org-agenda"
  3811. (&optional end))
  3812. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3813. (declare-function org-agenda-format-item
  3814. "org-agenda"
  3815. (extra txt &optional level category tags dotime
  3816. remove-re habitp))
  3817. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3818. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3819. (declare-function org-agenda-save-markers-for-cut-and-paste
  3820. "org-agenda"
  3821. (beg end))
  3822. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3823. (declare-function org-agenda-skip "org-agenda" ())
  3824. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3825. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3826. (declare-function org-indent-mode "org-indent" (&optional arg))
  3827. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3828. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3829. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3830. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3831. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3832. (declare-function parse-time-string "parse-time" (string))
  3833. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3834. (defvar align-mode-rules-list)
  3835. (defvar calc-embedded-close-formula)
  3836. (defvar calc-embedded-open-formula)
  3837. (defvar calc-embedded-open-mode)
  3838. (defvar font-lock-unfontify-region-function)
  3839. (defvar iswitchb-temp-buflist)
  3840. (defvar org-agenda-tags-todo-honor-ignore-options)
  3841. (defvar remember-data-file)
  3842. (defvar texmathp-why)
  3843. ;;;###autoload
  3844. (defun turn-on-orgtbl ()
  3845. "Unconditionally turn on `orgtbl-mode'."
  3846. (require 'org-table)
  3847. (orgtbl-mode 1))
  3848. (defun org-at-table-p (&optional table-type)
  3849. "Non-nil if the cursor is inside an Org table.
  3850. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  3851. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  3852. (or (not (derived-mode-p 'org-mode))
  3853. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3854. (and e (or table-type
  3855. (eq 'org (org-element-property :type e))))))))
  3856. (defun org-at-table.el-p ()
  3857. "Non-nil when point is at a table.el table."
  3858. (and (org-match-line "[ \t]*[|+]")
  3859. (let ((element (org-element-at-point)))
  3860. (and (eq (org-element-type element) 'table)
  3861. (eq (org-element-property :type element) 'table.el)))))
  3862. (defun org-at-table-hline-p ()
  3863. "Non-nil when point is inside a hline in a table.
  3864. Assume point is already in a table."
  3865. (org-match-line org-table-hline-regexp))
  3866. (defun org-table-map-tables (function &optional quietly)
  3867. "Apply FUNCTION to the start of all tables in the buffer."
  3868. (org-with-wide-buffer
  3869. (goto-char (point-min))
  3870. (while (re-search-forward org-table-any-line-regexp nil t)
  3871. (unless quietly
  3872. (message "Mapping tables: %d%%"
  3873. (floor (* 100.0 (point)) (buffer-size))))
  3874. (beginning-of-line 1)
  3875. (when (and (looking-at org-table-line-regexp)
  3876. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3877. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3878. (save-excursion (funcall function))
  3879. (or (looking-at org-table-line-regexp)
  3880. (forward-char 1)))
  3881. (re-search-forward org-table-any-border-regexp nil 1)))
  3882. (unless quietly (message "Mapping tables: done")))
  3883. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3884. (declare-function org-clock-update-mode-line "org-clock" ())
  3885. (declare-function org-resolve-clocks "org-clock"
  3886. (&optional also-non-dangling-p prompt last-valid))
  3887. (defun org-at-TBLFM-p (&optional pos)
  3888. "Non-nil when point (or POS) is in #+TBLFM line."
  3889. (save-excursion
  3890. (goto-char (or pos (point)))
  3891. (beginning-of-line)
  3892. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3893. (eq (org-element-type (org-element-at-point)) 'table))))
  3894. (defvar org-clock-start-time)
  3895. (defvar org-clock-marker (make-marker)
  3896. "Marker recording the last clock-in.")
  3897. (defvar org-clock-hd-marker (make-marker)
  3898. "Marker recording the last clock-in, but the headline position.")
  3899. (defvar org-clock-heading ""
  3900. "The heading of the current clock entry.")
  3901. (defun org-clock-is-active ()
  3902. "Return the buffer where the clock is currently running.
  3903. Return nil if no clock is running."
  3904. (marker-buffer org-clock-marker))
  3905. (defun org-check-running-clock ()
  3906. "Check if the current buffer contains the running clock.
  3907. If yes, offer to stop it and to save the buffer with the changes."
  3908. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3909. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3910. (buffer-name))))
  3911. (org-clock-out)
  3912. (when (y-or-n-p "Save changed buffer?")
  3913. (save-buffer))))
  3914. (defun org-clocktable-try-shift (dir n)
  3915. "Check if this line starts a clock table, if yes, shift the time block."
  3916. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3917. (org-clocktable-shift dir n)))
  3918. ;;;###autoload
  3919. (defun org-clock-persistence-insinuate ()
  3920. "Set up hooks for clock persistence."
  3921. (require 'org-clock)
  3922. (add-hook 'org-mode-hook 'org-clock-load)
  3923. (add-hook 'kill-emacs-hook 'org-clock-save))
  3924. (defgroup org-archive nil
  3925. "Options concerning archiving in Org mode."
  3926. :tag "Org Archive"
  3927. :group 'org-structure)
  3928. (defcustom org-archive-location "%s_archive::"
  3929. "The location where subtrees should be archived.
  3930. The value of this variable is a string, consisting of two parts,
  3931. separated by a double-colon. The first part is a filename and
  3932. the second part is a headline.
  3933. When the filename is omitted, archiving happens in the same file.
  3934. %s in the filename will be replaced by the current file
  3935. name (without the directory part). Archiving to a different file
  3936. is useful to keep archived entries from contributing to the
  3937. Org Agenda.
  3938. The archived entries will be filed as subtrees of the specified
  3939. headline. When the headline is omitted, the subtrees are simply
  3940. filed away at the end of the file, as top-level entries. Also in
  3941. the heading you can use %s to represent the file name, this can be
  3942. useful when using the same archive for a number of different files.
  3943. Here are a few examples:
  3944. \"%s_archive::\"
  3945. If the current file is Projects.org, archive in file
  3946. Projects.org_archive, as top-level trees. This is the default.
  3947. \"::* Archived Tasks\"
  3948. Archive in the current file, under the top-level headline
  3949. \"* Archived Tasks\".
  3950. \"~/org/archive.org::\"
  3951. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3952. \"~/org/archive.org::* From %s\"
  3953. Archive in file ~/org/archive.org (absolute path), under headlines
  3954. \"From FILENAME\" where file name is the current file name.
  3955. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3956. The \"datetree/\" string is special, signifying to archive
  3957. items to the datetree. Items are placed in either the CLOSED
  3958. date of the item, or the current date if there is no CLOSED date.
  3959. The heading will be a subentry to the current date. There doesn't
  3960. need to be a heading, but there always needs to be a slash after
  3961. datetree. For example, to store archived items directly in the
  3962. datetree, use \"~/org/datetree.org::datetree/\".
  3963. \"basement::** Finished Tasks\"
  3964. Archive in file ./basement (relative path), as level 3 trees
  3965. below the level 2 heading \"** Finished Tasks\".
  3966. You may set this option on a per-file basis by adding to the buffer a
  3967. line like
  3968. #+ARCHIVE: basement::** Finished Tasks
  3969. You may also define it locally for a subtree by setting an ARCHIVE property
  3970. in the entry. If such a property is found in an entry, or anywhere up
  3971. the hierarchy, it will be used."
  3972. :group 'org-archive
  3973. :type 'string)
  3974. (defcustom org-agenda-skip-archived-trees t
  3975. "Non-nil means the agenda will skip any items located in archived trees.
  3976. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3977. variable is no longer recommended, you should leave it at the value t.
  3978. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3979. :group 'org-archive
  3980. :group 'org-agenda-skip
  3981. :type 'boolean)
  3982. (defcustom org-columns-skip-archived-trees t
  3983. "Non-nil means ignore archived trees when creating column view."
  3984. :group 'org-archive
  3985. :group 'org-properties
  3986. :type 'boolean)
  3987. (defcustom org-cycle-open-archived-trees nil
  3988. "Non-nil means `org-cycle' will open archived trees.
  3989. An archived tree is a tree marked with the tag ARCHIVE.
  3990. When nil, archived trees will stay folded. You can still open them with
  3991. normal outline commands like `show-all', but not with the cycling commands."
  3992. :group 'org-archive
  3993. :group 'org-cycle
  3994. :type 'boolean)
  3995. (defcustom org-sparse-tree-open-archived-trees nil
  3996. "Non-nil means sparse tree construction shows matches in archived trees.
  3997. When nil, matches in these trees are highlighted, but the trees are kept in
  3998. collapsed state."
  3999. :group 'org-archive
  4000. :group 'org-sparse-trees
  4001. :type 'boolean)
  4002. (defcustom org-sparse-tree-default-date-type nil
  4003. "The default date type when building a sparse tree.
  4004. When this is nil, a date is a scheduled or a deadline timestamp.
  4005. Otherwise, these types are allowed:
  4006. all: all timestamps
  4007. active: only active timestamps (<...>)
  4008. inactive: only inactive timestamps ([...])
  4009. scheduled: only scheduled timestamps
  4010. deadline: only deadline timestamps"
  4011. :type '(choice (const :tag "Scheduled or deadline" nil)
  4012. (const :tag "All timestamps" all)
  4013. (const :tag "Only active timestamps" active)
  4014. (const :tag "Only inactive timestamps" inactive)
  4015. (const :tag "Only scheduled timestamps" scheduled)
  4016. (const :tag "Only deadline timestamps" deadline)
  4017. (const :tag "Only closed timestamps" closed))
  4018. :version "26.1"
  4019. :package-version '(Org . "8.3")
  4020. :group 'org-sparse-trees)
  4021. (defun org-cycle-hide-archived-subtrees (state)
  4022. "Re-hide all archived subtrees after a visibility state change.
  4023. STATE should be one of the symbols listed in the docstring of
  4024. `org-cycle-hook'."
  4025. (when (and (not org-cycle-open-archived-trees)
  4026. (not (memq state '(overview folded))))
  4027. (save-excursion
  4028. (let* ((globalp (memq state '(contents all)))
  4029. (beg (if globalp (point-min) (point)))
  4030. (end (if globalp (point-max) (org-end-of-subtree t))))
  4031. (org-hide-archived-subtrees beg end)
  4032. (goto-char beg)
  4033. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4034. (message "%s" (substitute-command-keys
  4035. "Subtree is archived and stays closed. Use \
  4036. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4037. (defun org-force-cycle-archived ()
  4038. "Cycle subtree even if it is archived."
  4039. (interactive)
  4040. (setq this-command 'org-cycle)
  4041. (let ((org-cycle-open-archived-trees t))
  4042. (call-interactively 'org-cycle)))
  4043. (defun org-hide-archived-subtrees (beg end)
  4044. "Re-hide all archived subtrees after a visibility state change."
  4045. (org-with-wide-buffer
  4046. (let ((case-fold-search nil)
  4047. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4048. (goto-char beg)
  4049. ;; Include headline point is currently on.
  4050. (beginning-of-line)
  4051. (while (and (< (point) end) (re-search-forward re end t))
  4052. (when (member org-archive-tag (org-get-tags))
  4053. (org-flag-subtree t)
  4054. (org-end-of-subtree t))))))
  4055. (declare-function outline-end-of-heading "outline" ())
  4056. (declare-function outline-flag-region "outline" (from to flag))
  4057. (defun org-flag-subtree (flag)
  4058. (save-excursion
  4059. (org-back-to-heading t)
  4060. (outline-end-of-heading)
  4061. (outline-flag-region (point)
  4062. (progn (org-end-of-subtree t) (point))
  4063. flag)))
  4064. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4065. ;; Declare Column View Code
  4066. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4067. (declare-function org-columns-compute "org-colview" (property))
  4068. ;; Declare ID code
  4069. (declare-function org-id-store-link "org-id")
  4070. (declare-function org-id-locations-load "org-id")
  4071. (declare-function org-id-locations-save "org-id")
  4072. (defvar org-id-track-globally)
  4073. ;;; Variables for pre-computed regular expressions, all buffer local
  4074. (defvar-local org-todo-regexp nil
  4075. "Matches any of the TODO state keywords.
  4076. Since TODO keywords are case-sensitive, `case-fold-search' is
  4077. expected to be bound to nil when matching against this regexp.")
  4078. (defvar-local org-not-done-regexp nil
  4079. "Matches any of the TODO state keywords except the last one.
  4080. Since TODO keywords are case-sensitive, `case-fold-search' is
  4081. expected to be bound to nil when matching against this regexp.")
  4082. (defvar-local org-not-done-heading-regexp nil
  4083. "Matches a TODO headline that is not done.
  4084. Since TODO keywords are case-sensitive, `case-fold-search' is
  4085. expected to be bound to nil when matching against this regexp.")
  4086. (defvar-local org-todo-line-regexp nil
  4087. "Matches a headline and puts TODO state into group 2 if present.
  4088. Since TODO keywords are case-sensitive, `case-fold-search' is
  4089. expected to be bound to nil when matching against this regexp.")
  4090. (defvar-local org-complex-heading-regexp nil
  4091. "Matches a headline and puts everything into groups:
  4092. group 1: Stars
  4093. group 2: The TODO keyword, maybe
  4094. group 3: Priority cookie
  4095. group 4: True headline
  4096. group 5: Tags
  4097. Since TODO keywords are case-sensitive, `case-fold-search' is
  4098. expected to be bound to nil when matching against this regexp.")
  4099. (defvar-local org-complex-heading-regexp-format nil
  4100. "Printf format to make regexp to match an exact headline.
  4101. This regexp will match the headline of any node which has the
  4102. exact headline text that is put into the format, but may have any
  4103. TODO state, priority and tags.")
  4104. (defvar-local org-todo-line-tags-regexp nil
  4105. "Matches a headline and puts TODO state into group 2 if present.
  4106. Also put tags into group 4 if tags are present.")
  4107. (defconst org-plain-time-of-day-regexp
  4108. (concat
  4109. "\\(\\<[012]?[0-9]"
  4110. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4111. "\\(--?"
  4112. "\\(\\<[012]?[0-9]"
  4113. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4114. "\\)?")
  4115. "Regular expression to match a plain time or time range.
  4116. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4117. groups carry important information:
  4118. 0 the full match
  4119. 1 the first time, range or not
  4120. 8 the second time, if it is a range.")
  4121. (defconst org-plain-time-extension-regexp
  4122. (concat
  4123. "\\(\\<[012]?[0-9]"
  4124. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4125. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4126. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4127. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4128. groups carry important information:
  4129. 0 the full match
  4130. 7 hours of duration
  4131. 9 minutes of duration")
  4132. (defconst org-stamp-time-of-day-regexp
  4133. (concat
  4134. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4135. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4136. "\\(--?"
  4137. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4138. "Regular expression to match a timestamp time or time range.
  4139. After a match, the following groups carry important information:
  4140. 0 the full match
  4141. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4142. 2 the first time, range or not
  4143. 4 the second time, if it is a range.")
  4144. (defconst org-startup-options
  4145. '(("fold" org-startup-folded t)
  4146. ("overview" org-startup-folded t)
  4147. ("nofold" org-startup-folded nil)
  4148. ("showall" org-startup-folded nil)
  4149. ("showeverything" org-startup-folded showeverything)
  4150. ("content" org-startup-folded content)
  4151. ("indent" org-startup-indented t)
  4152. ("noindent" org-startup-indented nil)
  4153. ("hidestars" org-hide-leading-stars t)
  4154. ("showstars" org-hide-leading-stars nil)
  4155. ("odd" org-odd-levels-only t)
  4156. ("oddeven" org-odd-levels-only nil)
  4157. ("align" org-startup-align-all-tables t)
  4158. ("noalign" org-startup-align-all-tables nil)
  4159. ("shrink" org-startup-shrink-all-tables t)
  4160. ("inlineimages" org-startup-with-inline-images t)
  4161. ("noinlineimages" org-startup-with-inline-images nil)
  4162. ("latexpreview" org-startup-with-latex-preview t)
  4163. ("nolatexpreview" org-startup-with-latex-preview nil)
  4164. ("customtime" org-display-custom-times t)
  4165. ("logdone" org-log-done time)
  4166. ("lognotedone" org-log-done note)
  4167. ("nologdone" org-log-done nil)
  4168. ("lognoteclock-out" org-log-note-clock-out t)
  4169. ("nolognoteclock-out" org-log-note-clock-out nil)
  4170. ("logrepeat" org-log-repeat state)
  4171. ("lognoterepeat" org-log-repeat note)
  4172. ("logdrawer" org-log-into-drawer t)
  4173. ("nologdrawer" org-log-into-drawer nil)
  4174. ("logstatesreversed" org-log-states-order-reversed t)
  4175. ("nologstatesreversed" org-log-states-order-reversed nil)
  4176. ("nologrepeat" org-log-repeat nil)
  4177. ("logreschedule" org-log-reschedule time)
  4178. ("lognotereschedule" org-log-reschedule note)
  4179. ("nologreschedule" org-log-reschedule nil)
  4180. ("logredeadline" org-log-redeadline time)
  4181. ("lognoteredeadline" org-log-redeadline note)
  4182. ("nologredeadline" org-log-redeadline nil)
  4183. ("logrefile" org-log-refile time)
  4184. ("lognoterefile" org-log-refile note)
  4185. ("nologrefile" org-log-refile nil)
  4186. ("fninline" org-footnote-define-inline t)
  4187. ("nofninline" org-footnote-define-inline nil)
  4188. ("fnlocal" org-footnote-section nil)
  4189. ("fnauto" org-footnote-auto-label t)
  4190. ("fnprompt" org-footnote-auto-label nil)
  4191. ("fnconfirm" org-footnote-auto-label confirm)
  4192. ("fnplain" org-footnote-auto-label plain)
  4193. ("fnadjust" org-footnote-auto-adjust t)
  4194. ("nofnadjust" org-footnote-auto-adjust nil)
  4195. ("constcgs" constants-unit-system cgs)
  4196. ("constSI" constants-unit-system SI)
  4197. ("noptag" org-tag-persistent-alist nil)
  4198. ("hideblocks" org-hide-block-startup t)
  4199. ("nohideblocks" org-hide-block-startup nil)
  4200. ("beamer" org-startup-with-beamer-mode t)
  4201. ("entitiespretty" org-pretty-entities t)
  4202. ("entitiesplain" org-pretty-entities nil))
  4203. "Variable associated with STARTUP options for org-mode.
  4204. Each element is a list of three items: the startup options (as written
  4205. in the #+STARTUP line), the corresponding variable, and the value to set
  4206. this variable to if the option is found. An optional forth element PUSH
  4207. means to push this value onto the list in the variable.")
  4208. (defcustom org-group-tags t
  4209. "When non-nil (the default), use group tags.
  4210. This can be turned on/off through `org-toggle-tags-groups'."
  4211. :group 'org-tags
  4212. :group 'org-startup
  4213. :type 'boolean)
  4214. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4215. (defun org-toggle-tags-groups ()
  4216. "Toggle support for group tags.
  4217. Support for group tags is controlled by the option
  4218. `org-group-tags', which is non-nil by default."
  4219. (interactive)
  4220. (setq org-group-tags (not org-group-tags))
  4221. (cond ((and (derived-mode-p 'org-agenda-mode)
  4222. org-group-tags)
  4223. (org-agenda-redo))
  4224. ((derived-mode-p 'org-mode)
  4225. (let ((org-inhibit-startup t)) (org-mode))))
  4226. (message "Groups tags support has been turned %s"
  4227. (if org-group-tags "on" "off")))
  4228. (defun org-set-regexps-and-options (&optional tags-only)
  4229. "Precompute regular expressions used in the current buffer.
  4230. When optional argument TAGS-ONLY is non-nil, only compute tags
  4231. related expressions."
  4232. (when (derived-mode-p 'org-mode)
  4233. (let ((alist (org--setup-collect-keywords
  4234. (org-make-options-regexp
  4235. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4236. (and (not tags-only)
  4237. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4238. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4239. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4240. ;; Startup options. Get this early since it does change
  4241. ;; behavior for other options (e.g., tags).
  4242. (let ((startup (cdr (assq 'startup alist))))
  4243. (dolist (option startup)
  4244. (let ((entry (assoc-string option org-startup-options t)))
  4245. (when entry
  4246. (let ((var (nth 1 entry))
  4247. (val (nth 2 entry)))
  4248. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4249. (unless (listp (symbol-value var))
  4250. (set (make-local-variable var) nil))
  4251. (add-to-list var val)))))))
  4252. (setq-local org-file-tags
  4253. (mapcar #'org-add-prop-inherited
  4254. (cdr (assq 'filetags alist))))
  4255. (setq org-current-tag-alist
  4256. (append org-tag-persistent-alist
  4257. (let ((tags (cdr (assq 'tags alist))))
  4258. (if tags (org-tag-string-to-alist tags)
  4259. org-tag-alist))))
  4260. (setq org-tag-groups-alist
  4261. (org-tag-alist-to-groups org-current-tag-alist))
  4262. (unless tags-only
  4263. ;; File properties.
  4264. (setq-local org-file-properties (cdr (assq 'property alist)))
  4265. ;; Archive location.
  4266. (let ((archive (cdr (assq 'archive alist))))
  4267. (when archive (setq-local org-archive-location archive)))
  4268. ;; Category.
  4269. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4270. (when cat
  4271. (setq-local org-category (intern cat))
  4272. (setq-local org-file-properties
  4273. (org--update-property-plist
  4274. "CATEGORY" cat org-file-properties))))
  4275. ;; Columns.
  4276. (let ((column (cdr (assq 'columns alist))))
  4277. (when column (setq-local org-columns-default-format column)))
  4278. ;; Constants.
  4279. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4280. ;; Link abbreviations.
  4281. (let ((links (cdr (assq 'link alist))))
  4282. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4283. ;; Priorities.
  4284. (let ((priorities (cdr (assq 'priorities alist))))
  4285. (when priorities
  4286. (setq-local org-highest-priority (nth 0 priorities))
  4287. (setq-local org-lowest-priority (nth 1 priorities))
  4288. (setq-local org-default-priority (nth 2 priorities))))
  4289. ;; Scripts.
  4290. (let ((scripts (assq 'scripts alist)))
  4291. (when scripts
  4292. (setq-local org-use-sub-superscripts (cdr scripts))))
  4293. ;; TODO keywords.
  4294. (setq-local org-todo-kwd-alist nil)
  4295. (setq-local org-todo-key-alist nil)
  4296. (setq-local org-todo-key-trigger nil)
  4297. (setq-local org-todo-keywords-1 nil)
  4298. (setq-local org-done-keywords nil)
  4299. (setq-local org-todo-heads nil)
  4300. (setq-local org-todo-sets nil)
  4301. (setq-local org-todo-log-states nil)
  4302. (let ((todo-sequences
  4303. (or (nreverse (cdr (assq 'todo alist)))
  4304. (let ((d (default-value 'org-todo-keywords)))
  4305. (if (not (stringp (car d))) d
  4306. ;; XXX: Backward compatibility code.
  4307. (list (cons org-todo-interpretation d)))))))
  4308. (dolist (sequence todo-sequences)
  4309. (let* ((sequence (or (run-hook-with-args-until-success
  4310. 'org-todo-setup-filter-hook sequence)
  4311. sequence))
  4312. (sequence-type (car sequence))
  4313. (keywords (cdr sequence))
  4314. (sep (member "|" keywords))
  4315. names alist)
  4316. (dolist (k (remove "|" keywords))
  4317. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4318. k)
  4319. (error "Invalid TODO keyword %s" k))
  4320. (let ((name (match-string 1 k))
  4321. (key (match-string 2 k))
  4322. (log (org-extract-log-state-settings k)))
  4323. (push name names)
  4324. (push (cons name (and key (string-to-char key))) alist)
  4325. (when log (push log org-todo-log-states))))
  4326. (let* ((names (nreverse names))
  4327. (done (if sep (org-remove-keyword-keys (cdr sep))
  4328. (last names)))
  4329. (head (car names))
  4330. (tail (list sequence-type head (car done) (org-last done))))
  4331. (add-to-list 'org-todo-heads head 'append)
  4332. (push names org-todo-sets)
  4333. (setq org-done-keywords (append org-done-keywords done nil))
  4334. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4335. (setq org-todo-key-alist
  4336. (append org-todo-key-alist
  4337. (and alist
  4338. (append '((:startgroup))
  4339. (nreverse alist)
  4340. '((:endgroup))))))
  4341. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4342. (setq org-todo-sets (nreverse org-todo-sets)
  4343. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4344. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4345. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4346. ;; Compute the regular expressions and other local variables.
  4347. ;; Using `org-outline-regexp-bol' would complicate them much,
  4348. ;; because of the fixed white space at the end of that string.
  4349. (unless org-done-keywords
  4350. (setq org-done-keywords
  4351. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4352. (setq org-not-done-keywords
  4353. (org-delete-all org-done-keywords
  4354. (copy-sequence org-todo-keywords-1))
  4355. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4356. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4357. org-not-done-heading-regexp
  4358. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4359. org-todo-line-regexp
  4360. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4361. org-complex-heading-regexp
  4362. (concat "^\\(\\*+\\)"
  4363. "\\(?: +" org-todo-regexp "\\)?"
  4364. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4365. "\\(?: +\\(.*?\\)\\)??"
  4366. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4367. "[ \t]*$")
  4368. org-complex-heading-regexp-format
  4369. (concat "^\\(\\*+\\)"
  4370. "\\(?: +" org-todo-regexp "\\)?"
  4371. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4372. "\\(?: +"
  4373. ;; Stats cookies can be stuck to body.
  4374. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4375. "\\(%s\\)"
  4376. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4377. "\\)"
  4378. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4379. "[ \t]*$")
  4380. org-todo-line-tags-regexp
  4381. (concat "^\\(\\*+\\)"
  4382. "\\(?: +" org-todo-regexp "\\)?"
  4383. "\\(?: +\\(.*?\\)\\)??"
  4384. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4385. "[ \t]*$"))
  4386. (org-compute-latex-and-related-regexp)))))
  4387. (defun org--setup-collect-keywords (regexp &optional files alist)
  4388. "Return setup keywords values as an alist.
  4389. REGEXP matches a subset of setup keywords. FILES is a list of
  4390. file names already visited. It is used to avoid circular setup
  4391. files. ALIST, when non-nil, is the alist computed so far.
  4392. Return value contains the following keys: `archive', `category',
  4393. `columns', `constants', `filetags', `link', `priorities',
  4394. `property', `scripts', `startup', `tags' and `todo'."
  4395. (org-with-wide-buffer
  4396. (goto-char (point-min))
  4397. (let ((case-fold-search t))
  4398. (while (re-search-forward regexp nil t)
  4399. (let ((element (org-element-at-point)))
  4400. (when (eq (org-element-type element) 'keyword)
  4401. (let ((key (org-element-property :key element))
  4402. (value (org-element-property :value element)))
  4403. (cond
  4404. ((equal key "ARCHIVE")
  4405. (when (org-string-nw-p value)
  4406. (push (cons 'archive value) alist)))
  4407. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4408. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4409. ((equal key "CONSTANTS")
  4410. (let* ((constants (assq 'constants alist))
  4411. (store (cdr constants)))
  4412. (dolist (pair (split-string value))
  4413. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4414. pair)
  4415. (let* ((name (match-string 1 pair))
  4416. (value (match-string 2 pair))
  4417. (old (assoc name store)))
  4418. (if old (setcdr old value)
  4419. (push (cons name value) store)))))
  4420. (if constants (setcdr constants store)
  4421. (push (cons 'constants store) alist))))
  4422. ((equal key "FILETAGS")
  4423. (when (org-string-nw-p value)
  4424. (let ((old (assq 'filetags alist))
  4425. (new (apply #'nconc
  4426. (mapcar (lambda (x) (org-split-string x ":"))
  4427. (split-string value)))))
  4428. (if old (setcdr old (append new (cdr old)))
  4429. (push (cons 'filetags new) alist)))))
  4430. ((equal key "LINK")
  4431. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4432. (let ((links (assq 'link alist))
  4433. (pair (cons (match-string-no-properties 1 value)
  4434. (match-string-no-properties 2 value))))
  4435. (if links (push pair (cdr links))
  4436. (push (list 'link pair) alist)))))
  4437. ((equal key "OPTIONS")
  4438. (when (and (org-string-nw-p value)
  4439. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4440. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4441. ((equal key "PRIORITIES")
  4442. (push (cons 'priorities
  4443. (let ((prio (split-string value)))
  4444. (if (< (length prio) 3) '(?A ?C ?B)
  4445. (mapcar #'string-to-char prio))))
  4446. alist))
  4447. ((equal key "PROPERTY")
  4448. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4449. (let* ((property (assq 'property alist))
  4450. (value (org--update-property-plist
  4451. (match-string-no-properties 1 value)
  4452. (match-string-no-properties 2 value)
  4453. (cdr property))))
  4454. (if property (setcdr property value)
  4455. (push (cons 'property value) alist)))))
  4456. ((equal key "STARTUP")
  4457. (let ((startup (assq 'startup alist)))
  4458. (if startup
  4459. (setcdr startup
  4460. (append (cdr startup) (split-string value)))
  4461. (push (cons 'startup (split-string value)) alist))))
  4462. ((equal key "TAGS")
  4463. (let ((tag-cell (assq 'tags alist)))
  4464. (if tag-cell
  4465. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4466. (push (cons 'tags value) alist))))
  4467. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4468. (let ((todo (assq 'todo alist))
  4469. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4470. (split-string value))))
  4471. (if todo (push value (cdr todo))
  4472. (push (list 'todo value) alist))))
  4473. ((equal key "SETUPFILE")
  4474. (unless buffer-read-only ; Do not check in Gnus messages.
  4475. (let ((f (and (org-string-nw-p value)
  4476. (expand-file-name
  4477. (org-unbracket-string "\"" "\"" value)))))
  4478. (when (and f (file-readable-p f) (not (member f files)))
  4479. (with-temp-buffer
  4480. (setq default-directory (file-name-directory f))
  4481. (insert-file-contents f)
  4482. (setq alist
  4483. ;; Fake Org mode to benefit from cache
  4484. ;; without recurring needlessly.
  4485. (let ((major-mode 'org-mode))
  4486. (org--setup-collect-keywords
  4487. regexp (cons f files) alist)))))))))))))))
  4488. alist)
  4489. (defun org-tag-string-to-alist (s)
  4490. "Return tag alist associated to string S.
  4491. S is a value for TAGS keyword or produced with
  4492. `org-tag-alist-to-string'. Return value is an alist suitable for
  4493. `org-tag-alist' or `org-tag-persistent-alist'."
  4494. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4495. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4496. "\\|{.+?}\\)" ; regular expression
  4497. "\\(?:(\\(.\\))\\)?\\'"))
  4498. alist group-flag)
  4499. (dolist (tokens lines (cdr (nreverse alist)))
  4500. (push '(:newline) alist)
  4501. (while tokens
  4502. (let ((token (pop tokens)))
  4503. (pcase token
  4504. ("{"
  4505. (push '(:startgroup) alist)
  4506. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4507. ("}"
  4508. (push '(:endgroup) alist)
  4509. (setq group-flag nil))
  4510. ("["
  4511. (push '(:startgrouptag) alist)
  4512. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4513. ("]"
  4514. (push '(:endgrouptag) alist)
  4515. (setq group-flag nil))
  4516. (":"
  4517. (push '(:grouptags) alist))
  4518. ((guard (string-match tag-re token))
  4519. (let ((tag (match-string 1 token))
  4520. (key (and (match-beginning 2)
  4521. (string-to-char (match-string 2 token)))))
  4522. ;; Push all tags in groups, no matter if they already
  4523. ;; appear somewhere else in the list.
  4524. (when (or group-flag (not (assoc tag alist)))
  4525. (push (cons tag key) alist))))))))))
  4526. (defun org-tag-alist-to-string (alist &optional skip-key)
  4527. "Return tag string associated to ALIST.
  4528. ALIST is an alist, as defined in `org-tag-alist' or
  4529. `org-tag-persistent-alist', or produced with
  4530. `org-tag-string-to-alist'.
  4531. Return value is a string suitable as a value for \"TAGS\"
  4532. keyword.
  4533. When optional argument SKIP-KEY is non-nil, skip selection keys
  4534. next to tags."
  4535. (mapconcat (lambda (token)
  4536. (pcase token
  4537. (`(:startgroup) "{")
  4538. (`(:endgroup) "}")
  4539. (`(:startgrouptag) "[")
  4540. (`(:endgrouptag) "]")
  4541. (`(:grouptags) ":")
  4542. (`(:newline) "\\n")
  4543. ((and
  4544. (guard (not skip-key))
  4545. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4546. (format "%s(%c)" tag key))
  4547. (`(,(and tag (pred stringp)) . ,_) tag)
  4548. (_ (user-error "Invalid tag token: %S" token))))
  4549. alist
  4550. " "))
  4551. (defun org-tag-alist-to-groups (alist)
  4552. "Return group alist from tag ALIST.
  4553. ALIST is an alist, as defined in `org-tag-alist' or
  4554. `org-tag-persistent-alist', or produced with
  4555. `org-tag-string-to-alist'. Return value is an alist following
  4556. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4557. a string, summarizing TAGS, as a list of strings."
  4558. (let (groups group-status current-group)
  4559. (dolist (token alist (nreverse groups))
  4560. (pcase token
  4561. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4562. (`(,(or :endgroup :endgrouptag))
  4563. (when (eq group-status 'append)
  4564. (push (nreverse current-group) groups))
  4565. (setq group-status nil))
  4566. (`(:grouptags) (setq group-status 'append))
  4567. ((and `(,tag . ,_) (guard group-status))
  4568. (if (eq group-status 'append) (push tag current-group)
  4569. (setq current-group (list tag))))
  4570. (_ nil)))))
  4571. (defvar org--file-cache (make-hash-table :test #'equal)
  4572. "Hash table to store contents of files referenced via a URL.
  4573. This is the cache of file URLs read using `org-file-contents'.")
  4574. (defun org-reset-file-cache ()
  4575. "Reset the cache of files downloaded by `org-file-contents'."
  4576. (clrhash org--file-cache))
  4577. (defun org-file-url-p (file)
  4578. "Non-nil if FILE is a URL."
  4579. (require 'ffap)
  4580. (string-match-p ffap-url-regexp file))
  4581. (defun org-file-contents (file &optional noerror nocache)
  4582. "Return the contents of FILE, as a string.
  4583. FILE can be a file name or URL.
  4584. If FILE is a URL, download the contents. If the URL contents are
  4585. already cached in the `org--file-cache' hash table, the download step
  4586. is skipped.
  4587. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4588. from file or URL.
  4589. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4590. is available. This option applies only if FILE is a URL."
  4591. (let* ((is-url (org-file-url-p file))
  4592. (cache (and is-url
  4593. (not nocache)
  4594. (gethash file org--file-cache))))
  4595. (cond
  4596. (cache)
  4597. (is-url
  4598. (with-current-buffer (url-retrieve-synchronously file)
  4599. (goto-char (point-min))
  4600. ;; Move point to after the url-retrieve header.
  4601. (search-forward "\n\n" nil :move)
  4602. ;; Search for the success code only in the url-retrieve header.
  4603. (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4604. ;; Update the cache `org--file-cache' and return contents.
  4605. (puthash file
  4606. (buffer-substring-no-properties (point) (point-max))
  4607. org--file-cache)
  4608. (funcall (if noerror #'message #'user-error)
  4609. "Unable to fetch file from %S"
  4610. file))))
  4611. (t
  4612. (with-temp-buffer
  4613. (condition-case err
  4614. (progn
  4615. (insert-file-contents file)
  4616. (buffer-string))
  4617. (file-error
  4618. (funcall (if noerror #'message #'user-error)
  4619. (error-message-string err)))))))))
  4620. (defun org-extract-log-state-settings (x)
  4621. "Extract the log state setting from a TODO keyword string.
  4622. This will extract info from a string like \"WAIT(w@/!)\"."
  4623. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4624. (let ((kw (match-string 1 x))
  4625. (log1 (and (match-end 3) (match-string 3 x)))
  4626. (log2 (and (match-end 4) (match-string 4 x))))
  4627. (and (or log1 log2)
  4628. (list kw
  4629. (and log1 (if (equal log1 "!") 'time 'note))
  4630. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4631. (defun org-remove-keyword-keys (list)
  4632. "Remove a pair of parenthesis at the end of each string in LIST."
  4633. (mapcar (lambda (x)
  4634. (if (string-match "(.*)$" x)
  4635. (substring x 0 (match-beginning 0))
  4636. x))
  4637. list))
  4638. (defun org-assign-fast-keys (alist)
  4639. "Assign fast keys to a keyword-key alist.
  4640. Respect keys that are already there."
  4641. (let (new e (alt ?0))
  4642. (while (setq e (pop alist))
  4643. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4644. (cdr e)) ;; Key already assigned.
  4645. (push e new)
  4646. (let ((clist (string-to-list (downcase (car e))))
  4647. (used (append new alist)))
  4648. (when (= (car clist) ?@)
  4649. (pop clist))
  4650. (while (and clist (rassoc (car clist) used))
  4651. (pop clist))
  4652. (unless clist
  4653. (while (rassoc alt used)
  4654. (cl-incf alt)))
  4655. (push (cons (car e) (or (car clist) alt)) new))))
  4656. (nreverse new)))
  4657. ;;; Some variables used in various places
  4658. (defvar org-window-configuration nil
  4659. "Used in various places to store a window configuration.")
  4660. (defvar org-selected-window nil
  4661. "Used in various places to store a window configuration.")
  4662. (defvar org-finish-function nil
  4663. "Function to be called when `C-c C-c' is used.
  4664. This is for getting out of special buffers like capture.")
  4665. (defvar org-last-state)
  4666. ;; Defined somewhere in this file, but used before definition.
  4667. (defvar org-entities) ;; defined in org-entities.el
  4668. (defvar org-struct-menu)
  4669. (defvar org-org-menu)
  4670. (defvar org-tbl-menu)
  4671. ;;;; Define the Org mode
  4672. ;; We use a before-change function to check if a table might need
  4673. ;; an update.
  4674. (defvar org-table-may-need-update t
  4675. "Indicates that a table might need an update.
  4676. This variable is set by `org-before-change-function'.
  4677. `org-table-align' sets it back to nil.")
  4678. (defun org-before-change-function (_beg _end)
  4679. "Every change indicates that a table might need an update."
  4680. (setq org-table-may-need-update t))
  4681. (defvar org-mode-map)
  4682. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4683. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4684. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4685. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4686. (defvar org-table-buffer-is-an nil)
  4687. (defvar bidi-paragraph-direction)
  4688. (defvar buffer-face-mode-face)
  4689. (require 'outline)
  4690. ;; Other stuff we need.
  4691. (require 'time-date)
  4692. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4693. (require 'easymenu)
  4694. (autoload 'easy-menu-add "easymenu")
  4695. (require 'overlay)
  4696. ;; (require 'org-macs) moved higher up in the file before it is first used
  4697. (require 'org-entities)
  4698. ;; (require 'org-compat) moved higher up in the file before it is first used
  4699. (require 'org-faces)
  4700. (require 'org-list)
  4701. (require 'org-pcomplete)
  4702. (require 'org-src)
  4703. (require 'org-footnote)
  4704. (require 'org-macro)
  4705. ;; babel
  4706. (require 'ob)
  4707. ;;;###autoload
  4708. (define-derived-mode org-mode outline-mode "Org"
  4709. "Outline-based notes management and organizer, alias
  4710. \"Carsten's outline-mode for keeping track of everything.\"
  4711. Org mode develops organizational tasks around a NOTES file which
  4712. contains information about projects as plain text. Org mode is
  4713. implemented on top of Outline mode, which is ideal to keep the content
  4714. of large files well structured. It supports ToDo items, deadlines and
  4715. time stamps, which magically appear in the diary listing of the Emacs
  4716. calendar. Tables are easily created with a built-in table editor.
  4717. Plain text URL-like links connect to websites, emails (VM), Usenet
  4718. messages (Gnus), BBDB entries, and any files related to the project.
  4719. For printing and sharing of notes, an Org file (or a part of it)
  4720. can be exported as a structured ASCII or HTML file.
  4721. The following commands are available:
  4722. \\{org-mode-map}"
  4723. ;; Get rid of Outline menus, they are not needed
  4724. ;; Need to do this here because define-derived-mode sets up
  4725. ;; the keymap so late. Still, it is a waste to call this each time
  4726. ;; we switch another buffer into Org mode.
  4727. (define-key org-mode-map [menu-bar headings] 'undefined)
  4728. (define-key org-mode-map [menu-bar hide] 'undefined)
  4729. (define-key org-mode-map [menu-bar show] 'undefined)
  4730. (org-load-modules-maybe)
  4731. (org-install-agenda-files-menu)
  4732. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4733. (add-to-invisibility-spec '(org-hide-block . t))
  4734. (setq-local outline-regexp org-outline-regexp)
  4735. (setq-local outline-level 'org-outline-level)
  4736. (setq bidi-paragraph-direction 'left-to-right)
  4737. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4738. (unless org-display-table
  4739. (setq org-display-table (make-display-table)))
  4740. (set-display-table-slot
  4741. org-display-table 4
  4742. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4743. org-ellipsis)))
  4744. (setq buffer-display-table org-display-table))
  4745. (org-set-regexps-and-options)
  4746. (org-set-font-lock-defaults)
  4747. (when (and org-tag-faces (not org-tags-special-faces-re))
  4748. ;; tag faces set outside customize.... force initialization.
  4749. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4750. ;; Calc embedded
  4751. (setq-local calc-embedded-open-mode "# ")
  4752. ;; Modify a few syntax entries
  4753. (modify-syntax-entry ?@ "w")
  4754. (modify-syntax-entry ?\" "\"")
  4755. (modify-syntax-entry ?\\ "_")
  4756. (modify-syntax-entry ?~ "_")
  4757. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4758. ;; Activate before-change-function
  4759. (setq-local org-table-may-need-update t)
  4760. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4761. ;; Check for running clock before killing a buffer
  4762. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4763. ;; Initialize macros templates.
  4764. (org-macro-initialize-templates)
  4765. ;; Initialize radio targets.
  4766. (org-update-radio-target-regexp)
  4767. ;; Indentation.
  4768. (setq-local indent-line-function 'org-indent-line)
  4769. (setq-local indent-region-function 'org-indent-region)
  4770. ;; Filling and auto-filling.
  4771. (org-setup-filling)
  4772. ;; Comments.
  4773. (org-setup-comments-handling)
  4774. ;; Initialize cache.
  4775. (org-element-cache-reset)
  4776. ;; Beginning/end of defun
  4777. (setq-local beginning-of-defun-function 'org-backward-element)
  4778. (setq-local end-of-defun-function
  4779. (lambda ()
  4780. (if (not (org-at-heading-p))
  4781. (org-forward-element)
  4782. (org-forward-element)
  4783. (forward-char -1))))
  4784. ;; Next error for sparse trees
  4785. (setq-local next-error-function 'org-occur-next-match)
  4786. ;; Make sure dependence stuff works reliably, even for users who set it
  4787. ;; too late :-(
  4788. (if org-enforce-todo-dependencies
  4789. (add-hook 'org-blocker-hook
  4790. 'org-block-todo-from-children-or-siblings-or-parent)
  4791. (remove-hook 'org-blocker-hook
  4792. 'org-block-todo-from-children-or-siblings-or-parent))
  4793. (if org-enforce-todo-checkbox-dependencies
  4794. (add-hook 'org-blocker-hook
  4795. 'org-block-todo-from-checkboxes)
  4796. (remove-hook 'org-blocker-hook
  4797. 'org-block-todo-from-checkboxes))
  4798. ;; Align options lines
  4799. (setq-local
  4800. align-mode-rules-list
  4801. '((org-in-buffer-settings
  4802. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4803. (modes . '(org-mode)))))
  4804. ;; Imenu
  4805. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4806. ;; Make isearch reveal context
  4807. (setq-local outline-isearch-open-invisible-function
  4808. (lambda (&rest _) (org-show-context 'isearch)))
  4809. ;; Setup the pcomplete hooks
  4810. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4811. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4812. (setq-local pcomplete-default-completion-function 'ignore)
  4813. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4814. (setq-local pcomplete-termination-string "")
  4815. (setq-local buffer-face-mode-face 'org-default)
  4816. ;; If empty file that did not turn on Org mode automatically, make
  4817. ;; it to.
  4818. (when (and org-insert-mode-line-in-empty-file
  4819. (called-interactively-p 'any)
  4820. (= (point-min) (point-max)))
  4821. (insert "# -*- mode: org -*-\n\n"))
  4822. (unless org-inhibit-startup
  4823. (org-unmodified
  4824. (when org-startup-with-beamer-mode (org-beamer-mode))
  4825. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4826. (org-table-map-tables
  4827. (cond ((and org-startup-align-all-tables
  4828. org-startup-shrink-all-tables)
  4829. (lambda () (org-table-align) (org-table-shrink)))
  4830. (org-startup-align-all-tables #'org-table-align)
  4831. (t #'org-table-shrink))
  4832. t))
  4833. (when org-startup-with-inline-images (org-display-inline-images))
  4834. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4835. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4836. (when org-startup-truncated (setq truncate-lines t))
  4837. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4838. (org-refresh-effort-properties)))
  4839. ;; Try to set `org-hide' face correctly.
  4840. (let ((foreground (org-find-invisible-foreground)))
  4841. (when foreground
  4842. (set-face-foreground 'org-hide foreground))))
  4843. ;; Update `customize-package-emacs-version-alist'
  4844. (add-to-list 'customize-package-emacs-version-alist
  4845. '(Org ("8.0" . "24.4")
  4846. ("8.1" . "24.4")
  4847. ("8.2" . "24.4")
  4848. ("8.2.7" . "24.4")
  4849. ("8.3" . "26.1")
  4850. ("9.0" . "26.1")
  4851. ("9.1" . "26.1")))
  4852. (defvar org-mode-transpose-word-syntax-table
  4853. (let ((st (make-syntax-table text-mode-syntax-table)))
  4854. (dolist (c org-emphasis-alist st)
  4855. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4856. (when (fboundp 'abbrev-table-put)
  4857. (abbrev-table-put org-mode-abbrev-table
  4858. :parents (list text-mode-abbrev-table)))
  4859. (defun org-find-invisible-foreground ()
  4860. (let ((candidates (remove
  4861. "unspecified-bg"
  4862. (nconc
  4863. (list (face-background 'default)
  4864. (face-background 'org-default))
  4865. (mapcar
  4866. (lambda (alist)
  4867. (when (boundp alist)
  4868. (cdr (assq 'background-color (symbol-value alist)))))
  4869. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4870. (list (face-foreground 'org-hide))))))
  4871. (car (remove nil candidates))))
  4872. (defun org-current-time (&optional rounding-minutes past)
  4873. "Current time, possibly rounded to ROUNDING-MINUTES.
  4874. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4875. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4876. the rounding returns a past time."
  4877. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4878. (car org-time-stamp-rounding-minutes)))
  4879. (time (decode-time)) res)
  4880. (if (< r 1)
  4881. (current-time)
  4882. (setq res
  4883. (apply 'encode-time
  4884. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4885. (nthcdr 2 time))))
  4886. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4887. (seconds-to-time (- (float-time res) (* r 60)))
  4888. res))))
  4889. (defun org-today ()
  4890. "Return today date, considering `org-extend-today-until'."
  4891. (time-to-days
  4892. (time-subtract (current-time)
  4893. (list 0 (* 3600 org-extend-today-until) 0))))
  4894. ;;;; Font-Lock stuff, including the activators
  4895. (defvar org-mouse-map (make-sparse-keymap))
  4896. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4897. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4898. (when org-mouse-1-follows-link
  4899. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4900. (when org-tab-follows-link
  4901. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4902. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4903. (require 'font-lock)
  4904. (defconst org-non-link-chars "]\t\n\r<>")
  4905. (defvar org-link-types-re nil
  4906. "Matches a link that has a url-like prefix like \"http:\"")
  4907. (defvar org-link-re-with-space nil
  4908. "Matches a link with spaces, optional angular brackets around it.")
  4909. (defvar org-link-re-with-space2 nil
  4910. "Matches a link with spaces, optional angular brackets around it.")
  4911. (defvar org-link-re-with-space3 nil
  4912. "Matches a link with spaces, only for internal part in bracket links.")
  4913. (defvar org-angle-link-re nil
  4914. "Matches link with angular brackets, spaces are allowed.")
  4915. (defvar org-plain-link-re nil
  4916. "Matches plain link, without spaces.")
  4917. (defvar org-bracket-link-regexp nil
  4918. "Matches a link in double brackets.")
  4919. (defvar org-bracket-link-analytic-regexp nil
  4920. "Regular expression used to analyze links.
  4921. Here is what the match groups contain after a match:
  4922. 1: http:
  4923. 2: http
  4924. 3: path
  4925. 4: [desc]
  4926. 5: desc")
  4927. (defvar org-bracket-link-analytic-regexp++ nil
  4928. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4929. (defvar org-any-link-re nil
  4930. "Regular expression matching any link.")
  4931. (defconst org-match-sexp-depth 3
  4932. "Number of stacked braces for sub/superscript matching.")
  4933. (defun org-create-multibrace-regexp (left right n)
  4934. "Create a regular expression which will match a balanced sexp.
  4935. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4936. as single character strings.
  4937. The regexp returned will match the entire expression including the
  4938. delimiters. It will also define a single group which contains the
  4939. match except for the outermost delimiters. The maximum depth of
  4940. stacked delimiters is N. Escaping delimiters is not possible."
  4941. (let* ((nothing (concat "[^" left right "]*?"))
  4942. (or "\\|")
  4943. (re nothing)
  4944. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4945. (while (> n 1)
  4946. (setq n (1- n)
  4947. re (concat re or next)
  4948. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4949. (concat left "\\(" re "\\)" right)))
  4950. (defconst org-match-substring-regexp
  4951. (concat
  4952. "\\(\\S-\\)\\([_^]\\)\\("
  4953. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4954. "\\|"
  4955. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4956. "\\|"
  4957. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4958. "The regular expression matching a sub- or superscript.")
  4959. (defconst org-match-substring-with-braces-regexp
  4960. (concat
  4961. "\\(\\S-\\)\\([_^]\\)"
  4962. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4963. "The regular expression matching a sub- or superscript, forcing braces.")
  4964. (defun org-make-link-regexps ()
  4965. "Update the link regular expressions.
  4966. This should be called after the variable `org-link-parameters' has changed."
  4967. (let ((types-re (regexp-opt (org-link-types) t)))
  4968. (setq org-link-types-re
  4969. (concat "\\`" types-re ":")
  4970. org-link-re-with-space
  4971. (concat "<?" types-re ":"
  4972. "\\([^" org-non-link-chars " ]"
  4973. "[^" org-non-link-chars "]*"
  4974. "[^" org-non-link-chars " ]\\)>?")
  4975. org-link-re-with-space2
  4976. (concat "<?" types-re ":"
  4977. "\\([^" org-non-link-chars " ]"
  4978. "[^\t\n\r]*"
  4979. "[^" org-non-link-chars " ]\\)>?")
  4980. org-link-re-with-space3
  4981. (concat "<?" types-re ":"
  4982. "\\([^" org-non-link-chars " ]"
  4983. "[^\t\n\r]*\\)")
  4984. org-angle-link-re
  4985. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4986. types-re)
  4987. org-plain-link-re
  4988. (concat
  4989. "\\<" types-re ":"
  4990. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4991. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4992. org-bracket-link-regexp
  4993. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4994. org-bracket-link-analytic-regexp
  4995. (concat
  4996. "\\[\\["
  4997. "\\(" types-re ":\\)?"
  4998. "\\([^]]+\\)"
  4999. "\\]"
  5000. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5001. "\\]")
  5002. org-bracket-link-analytic-regexp++
  5003. (concat
  5004. "\\[\\["
  5005. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5006. "\\([^]]+\\)"
  5007. "\\]"
  5008. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5009. "\\]")
  5010. org-any-link-re
  5011. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5012. org-angle-link-re "\\)\\|\\("
  5013. org-plain-link-re "\\)"))))
  5014. (org-make-link-regexps)
  5015. (defvar org-emph-face nil)
  5016. (defun org-do-emphasis-faces (limit)
  5017. "Run through the buffer and emphasize strings."
  5018. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  5019. (car org-emphasis-regexp-components))))
  5020. (catch :exit
  5021. (while (re-search-forward quick-re limit t)
  5022. (let* ((marker (match-string 2))
  5023. (verbatim? (member marker '("~" "="))))
  5024. (when (save-excursion
  5025. (goto-char (match-beginning 0))
  5026. ;; Do not match headline stars. Do not consider
  5027. ;; stars of a headline as closing marker for bold
  5028. ;; markup either. Do not match table hlines.
  5029. (and
  5030. (not (looking-at-p org-outline-regexp-bol))
  5031. (not (and (equal marker "+")
  5032. (org-match-line
  5033. "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  5034. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5035. (not (string-match-p
  5036. (concat org-outline-regexp-bol "\\'")
  5037. (match-string 0)))))
  5038. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5039. (font-lock-prepend-text-property
  5040. (match-beginning 2) (match-end 2) 'face face)
  5041. (when verbatim?
  5042. (org-remove-flyspell-overlays-in
  5043. (match-beginning 0) (match-end 0)))
  5044. (add-text-properties (match-beginning 2) (match-end 2)
  5045. '(font-lock-multiline t org-emphasis t))
  5046. (when org-hide-emphasis-markers
  5047. (add-text-properties (match-end 4) (match-beginning 5)
  5048. '(invisible org-link))
  5049. (add-text-properties (match-beginning 3) (match-end 3)
  5050. '(invisible org-link)))
  5051. (throw :exit t))))))))
  5052. (defun org-emphasize (&optional char)
  5053. "Insert or change an emphasis, i.e. a font like bold or italic.
  5054. If there is an active region, change that region to a new emphasis.
  5055. If there is no region, just insert the marker characters and position
  5056. the cursor between them.
  5057. CHAR should be the marker character. If it is a space, it means to
  5058. remove the emphasis of the selected region.
  5059. If CHAR is not given (for example in an interactive call) it will be
  5060. prompted for."
  5061. (interactive)
  5062. (let ((erc org-emphasis-regexp-components)
  5063. (string "") beg end move s)
  5064. (if (org-region-active-p)
  5065. (setq beg (region-beginning)
  5066. end (region-end)
  5067. string (buffer-substring beg end))
  5068. (setq move t))
  5069. (unless char
  5070. (message "Emphasis marker or tag: [%s]"
  5071. (mapconcat #'car org-emphasis-alist ""))
  5072. (setq char (read-char-exclusive)))
  5073. (if (equal char ?\s)
  5074. (setq s ""
  5075. move nil)
  5076. (unless (assoc (char-to-string char) org-emphasis-alist)
  5077. (user-error "No such emphasis marker: \"%c\"" char))
  5078. (setq s (char-to-string char)))
  5079. (while (and (> (length string) 1)
  5080. (equal (substring string 0 1) (substring string -1))
  5081. (assoc (substring string 0 1) org-emphasis-alist))
  5082. (setq string (substring string 1 -1)))
  5083. (setq string (concat s string s))
  5084. (when beg (delete-region beg end))
  5085. (unless (or (bolp)
  5086. (string-match (concat "[" (nth 0 erc) "\n]")
  5087. (char-to-string (char-before (point)))))
  5088. (insert " "))
  5089. (unless (or (eobp)
  5090. (string-match (concat "[" (nth 1 erc) "\n]")
  5091. (char-to-string (char-after (point)))))
  5092. (insert " ") (backward-char 1))
  5093. (insert string)
  5094. (and move (backward-char 1))))
  5095. (defconst org-nonsticky-props
  5096. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5097. (defsubst org-rear-nonsticky-at (pos)
  5098. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5099. (defun org-activate-links (limit)
  5100. "Add link properties to links.
  5101. This includes angle, plain, and bracket links."
  5102. (catch :exit
  5103. (while (re-search-forward org-any-link-re limit t)
  5104. (let* ((start (match-beginning 0))
  5105. (end (match-end 0))
  5106. (style (cond ((eq ?< (char-after start)) 'angle)
  5107. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5108. (t 'plain))))
  5109. (when (and (memq style org-highlight-links)
  5110. ;; Do not confuse plain links with tags.
  5111. (not (and (eq style 'plain)
  5112. (let ((face (get-text-property
  5113. (max (1- start) (point-min)) 'face)))
  5114. (if (consp face) (memq 'org-tag face)
  5115. (eq 'org-tag face))))))
  5116. (let* ((link-object (save-excursion
  5117. (goto-char start)
  5118. (save-match-data (org-element-link-parser))))
  5119. (link (org-element-property :raw-link link-object))
  5120. (type (org-element-property :type link-object))
  5121. (path (org-element-property :path link-object))
  5122. (properties ;for link's visible part
  5123. (list
  5124. 'face (pcase (org-link-get-parameter type :face)
  5125. ((and (pred functionp) face) (funcall face path))
  5126. ((and (pred facep) face) face)
  5127. ((and (pred consp) face) face) ;anonymous
  5128. (_ 'org-link))
  5129. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5130. 'highlight)
  5131. 'keymap (or (org-link-get-parameter type :keymap)
  5132. org-mouse-map)
  5133. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5134. ((and (pred stringp) echo) echo)
  5135. ((and (pred functionp) echo) echo)
  5136. (_ (concat "LINK: " link)))
  5137. 'htmlize-link (pcase (org-link-get-parameter type
  5138. :htmlize-link)
  5139. ((and (pred functionp) f) (funcall f))
  5140. (_ `(:uri ,link)))
  5141. 'font-lock-multiline t)))
  5142. (org-remove-flyspell-overlays-in start end)
  5143. (org-rear-nonsticky-at end)
  5144. (if (not (eq 'bracket style))
  5145. (add-text-properties start end properties)
  5146. ;; Handle invisible parts in bracket links.
  5147. (remove-text-properties start end '(invisible nil))
  5148. (let ((hidden
  5149. (append `(invisible
  5150. ,(or (org-link-get-parameter type :display)
  5151. 'org-link))
  5152. properties))
  5153. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5154. (visible-end (or (match-end 4) (match-end 2))))
  5155. (add-text-properties start visible-start hidden)
  5156. (add-text-properties visible-start visible-end properties)
  5157. (add-text-properties visible-end end hidden)
  5158. (org-rear-nonsticky-at visible-start)
  5159. (org-rear-nonsticky-at visible-end)))
  5160. (let ((f (org-link-get-parameter type :activate-func)))
  5161. (when (functionp f)
  5162. (funcall f start end path (eq style 'bracket))))
  5163. (throw :exit t))))) ;signal success
  5164. nil))
  5165. (defun org-activate-code (limit)
  5166. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5167. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5168. (remove-text-properties (match-beginning 0) (match-end 0)
  5169. '(display t invisible t intangible t))
  5170. t))
  5171. (defcustom org-src-fontify-natively t
  5172. "When non-nil, fontify code in code blocks.
  5173. See also the `org-block' face."
  5174. :type 'boolean
  5175. :version "26.1"
  5176. :package-version '(Org . "8.3")
  5177. :group 'org-appearance
  5178. :group 'org-babel)
  5179. (defcustom org-allow-promoting-top-level-subtree nil
  5180. "When non-nil, allow promoting a top level subtree.
  5181. The leading star of the top level headline will be replaced
  5182. by a #."
  5183. :type 'boolean
  5184. :version "24.1"
  5185. :group 'org-appearance)
  5186. (defun org-fontify-meta-lines-and-blocks (limit)
  5187. (condition-case nil
  5188. (org-fontify-meta-lines-and-blocks-1 limit)
  5189. (error (message "org-mode fontification error in %S at %d"
  5190. (current-buffer)
  5191. (line-number-at-pos)))))
  5192. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5193. "Fontify #+ lines and blocks."
  5194. (let ((case-fold-search t))
  5195. (when (re-search-forward
  5196. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5197. limit t)
  5198. (let ((beg (match-beginning 0))
  5199. (block-start (match-end 0))
  5200. (block-end nil)
  5201. (lang (match-string 7))
  5202. (beg1 (line-beginning-position 2))
  5203. (dc1 (downcase (match-string 2)))
  5204. (dc3 (downcase (match-string 3)))
  5205. end end1 quoting block-type)
  5206. (cond
  5207. ((and (match-end 4) (equal dc3 "+begin"))
  5208. ;; Truly a block
  5209. (setq block-type (downcase (match-string 5))
  5210. quoting (member block-type org-protecting-blocks))
  5211. (when (re-search-forward
  5212. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5213. nil t) ;; on purpose, we look further than LIMIT
  5214. (setq end (min (point-max) (match-end 0))
  5215. end1 (min (point-max) (1- (match-beginning 0))))
  5216. (setq block-end (match-beginning 0))
  5217. (when quoting
  5218. (org-remove-flyspell-overlays-in beg1 end1)
  5219. (remove-text-properties beg end
  5220. '(display t invisible t intangible t)))
  5221. (add-text-properties
  5222. beg end '(font-lock-fontified t font-lock-multiline t))
  5223. (add-text-properties beg beg1 '(face org-meta-line))
  5224. (org-remove-flyspell-overlays-in beg beg1)
  5225. (add-text-properties ; For end_src
  5226. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5227. (org-remove-flyspell-overlays-in end1 end)
  5228. (cond
  5229. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5230. (org-src-font-lock-fontify-block lang block-start block-end)
  5231. (add-text-properties beg1 block-end '(src-block t)))
  5232. (quoting
  5233. (add-text-properties beg1 (min (point-max) (1+ end1))
  5234. (list 'face
  5235. (list :inherit
  5236. (let ((face-name
  5237. (intern (format "org-block-%s" lang))))
  5238. (append (and (facep face-name) (list face-name))
  5239. '(org-block))))))) ; end of source block
  5240. ((not org-fontify-quote-and-verse-blocks))
  5241. ((string= block-type "quote")
  5242. (add-face-text-property
  5243. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5244. ((string= block-type "verse")
  5245. (add-face-text-property
  5246. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5247. (add-text-properties beg beg1 '(face org-block-begin-line))
  5248. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5249. '(face org-block-end-line))
  5250. t))
  5251. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5252. (org-remove-flyspell-overlays-in
  5253. (match-beginning 0)
  5254. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5255. (add-text-properties
  5256. beg (match-end 3)
  5257. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5258. '(font-lock-fontified t invisible t)
  5259. '(font-lock-fontified t face org-document-info-keyword)))
  5260. (add-text-properties
  5261. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5262. (if (string-equal dc1 "+title:")
  5263. '(font-lock-fontified t face org-document-title)
  5264. '(font-lock-fontified t face org-document-info))))
  5265. ((string-prefix-p "+caption" dc1)
  5266. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5267. (remove-text-properties (match-beginning 0) (match-end 0)
  5268. '(display t invisible t intangible t))
  5269. ;; Handle short captions.
  5270. (save-excursion
  5271. (beginning-of-line)
  5272. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5273. (add-text-properties (line-beginning-position) (match-end 1)
  5274. '(font-lock-fontified t face org-meta-line))
  5275. (add-text-properties (match-end 0) (line-end-position)
  5276. '(font-lock-fontified t face org-block))
  5277. t)
  5278. ((member dc3 '(" " ""))
  5279. (org-remove-flyspell-overlays-in beg (match-end 0))
  5280. (add-text-properties
  5281. beg (match-end 0)
  5282. '(font-lock-fontified t face font-lock-comment-face)))
  5283. (t ;; just any other in-buffer setting, but not indented
  5284. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5285. (remove-text-properties (match-beginning 0) (match-end 0)
  5286. '(display t invisible t intangible t))
  5287. (add-text-properties beg (match-end 0)
  5288. '(font-lock-fontified t face org-meta-line))
  5289. t))))))
  5290. (defun org-fontify-drawers (limit)
  5291. "Fontify drawers."
  5292. (when (re-search-forward org-drawer-regexp limit t)
  5293. (add-text-properties
  5294. (match-beginning 0) (match-end 0)
  5295. '(font-lock-fontified t face org-special-keyword))
  5296. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5297. t))
  5298. (defun org-fontify-macros (limit)
  5299. "Fontify macros."
  5300. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5301. (add-text-properties
  5302. (match-beginning 0) (match-end 0)
  5303. '(font-lock-fontified t face org-macro))
  5304. (when org-hide-macro-markers
  5305. (add-text-properties (match-end 2) (match-beginning 2)
  5306. '(invisible t))
  5307. (add-text-properties (match-beginning 1) (match-end 1)
  5308. '(invisible t)))
  5309. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5310. t))
  5311. (defun org-activate-footnote-links (limit)
  5312. "Add text properties for footnotes."
  5313. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5314. (when fn
  5315. (let* ((beg (nth 1 fn))
  5316. (end (nth 2 fn))
  5317. (label (car fn))
  5318. (referencep (/= (line-beginning-position) beg)))
  5319. (when (and referencep (nth 3 fn))
  5320. (save-excursion
  5321. (goto-char beg)
  5322. (search-forward (or label "fn:"))
  5323. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5324. (add-text-properties beg end
  5325. (list 'mouse-face 'highlight
  5326. 'keymap org-mouse-map
  5327. 'help-echo
  5328. (if referencep "Footnote reference"
  5329. "Footnote definition")
  5330. 'font-lock-fontified t
  5331. 'font-lock-multiline t
  5332. 'face 'org-footnote))))))
  5333. (defun org-activate-dates (limit)
  5334. "Add text properties for dates."
  5335. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5336. (not (equal (char-before (match-beginning 0)) 91)))
  5337. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5338. (add-text-properties (match-beginning 0) (match-end 0)
  5339. (list 'mouse-face 'highlight
  5340. 'keymap org-mouse-map))
  5341. (org-rear-nonsticky-at (match-end 0))
  5342. (when org-display-custom-times
  5343. ;; If it's a date range, activate custom time for second date.
  5344. (when (match-end 3)
  5345. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5346. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5347. t))
  5348. (defvar-local org-target-link-regexp nil
  5349. "Regular expression matching radio targets in plain text.")
  5350. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5351. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5352. border border border))
  5353. "Regular expression matching a link target.")
  5354. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5355. "Regular expression matching a radio target.")
  5356. (defconst org-any-target-regexp
  5357. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5358. "Regular expression matching any target.")
  5359. (defun org-activate-target-links (limit)
  5360. "Add text properties for target matches."
  5361. (when org-target-link-regexp
  5362. (let ((case-fold-search t))
  5363. (when (re-search-forward org-target-link-regexp limit t)
  5364. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5365. (add-text-properties (match-beginning 1) (match-end 1)
  5366. (list 'mouse-face 'highlight
  5367. 'keymap org-mouse-map
  5368. 'help-echo "Radio target link"
  5369. 'org-linked-text t))
  5370. (org-rear-nonsticky-at (match-end 1))
  5371. t))))
  5372. (defun org-update-radio-target-regexp ()
  5373. "Find all radio targets in this file and update the regular expression.
  5374. Also refresh fontification if needed."
  5375. (interactive)
  5376. (let ((old-regexp org-target-link-regexp)
  5377. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5378. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5379. (targets
  5380. (org-with-wide-buffer
  5381. (goto-char (point-min))
  5382. (let (rtn)
  5383. (while (re-search-forward org-radio-target-regexp nil t)
  5384. ;; Make sure point is really within the object.
  5385. (backward-char)
  5386. (let ((obj (org-element-context)))
  5387. (when (eq (org-element-type obj) 'radio-target)
  5388. (cl-pushnew (org-element-property :value obj) rtn
  5389. :test #'equal))))
  5390. rtn))))
  5391. (setq org-target-link-regexp
  5392. (and targets
  5393. (concat before-re
  5394. (mapconcat
  5395. (lambda (x)
  5396. (replace-regexp-in-string
  5397. " +" "\\s-+" (regexp-quote x) t t))
  5398. targets
  5399. "\\|")
  5400. after-re)))
  5401. (unless (equal old-regexp org-target-link-regexp)
  5402. ;; Clean-up cache.
  5403. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5404. ((not org-target-link-regexp) old-regexp)
  5405. (t
  5406. (concat before-re
  5407. (mapconcat
  5408. (lambda (re)
  5409. (substring re (length before-re)
  5410. (- (length after-re))))
  5411. (list old-regexp org-target-link-regexp)
  5412. "\\|")
  5413. after-re)))))
  5414. (org-with-wide-buffer
  5415. (goto-char (point-min))
  5416. (while (re-search-forward regexp nil t)
  5417. (org-element-cache-refresh (match-beginning 1)))))
  5418. ;; Re fontify buffer.
  5419. (when (memq 'radio org-highlight-links)
  5420. (org-restart-font-lock)))))
  5421. (defvar org-latex-and-related-regexp nil
  5422. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5423. (defun org-compute-latex-and-related-regexp ()
  5424. "Compute regular expression for LaTeX, entities and sub/superscript.
  5425. Result depends on variable `org-highlight-latex-and-related'."
  5426. (setq-local
  5427. org-latex-and-related-regexp
  5428. (let* ((re-sub
  5429. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5430. ((eq org-use-sub-superscripts '{})
  5431. (list org-match-substring-with-braces-regexp))
  5432. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5433. (re-latex
  5434. (when (memq 'latex org-highlight-latex-and-related)
  5435. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5436. (delq nil
  5437. (mapcar (lambda (x)
  5438. (and (member (car x) matchers) (nth 1 x)))
  5439. org-latex-regexps)))))
  5440. (re-entities
  5441. (when (memq 'entities org-highlight-latex-and-related)
  5442. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5443. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5444. (defun org-do-latex-and-related (limit)
  5445. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5446. LIMIT bounds the search for syntax to highlight. Stop at first
  5447. highlighted object, if any. Return t if some highlighting was
  5448. done, nil otherwise."
  5449. (when (org-string-nw-p org-latex-and-related-regexp)
  5450. (catch 'found
  5451. (while (re-search-forward org-latex-and-related-regexp limit t)
  5452. (unless
  5453. (cl-some
  5454. (lambda (f)
  5455. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5456. (save-excursion
  5457. (goto-char (1+ (match-beginning 0)))
  5458. (face-at-point nil t)))
  5459. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5460. '(?_ ?^))
  5461. 1
  5462. 0)))
  5463. (font-lock-prepend-text-property
  5464. (+ offset (match-beginning 0)) (match-end 0)
  5465. 'face 'org-latex-and-related)
  5466. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5467. '(font-lock-multiline t)))
  5468. (throw 'found t)))
  5469. nil)))
  5470. (defun org-restart-font-lock ()
  5471. "Restart `font-lock-mode', to force refontification."
  5472. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5473. (font-lock-mode -1)
  5474. (font-lock-mode 1)))
  5475. (defun org-activate-tags (limit)
  5476. (when (re-search-forward
  5477. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5478. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5479. (add-text-properties (match-beginning 1) (match-end 1)
  5480. (list 'mouse-face 'highlight
  5481. 'keymap org-mouse-map))
  5482. (org-rear-nonsticky-at (match-end 1))
  5483. t))
  5484. (defun org-outline-level ()
  5485. "Compute the outline level of the heading at point.
  5486. If this is called at a normal headline, the level is the number
  5487. of stars. Use `org-reduced-level' to remove the effect of
  5488. `org-odd-levels'. Unlike to `org-current-level', this function
  5489. takes into consideration inlinetasks."
  5490. (org-with-wide-buffer
  5491. (end-of-line)
  5492. (if (re-search-backward org-outline-regexp-bol nil t)
  5493. (1- (- (match-end 0) (match-beginning 0)))
  5494. 0)))
  5495. (defvar org-font-lock-keywords nil)
  5496. (defsubst org-re-property (property &optional literal allow-null value)
  5497. "Return a regexp matching a PROPERTY line.
  5498. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5499. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5500. non-nil, match properties even without a value.
  5501. Match group 3 is set to the value when it exists. If there is no
  5502. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5503. With optional argument VALUE, match only property lines with
  5504. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5505. unless LITERAL is non-nil."
  5506. (concat
  5507. "^\\(?4:[ \t]*\\)"
  5508. (format "\\(?1::\\(?2:%s\\):\\)"
  5509. (if literal property (regexp-quote property)))
  5510. (cond (value
  5511. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5512. (if literal value (regexp-quote value))))
  5513. (allow-null
  5514. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5515. (t
  5516. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5517. (defconst org-property-re
  5518. (org-re-property "\\S-+" 'literal t)
  5519. "Regular expression matching a property line.
  5520. There are four matching groups:
  5521. 1: :PROPKEY: including the leading and trailing colon,
  5522. 2: PROPKEY without the leading and trailing colon,
  5523. 3: PROPVAL without leading or trailing spaces,
  5524. 4: the indentation of the current line,
  5525. 5: trailing whitespace.")
  5526. (defvar org-font-lock-hook nil
  5527. "Functions to be called for special font lock stuff.")
  5528. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5529. (defvar org-font-lock-set-keywords-hook nil
  5530. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5531. This is called after `org-font-lock-extra-keywords' is defined, but before
  5532. it is installed to be used by font lock. This can be useful if something
  5533. needs to be inserted at a specific position in the font-lock sequence.")
  5534. (defun org-font-lock-hook (limit)
  5535. "Run `org-font-lock-hook' within LIMIT."
  5536. (run-hook-with-args 'org-font-lock-hook limit))
  5537. (defun org-set-font-lock-defaults ()
  5538. "Set font lock defaults for the current buffer."
  5539. (let* ((em org-fontify-emphasized-text)
  5540. (lk org-highlight-links)
  5541. (org-font-lock-extra-keywords
  5542. (list
  5543. ;; Call the hook
  5544. '(org-font-lock-hook)
  5545. ;; Headlines
  5546. `(,(if org-fontify-whole-heading-line
  5547. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5548. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5549. (1 (org-get-level-face 1))
  5550. (2 (org-get-level-face 2))
  5551. (3 (org-get-level-face 3)))
  5552. ;; Table lines
  5553. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5554. (1 'org-table t))
  5555. ;; Table internals
  5556. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5557. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5558. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5559. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5560. ;; Drawers
  5561. '(org-fontify-drawers)
  5562. ;; Properties
  5563. (list org-property-re
  5564. '(1 'org-special-keyword t)
  5565. '(3 'org-property-value t))
  5566. ;; Link related fontification.
  5567. '(org-activate-links)
  5568. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5569. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5570. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5571. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5572. ;; Targets.
  5573. (list org-any-target-regexp '(0 'org-target t))
  5574. ;; Diary sexps.
  5575. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5576. ;; Macro
  5577. '(org-fontify-macros)
  5578. ;; TODO keyword
  5579. (list (format org-heading-keyword-regexp-format
  5580. org-todo-regexp)
  5581. '(2 (org-get-todo-face 2) t))
  5582. ;; DONE
  5583. (if org-fontify-done-headline
  5584. (list (format org-heading-keyword-regexp-format
  5585. (concat
  5586. "\\(?:"
  5587. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5588. "\\)"))
  5589. '(2 'org-headline-done t))
  5590. nil)
  5591. ;; Priorities
  5592. '(org-font-lock-add-priority-faces)
  5593. ;; Tags
  5594. '(org-font-lock-add-tag-faces)
  5595. ;; Tags groups
  5596. (when (and org-group-tags org-tag-groups-alist)
  5597. (list (concat org-outline-regexp-bol ".+\\(:"
  5598. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5599. ":\\).*$")
  5600. '(1 'org-tag-group prepend)))
  5601. ;; Special keywords
  5602. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5603. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5604. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5605. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5606. ;; Emphasis
  5607. (when em '(org-do-emphasis-faces))
  5608. ;; Checkboxes
  5609. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5610. 1 'org-checkbox prepend)
  5611. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5612. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5613. (0 (org-get-checkbox-statistics-face) t)))
  5614. ;; Description list items
  5615. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5616. 1 'org-list-dt prepend)
  5617. ;; ARCHIVEd headings
  5618. (list (concat
  5619. org-outline-regexp-bol
  5620. "\\(.*:" org-archive-tag ":.*\\)")
  5621. '(1 'org-archived prepend))
  5622. ;; Specials
  5623. '(org-do-latex-and-related)
  5624. '(org-fontify-entities)
  5625. '(org-raise-scripts)
  5626. ;; Code
  5627. '(org-activate-code (1 'org-code t))
  5628. ;; COMMENT
  5629. (list (format
  5630. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5631. org-todo-regexp
  5632. org-comment-string)
  5633. '(9 'org-special-keyword t))
  5634. ;; Blocks and meta lines
  5635. '(org-fontify-meta-lines-and-blocks))))
  5636. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5637. (run-hooks 'org-font-lock-set-keywords-hook)
  5638. ;; Now set the full font-lock-keywords
  5639. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5640. (setq-local font-lock-defaults
  5641. '(org-font-lock-keywords t nil nil backward-paragraph))
  5642. (kill-local-variable 'font-lock-keywords)
  5643. nil))
  5644. (defun org-toggle-pretty-entities ()
  5645. "Toggle the composition display of entities as UTF8 characters."
  5646. (interactive)
  5647. (setq-local org-pretty-entities (not org-pretty-entities))
  5648. (org-restart-font-lock)
  5649. (if org-pretty-entities
  5650. (message "Entities are now displayed as UTF8 characters")
  5651. (save-restriction
  5652. (widen)
  5653. (decompose-region (point-min) (point-max))
  5654. (message "Entities are now displayed as plain text"))))
  5655. (defvar-local org-custom-properties-overlays nil
  5656. "List of overlays used for custom properties.")
  5657. (defun org-toggle-custom-properties-visibility ()
  5658. "Display or hide properties in `org-custom-properties'."
  5659. (interactive)
  5660. (if org-custom-properties-overlays
  5661. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5662. (setq org-custom-properties-overlays nil))
  5663. (when org-custom-properties
  5664. (org-with-wide-buffer
  5665. (goto-char (point-min))
  5666. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5667. (while (re-search-forward regexp nil t)
  5668. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5669. (when (and end (< (point) end))
  5670. ;; Hide first custom property in current drawer.
  5671. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5672. (overlay-put o 'invisible t)
  5673. (overlay-put o 'org-custom-property t)
  5674. (push o org-custom-properties-overlays))
  5675. ;; Hide additional custom properties in the same drawer.
  5676. (while (re-search-forward regexp end t)
  5677. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5678. (overlay-put o 'invisible t)
  5679. (overlay-put o 'org-custom-property t)
  5680. (push o org-custom-properties-overlays)))))
  5681. ;; Each entry is limited to a single property drawer.
  5682. (outline-next-heading)))))))
  5683. (defun org-fontify-entities (limit)
  5684. "Find an entity to fontify."
  5685. (let (ee)
  5686. (when org-pretty-entities
  5687. (catch 'match
  5688. ;; "\_ "-family is left out on purpose. Only the first one,
  5689. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5690. ;; confusing when adding a second white space character.
  5691. (while (re-search-forward
  5692. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5693. limit t)
  5694. (when (and (not (org-at-comment-p))
  5695. (setq ee (org-entity-get (match-string 1)))
  5696. (= (length (nth 6 ee)) 1))
  5697. (let* ((end (if (equal (match-string 2) "{}")
  5698. (match-end 2)
  5699. (match-end 1))))
  5700. (add-text-properties
  5701. (match-beginning 0) end
  5702. (list 'font-lock-fontified t))
  5703. (compose-region (match-beginning 0) end
  5704. (nth 6 ee) nil)
  5705. (backward-char 1)
  5706. (throw 'match t))))
  5707. nil))))
  5708. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5709. "Fontify string S like in Org mode."
  5710. (with-temp-buffer
  5711. (insert s)
  5712. (let ((org-odd-levels-only odd-levels))
  5713. (org-mode)
  5714. (org-font-lock-ensure)
  5715. (buffer-string))))
  5716. (defvar org-m nil)
  5717. (defvar org-l nil)
  5718. (defvar org-f nil)
  5719. (defun org-get-level-face (n)
  5720. "Get the right face for match N in font-lock matching of headlines."
  5721. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5722. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5723. (if org-cycle-level-faces
  5724. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5725. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5726. (cond
  5727. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5728. ((eq n 2) org-f)
  5729. (t (unless org-level-color-stars-only org-f))))
  5730. (defun org-face-from-face-or-color (context inherit face-or-color)
  5731. "Create a face list that inherits INHERIT, but sets the foreground color.
  5732. When FACE-OR-COLOR is not a string, just return it."
  5733. (if (stringp face-or-color)
  5734. (list :inherit inherit
  5735. (cdr (assoc context org-faces-easy-properties))
  5736. face-or-color)
  5737. face-or-color))
  5738. (defun org-get-todo-face (kwd)
  5739. "Get the right face for a TODO keyword KWD.
  5740. If KWD is a number, get the corresponding match group."
  5741. (when (numberp kwd) (setq kwd (match-string kwd)))
  5742. (or (org-face-from-face-or-color
  5743. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5744. (and (member kwd org-done-keywords) 'org-done)
  5745. 'org-todo))
  5746. (defun org-get-priority-face (priority)
  5747. "Get the right face for PRIORITY.
  5748. PRIORITY is a character."
  5749. (or (org-face-from-face-or-color
  5750. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5751. 'org-priority))
  5752. (defun org-get-tag-face (tag)
  5753. "Get the right face for TAG.
  5754. If TAG is a number, get the corresponding match group."
  5755. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5756. (or (org-face-from-face-or-color
  5757. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5758. 'org-tag)))
  5759. (defun org-font-lock-add-priority-faces (limit)
  5760. "Add the special priority faces."
  5761. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5762. (add-text-properties
  5763. (match-beginning 1) (match-end 1)
  5764. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5765. 'font-lock-fontified t))))
  5766. (defun org-font-lock-add-tag-faces (limit)
  5767. "Add the special tag faces."
  5768. (when (and org-tag-faces org-tags-special-faces-re)
  5769. (while (re-search-forward org-tags-special-faces-re limit t)
  5770. (add-text-properties (match-beginning 1) (match-end 1)
  5771. (list 'face (org-get-tag-face 1)
  5772. 'font-lock-fontified t))
  5773. (backward-char 1))))
  5774. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5775. "Remove fontification and activation overlays from links."
  5776. (font-lock-default-unfontify-region beg end)
  5777. (let* ((buffer-undo-list t)
  5778. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5779. (inhibit-modification-hooks t)
  5780. deactivate-mark buffer-file-name buffer-file-truename)
  5781. (decompose-region beg end)
  5782. (remove-text-properties beg end
  5783. '(mouse-face t keymap t org-linked-text t
  5784. invisible t intangible t
  5785. org-emphasis t))
  5786. (org-remove-font-lock-display-properties beg end)))
  5787. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5788. ((raise 0.3) (height 0.7))
  5789. ((raise -0.5))
  5790. ((raise 0.5)))
  5791. "Display properties for showing superscripts and subscripts.")
  5792. (defun org-remove-font-lock-display-properties (beg end)
  5793. "Remove specific display properties that have been added by font lock.
  5794. The will remove the raise properties that are used to show superscripts
  5795. and subscripts."
  5796. (let (next prop)
  5797. (while (< beg end)
  5798. (setq next (next-single-property-change beg 'display nil end)
  5799. prop (get-text-property beg 'display))
  5800. (when (member prop org-script-display)
  5801. (put-text-property beg next 'display nil))
  5802. (setq beg next))))
  5803. (defun org-raise-scripts (limit)
  5804. "Add raise properties to sub/superscripts."
  5805. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5806. (re-search-forward
  5807. (if (eq org-use-sub-superscripts t)
  5808. org-match-substring-regexp
  5809. org-match-substring-with-braces-regexp)
  5810. limit t))
  5811. (let* ((pos (point)) table-p comment-p
  5812. (mpos (match-beginning 3))
  5813. (emph-p (get-text-property mpos 'org-emphasis))
  5814. (link-p (get-text-property mpos 'mouse-face))
  5815. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5816. (goto-char (point-at-bol))
  5817. (setq table-p (looking-at-p org-table-dataline-regexp)
  5818. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5819. (goto-char pos)
  5820. ;; Handle a_b^c
  5821. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5822. (unless (or comment-p emph-p link-p keyw-p)
  5823. (put-text-property (match-beginning 3) (match-end 0)
  5824. 'display
  5825. (if (equal (char-after (match-beginning 2)) ?^)
  5826. (nth (if table-p 3 1) org-script-display)
  5827. (nth (if table-p 2 0) org-script-display)))
  5828. (add-text-properties (match-beginning 2) (match-end 2)
  5829. (list 'invisible t))
  5830. (when (and (eq (char-after (match-beginning 3)) ?{)
  5831. (eq (char-before (match-end 3)) ?}))
  5832. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5833. (list 'invisible t))
  5834. (add-text-properties (1- (match-end 3)) (match-end 3)
  5835. (list 'invisible t))))
  5836. t)))
  5837. ;;;; Visibility cycling, including org-goto and indirect buffer
  5838. ;;; Cycling
  5839. (defvar-local org-cycle-global-status nil)
  5840. (put 'org-cycle-global-status 'org-state t)
  5841. (defvar-local org-cycle-subtree-status nil)
  5842. (put 'org-cycle-subtree-status 'org-state t)
  5843. (defvar org-inlinetask-min-level)
  5844. (defun org-unlogged-message (&rest args)
  5845. "Display a message, but avoid logging it in the *Messages* buffer."
  5846. (let ((message-log-max nil))
  5847. (apply 'message args)))
  5848. ;;;###autoload
  5849. (defun org-cycle (&optional arg)
  5850. "TAB-action and visibility cycling for Org mode.
  5851. This is the command invoked in Org mode by the `TAB' key. Its main
  5852. purpose is outline visibility cycling, but it also invokes other actions
  5853. in special contexts.
  5854. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5855. the entire
  5856. buffer through 3 states (global cycling)
  5857. 1. OVERVIEW: Show only top-level headlines.
  5858. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5859. 3. SHOW ALL: Show everything.
  5860. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5861. switch to the startup visibility,
  5862. determined by the variable `org-startup-folded', and by any VISIBILITY
  5863. properties in the buffer.
  5864. With a `\\[universal-argument] \\[universal-argument] \
  5865. \\[universal-argument]' prefix argument, show the entire buffer, including
  5866. any drawers.
  5867. When inside a table, re-align the table and move to the next field.
  5868. When point is at the beginning of a headline, rotate the subtree started
  5869. by this line through 3 different states (local cycling)
  5870. 1. FOLDED: Only the main headline is shown.
  5871. 2. CHILDREN: The main headline and the direct children are shown.
  5872. From this state, you can move to one of the children
  5873. and zoom in further.
  5874. 3. SUBTREE: Show the entire subtree, including body text.
  5875. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5876. When point is at the beginning of an empty headline and the variable
  5877. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5878. of the headline by demoting and promoting it to likely levels. This
  5879. speeds up creation document structure by pressing `TAB' once or several
  5880. times right after creating a new headline.
  5881. When there is a numeric prefix, go up to a heading with level ARG, do
  5882. a `show-subtree' and return to the previous cursor position. If ARG
  5883. is negative, go up that many levels.
  5884. When point is not at the beginning of a headline, execute the global
  5885. binding for `TAB', which is re-indenting the line. See the option
  5886. `org-cycle-emulate-tab' for details.
  5887. As a special case, if point is at the beginning of the buffer and there is
  5888. no headline in line 1, this function will act as if called with prefix arg
  5889. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5890. prefix arg, but only
  5891. if the variable `org-cycle-global-at-bob' is t."
  5892. (interactive "P")
  5893. (org-load-modules-maybe)
  5894. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5895. (and org-cycle-level-after-item/entry-creation
  5896. (or (org-cycle-level)
  5897. (org-cycle-item-indentation))))
  5898. (let* ((limit-level
  5899. (or org-cycle-max-level
  5900. (and (boundp 'org-inlinetask-min-level)
  5901. org-inlinetask-min-level
  5902. (1- org-inlinetask-min-level))))
  5903. (nstars (and limit-level
  5904. (if org-odd-levels-only
  5905. (and limit-level (1- (* limit-level 2)))
  5906. limit-level)))
  5907. (org-outline-regexp
  5908. (if (not (derived-mode-p 'org-mode))
  5909. outline-regexp
  5910. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5911. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5912. (not (looking-at org-outline-regexp))))
  5913. (org-cycle-hook
  5914. (if bob-special
  5915. (delq 'org-optimize-window-after-visibility-change
  5916. (copy-sequence org-cycle-hook))
  5917. org-cycle-hook))
  5918. (pos (point)))
  5919. (cond
  5920. ((equal arg '(16))
  5921. (setq last-command 'dummy)
  5922. (org-set-startup-visibility)
  5923. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5924. ((equal arg '(64))
  5925. (outline-show-all)
  5926. (org-unlogged-message "Entire buffer visible, including drawers"))
  5927. ((equal arg '(4)) (org-cycle-internal-global))
  5928. ;; Try hiding block at point.
  5929. ((org-hide-block-toggle-maybe))
  5930. ;; Try cdlatex TAB completion
  5931. ((org-try-cdlatex-tab))
  5932. ;; Table: enter it or move to the next field.
  5933. ((org-at-table-p 'any)
  5934. (if (org-at-table.el-p)
  5935. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5936. Use `\\[org-edit-special]' to edit table.el tables"))
  5937. (if arg (org-table-edit-field t)
  5938. (org-table-justify-field-maybe)
  5939. (call-interactively 'org-table-next-field))))
  5940. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5941. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5942. (bob-special (org-cycle-internal-global))
  5943. ;; Drawers: delegate to `org-flag-drawer'.
  5944. ((save-excursion
  5945. (beginning-of-line 1)
  5946. (looking-at org-drawer-regexp))
  5947. (org-flag-drawer ; toggle block visibility
  5948. (not (get-char-property (match-end 0) 'invisible))))
  5949. ;; Show-subtree, ARG levels up from here.
  5950. ((integerp arg)
  5951. (save-excursion
  5952. (org-back-to-heading)
  5953. (outline-up-heading (if (< arg 0) (- arg)
  5954. (- (funcall outline-level) arg)))
  5955. (org-show-subtree)))
  5956. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5957. ((and (featurep 'org-inlinetask)
  5958. (org-inlinetask-at-task-p)
  5959. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5960. (org-inlinetask-toggle-visibility))
  5961. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5962. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5963. (save-excursion (move-beginning-of-line 1)
  5964. (looking-at org-outline-regexp)))
  5965. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5966. (org-cycle-internal-local))
  5967. ;; From there: TAB emulation and template completion.
  5968. (buffer-read-only (org-back-to-heading))
  5969. ((run-hook-with-args-until-success
  5970. 'org-tab-after-check-for-cycling-hook))
  5971. ((org-try-structure-completion))
  5972. ((run-hook-with-args-until-success
  5973. 'org-tab-before-tab-emulation-hook))
  5974. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5975. (or (not (bolp))
  5976. (not (looking-at org-outline-regexp))))
  5977. (call-interactively (global-key-binding "\t")))
  5978. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5979. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5980. (or (and (eq org-cycle-emulate-tab 'white)
  5981. (= (match-end 0) (point-at-eol)))
  5982. (and (eq org-cycle-emulate-tab 'whitestart)
  5983. (>= (match-end 0) pos))))
  5984. t
  5985. (eq org-cycle-emulate-tab t))
  5986. (call-interactively (global-key-binding "\t")))
  5987. (t (save-excursion
  5988. (org-back-to-heading)
  5989. (org-cycle)))))))
  5990. (defun org-cycle-internal-global ()
  5991. "Do the global cycling action."
  5992. ;; Hack to avoid display of messages for .org attachments in Gnus
  5993. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5994. (cond
  5995. ((and (eq last-command this-command)
  5996. (eq org-cycle-global-status 'overview))
  5997. ;; We just created the overview - now do table of contents
  5998. ;; This can be slow in very large buffers, so indicate action
  5999. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6000. (unless ga (org-unlogged-message "CONTENTS..."))
  6001. (org-content)
  6002. (unless ga (org-unlogged-message "CONTENTS...done"))
  6003. (setq org-cycle-global-status 'contents)
  6004. (run-hook-with-args 'org-cycle-hook 'contents))
  6005. ((and (eq last-command this-command)
  6006. (eq org-cycle-global-status 'contents))
  6007. ;; We just showed the table of contents - now show everything
  6008. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6009. (outline-show-all)
  6010. (unless ga (org-unlogged-message "SHOW ALL"))
  6011. (setq org-cycle-global-status 'all)
  6012. (run-hook-with-args 'org-cycle-hook 'all))
  6013. (t
  6014. ;; Default action: go to overview
  6015. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6016. (org-overview)
  6017. (unless ga (org-unlogged-message "OVERVIEW"))
  6018. (setq org-cycle-global-status 'overview)
  6019. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6020. (defvar org-called-with-limited-levels nil
  6021. "Non-nil when `org-with-limited-levels' is currently active.")
  6022. (defun org-invisible-p (&optional pos)
  6023. "Non-nil if the character after POS is invisible.
  6024. If POS is nil, use `point' instead."
  6025. (get-char-property (or pos (point)) 'invisible))
  6026. (defun org-cycle-internal-local ()
  6027. "Do the local cycling action."
  6028. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6029. ;; First, determine end of headline (EOH), end of subtree or item
  6030. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6031. (save-excursion
  6032. (if (org-at-item-p)
  6033. (progn
  6034. (beginning-of-line)
  6035. (setq struct (org-list-struct))
  6036. (setq eoh (point-at-eol))
  6037. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6038. (setq has-children (org-list-has-child-p (point) struct)))
  6039. (org-back-to-heading)
  6040. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6041. (setq eos (save-excursion (org-end-of-subtree t t)
  6042. (when (bolp) (backward-char)) (point)))
  6043. (setq has-children
  6044. (or (save-excursion
  6045. (let ((level (funcall outline-level)))
  6046. (outline-next-heading)
  6047. (and (org-at-heading-p t)
  6048. (> (funcall outline-level) level))))
  6049. (save-excursion
  6050. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6051. ;; Determine end invisible part of buffer (EOL)
  6052. (beginning-of-line 2)
  6053. (while (and (not (eobp)) ;This is like `next-line'.
  6054. (get-char-property (1- (point)) 'invisible))
  6055. (goto-char (next-single-char-property-change (point) 'invisible))
  6056. (and (eolp) (beginning-of-line 2)))
  6057. (setq eol (point)))
  6058. ;; Find out what to do next and set `this-command'
  6059. (cond
  6060. ((= eos eoh)
  6061. ;; Nothing is hidden behind this heading
  6062. (unless (org-before-first-heading-p)
  6063. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6064. (org-unlogged-message "EMPTY ENTRY")
  6065. (setq org-cycle-subtree-status nil)
  6066. (save-excursion
  6067. (goto-char eos)
  6068. (outline-next-heading)
  6069. (when (org-invisible-p) (org-flag-heading nil))))
  6070. ((and (or (>= eol eos)
  6071. (not (string-match "\\S-" (buffer-substring eol eos))))
  6072. (or has-children
  6073. (not (setq children-skipped
  6074. org-cycle-skip-children-state-if-no-children))))
  6075. ;; Entire subtree is hidden in one line: children view
  6076. (unless (org-before-first-heading-p)
  6077. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6078. (if (org-at-item-p)
  6079. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6080. (org-show-entry)
  6081. (org-with-limited-levels (org-show-children))
  6082. ;; FIXME: This slows down the func way too much.
  6083. ;; How keep drawers hidden in subtree anyway?
  6084. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6085. ;; (org-cycle-hide-drawers 'subtree))
  6086. ;; Fold every list in subtree to top-level items.
  6087. (when (eq org-cycle-include-plain-lists 'integrate)
  6088. (save-excursion
  6089. (org-back-to-heading)
  6090. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6091. (beginning-of-line 1)
  6092. (let* ((struct (org-list-struct))
  6093. (prevs (org-list-prevs-alist struct))
  6094. (end (org-list-get-bottom-point struct)))
  6095. (dolist (e (org-list-get-all-items (point) struct prevs))
  6096. (org-list-set-item-visibility e struct 'folded))
  6097. (goto-char (if (< end eos) end eos)))))))
  6098. (org-unlogged-message "CHILDREN")
  6099. (save-excursion
  6100. (goto-char eos)
  6101. (outline-next-heading)
  6102. (when (org-invisible-p) (org-flag-heading nil)))
  6103. (setq org-cycle-subtree-status 'children)
  6104. (unless (org-before-first-heading-p)
  6105. (run-hook-with-args 'org-cycle-hook 'children)))
  6106. ((or children-skipped
  6107. (and (eq last-command this-command)
  6108. (eq org-cycle-subtree-status 'children)))
  6109. ;; We just showed the children, or no children are there,
  6110. ;; now show everything.
  6111. (unless (org-before-first-heading-p)
  6112. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6113. (outline-flag-region eoh eos nil)
  6114. (org-unlogged-message
  6115. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6116. (setq org-cycle-subtree-status 'subtree)
  6117. (unless (org-before-first-heading-p)
  6118. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6119. (t
  6120. ;; Default action: hide the subtree.
  6121. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6122. (outline-flag-region eoh eos t)
  6123. (org-unlogged-message "FOLDED")
  6124. (setq org-cycle-subtree-status 'folded)
  6125. (unless (org-before-first-heading-p)
  6126. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6127. ;;;###autoload
  6128. (defun org-global-cycle (&optional arg)
  6129. "Cycle the global visibility. For details see `org-cycle'.
  6130. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6131. With a numeric prefix, show all headlines up to that level."
  6132. (interactive "P")
  6133. (let ((org-cycle-include-plain-lists
  6134. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6135. (cond
  6136. ((integerp arg)
  6137. (outline-show-all)
  6138. (outline-hide-sublevels arg)
  6139. (setq org-cycle-global-status 'contents))
  6140. ((equal arg '(4))
  6141. (org-set-startup-visibility)
  6142. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6143. (t
  6144. (org-cycle '(4))))))
  6145. (defun org-set-startup-visibility ()
  6146. "Set the visibility required by startup options and properties."
  6147. (cond
  6148. ((eq org-startup-folded t)
  6149. (org-overview))
  6150. ((eq org-startup-folded 'content)
  6151. (org-content))
  6152. ((or (eq org-startup-folded 'showeverything)
  6153. (eq org-startup-folded nil))
  6154. (outline-show-all)))
  6155. (unless (eq org-startup-folded 'showeverything)
  6156. (when org-hide-block-startup (org-hide-block-all))
  6157. (org-set-visibility-according-to-property 'no-cleanup)
  6158. (org-cycle-hide-archived-subtrees 'all)
  6159. (org-cycle-hide-drawers 'all)
  6160. (org-cycle-show-empty-lines t)))
  6161. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6162. "Switch subtree visibilities according to :VISIBILITY: property."
  6163. (interactive)
  6164. (org-with-wide-buffer
  6165. (goto-char (point-min))
  6166. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6167. (if (not (org-at-property-p)) (outline-next-heading)
  6168. (let ((state (match-string 3)))
  6169. (save-excursion
  6170. (org-back-to-heading t)
  6171. (outline-hide-subtree)
  6172. (org-reveal)
  6173. (cond
  6174. ((equal state "folded")
  6175. (outline-hide-subtree))
  6176. ((equal state "children")
  6177. (org-show-hidden-entry)
  6178. (org-show-children))
  6179. ((equal state "content")
  6180. (save-excursion
  6181. (save-restriction
  6182. (org-narrow-to-subtree)
  6183. (org-content))))
  6184. ((member state '("all" "showall"))
  6185. (outline-show-subtree)))))))
  6186. (unless no-cleanup
  6187. (org-cycle-hide-archived-subtrees 'all)
  6188. (org-cycle-hide-drawers 'all)
  6189. (org-cycle-show-empty-lines 'all))))
  6190. ;; This function uses outline-regexp instead of the more fundamental
  6191. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6192. ;; buffers, where outline-regexp is needed.
  6193. (defun org-overview ()
  6194. "Switch to overview mode, showing only top-level headlines.
  6195. This shows all headlines with a level equal or greater than the level
  6196. of the first headline in the buffer. This is important, because if the
  6197. first headline is not level one, then (hide-sublevels 1) gives confusing
  6198. results."
  6199. (interactive)
  6200. (save-excursion
  6201. (let ((level
  6202. (save-excursion
  6203. (goto-char (point-min))
  6204. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6205. (goto-char (match-beginning 0))
  6206. (funcall outline-level)))))
  6207. (and level (outline-hide-sublevels level)))))
  6208. (defun org-content (&optional arg)
  6209. "Show all headlines in the buffer, like a table of contents.
  6210. With numerical argument N, show content up to level N."
  6211. (interactive "P")
  6212. (org-overview)
  6213. (save-excursion
  6214. ;; Visit all headings and show their offspring
  6215. (and (integerp arg) (org-overview))
  6216. (goto-char (point-max))
  6217. (catch 'exit
  6218. (while (and (progn (condition-case nil
  6219. (outline-previous-visible-heading 1)
  6220. (error (goto-char (point-min))))
  6221. t)
  6222. (looking-at org-outline-regexp))
  6223. (if (integerp arg)
  6224. (org-show-children (1- arg))
  6225. (outline-show-branches))
  6226. (when (bobp) (throw 'exit nil))))))
  6227. (defun org-optimize-window-after-visibility-change (state)
  6228. "Adjust the window after a change in outline visibility.
  6229. This function is the default value of the hook `org-cycle-hook'."
  6230. (when (get-buffer-window (current-buffer))
  6231. (cond
  6232. ((eq state 'content) nil)
  6233. ((eq state 'all) nil)
  6234. ((eq state 'folded) nil)
  6235. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6236. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6237. (defun org-remove-empty-overlays-at (pos)
  6238. "Remove outline overlays that do not contain non-white stuff."
  6239. (dolist (o (overlays-at pos))
  6240. (and (eq 'outline (overlay-get o 'invisible))
  6241. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6242. (overlay-end o))))
  6243. (delete-overlay o))))
  6244. (defun org-clean-visibility-after-subtree-move ()
  6245. "Fix visibility issues after moving a subtree."
  6246. ;; First, find a reasonable region to look at:
  6247. ;; Start two siblings above, end three below
  6248. (let* ((beg (save-excursion
  6249. (and (org-get-last-sibling)
  6250. (org-get-last-sibling))
  6251. (point)))
  6252. (end (save-excursion
  6253. (and (org-get-next-sibling)
  6254. (org-get-next-sibling)
  6255. (org-get-next-sibling))
  6256. (if (org-at-heading-p)
  6257. (point-at-eol)
  6258. (point))))
  6259. (level (looking-at "\\*+"))
  6260. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6261. (save-excursion
  6262. (save-restriction
  6263. (narrow-to-region beg end)
  6264. (when re
  6265. ;; Properly fold already folded siblings
  6266. (goto-char (point-min))
  6267. (while (re-search-forward re nil t)
  6268. (when (and (not (org-invisible-p))
  6269. (save-excursion
  6270. (goto-char (point-at-eol)) (org-invisible-p)))
  6271. (outline-hide-entry))))
  6272. (org-cycle-show-empty-lines 'overview)
  6273. (org-cycle-hide-drawers 'overview)))))
  6274. (defun org-cycle-show-empty-lines (state)
  6275. "Show empty lines above all visible headlines.
  6276. The region to be covered depends on STATE when called through
  6277. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6278. entire buffer covered. Note that an empty line is only shown if there
  6279. are at least `org-cycle-separator-lines' empty lines before the headline."
  6280. (when (/= org-cycle-separator-lines 0)
  6281. (save-excursion
  6282. (let* ((n (abs org-cycle-separator-lines))
  6283. (re (cond
  6284. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6285. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6286. (t (let ((ns (number-to-string (- n 2))))
  6287. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6288. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6289. beg end)
  6290. (cond
  6291. ((memq state '(overview contents t))
  6292. (setq beg (point-min) end (point-max)))
  6293. ((memq state '(children folded))
  6294. (setq beg (point)
  6295. end (progn (org-end-of-subtree t t)
  6296. (line-beginning-position 2)))))
  6297. (when beg
  6298. (goto-char beg)
  6299. (while (re-search-forward re end t)
  6300. (unless (get-char-property (match-end 1) 'invisible)
  6301. (let ((e (match-end 1))
  6302. (b (if (>= org-cycle-separator-lines 0)
  6303. (match-beginning 1)
  6304. (save-excursion
  6305. (goto-char (match-beginning 0))
  6306. (skip-chars-backward " \t\n")
  6307. (line-end-position)))))
  6308. (outline-flag-region b e nil))))))))
  6309. ;; Never hide empty lines at the end of the file.
  6310. (save-excursion
  6311. (goto-char (point-max))
  6312. (outline-previous-heading)
  6313. (outline-end-of-heading)
  6314. (when (and (looking-at "[ \t\n]+")
  6315. (= (match-end 0) (point-max)))
  6316. (outline-flag-region (point) (match-end 0) nil))))
  6317. (defun org-show-empty-lines-in-parent ()
  6318. "Move to the parent and re-show empty lines before visible headlines."
  6319. (save-excursion
  6320. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6321. (org-cycle-show-empty-lines context))))
  6322. (defun org-files-list ()
  6323. "Return `org-agenda-files' list, plus all open Org files.
  6324. This is useful for operations that need to scan all of a user's
  6325. open and agenda-wise Org files."
  6326. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6327. (dolist (buf (buffer-list))
  6328. (with-current-buffer buf
  6329. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6330. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6331. files))
  6332. (defsubst org-entry-beginning-position ()
  6333. "Return the beginning position of the current entry."
  6334. (save-excursion (org-back-to-heading t) (point)))
  6335. (defsubst org-entry-end-position ()
  6336. "Return the end position of the current entry."
  6337. (save-excursion (outline-next-heading) (point)))
  6338. (defun org-cycle-hide-drawers (state &optional exceptions)
  6339. "Re-hide all drawers after a visibility state change.
  6340. STATE should be one of the symbols listed in the docstring of
  6341. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6342. a list of strings specifying which drawers should not be hidden."
  6343. (when (and (derived-mode-p 'org-mode)
  6344. (not (memq state '(overview folded contents))))
  6345. (save-excursion
  6346. (let* ((globalp (eq state 'all))
  6347. (beg (if globalp (point-min) (point)))
  6348. (end (if globalp (point-max)
  6349. (if (eq state 'children)
  6350. (save-excursion (outline-next-heading) (point))
  6351. (org-end-of-subtree t)))))
  6352. (goto-char beg)
  6353. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6354. (unless (member-ignore-case (match-string 1) exceptions)
  6355. (let ((drawer (org-element-at-point)))
  6356. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6357. (org-flag-drawer t drawer)
  6358. ;; Make sure to skip drawer entirely or we might flag
  6359. ;; it another time when matching its ending line with
  6360. ;; `org-drawer-regexp'.
  6361. (goto-char (org-element-property :end drawer))))))))))
  6362. (defun org-flag-drawer (flag &optional element)
  6363. "When FLAG is non-nil, hide the drawer we are at.
  6364. Otherwise make it visible. When optional argument ELEMENT is
  6365. a parsed drawer, as returned by `org-element-at-point', hide or
  6366. show that drawer instead."
  6367. (let ((drawer (or element
  6368. (and (save-excursion
  6369. (beginning-of-line)
  6370. (looking-at-p org-drawer-regexp))
  6371. (org-element-at-point)))))
  6372. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6373. (let ((post (org-element-property :post-affiliated drawer)))
  6374. (save-excursion
  6375. (outline-flag-region
  6376. (progn (goto-char post) (line-end-position))
  6377. (progn (goto-char (org-element-property :end drawer))
  6378. (skip-chars-backward " \r\t\n")
  6379. (line-end-position))
  6380. flag))
  6381. ;; When the drawer is hidden away, make sure point lies in
  6382. ;; a visible part of the buffer.
  6383. (when (and flag (> (line-beginning-position) post))
  6384. (goto-char post))))))
  6385. (defun org-subtree-end-visible-p ()
  6386. "Is the end of the current subtree visible?"
  6387. (pos-visible-in-window-p
  6388. (save-excursion (org-end-of-subtree t) (point))))
  6389. (defun org-first-headline-recenter ()
  6390. "Move cursor to the first headline and recenter the headline."
  6391. (let ((window (get-buffer-window)))
  6392. (when window
  6393. (goto-char (point-min))
  6394. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6395. (set-window-start window (line-beginning-position))))))
  6396. ;;; Saving and restoring visibility
  6397. (defun org-outline-overlay-data (&optional use-markers)
  6398. "Return a list of the locations of all outline overlays.
  6399. These are overlays with the `invisible' property value `outline'.
  6400. The return value is a list of cons cells, with start and stop
  6401. positions for each overlay.
  6402. If USE-MARKERS is set, return the positions as markers."
  6403. (let (beg end)
  6404. (org-with-wide-buffer
  6405. (delq nil
  6406. (mapcar (lambda (o)
  6407. (when (eq (overlay-get o 'invisible) 'outline)
  6408. (setq beg (overlay-start o)
  6409. end (overlay-end o))
  6410. (and beg end (> end beg)
  6411. (if use-markers
  6412. (cons (copy-marker beg)
  6413. (copy-marker end t))
  6414. (cons beg end)))))
  6415. (overlays-in (point-min) (point-max)))))))
  6416. (defun org-set-outline-overlay-data (data)
  6417. "Create visibility overlays for all positions in DATA.
  6418. DATA should have been made by `org-outline-overlay-data'."
  6419. (org-with-wide-buffer
  6420. (outline-show-all)
  6421. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6422. ;;; Folding of blocks
  6423. (defvar-local org-hide-block-overlays nil
  6424. "Overlays hiding blocks.")
  6425. (defun org-block-map (function &optional start end)
  6426. "Call FUNCTION at the head of all source blocks in the current buffer.
  6427. Optional arguments START and END can be used to limit the range."
  6428. (let ((start (or start (point-min)))
  6429. (end (or end (point-max))))
  6430. (save-excursion
  6431. (goto-char start)
  6432. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6433. (save-excursion
  6434. (save-match-data
  6435. (goto-char (match-beginning 0))
  6436. (funcall function)))))))
  6437. (defun org-hide-block-toggle-all ()
  6438. "Toggle the visibility of all blocks in the current buffer."
  6439. (org-block-map 'org-hide-block-toggle))
  6440. (defun org-hide-block-all ()
  6441. "Fold all blocks in the current buffer."
  6442. (interactive)
  6443. (org-show-block-all)
  6444. (org-block-map 'org-hide-block-toggle-maybe))
  6445. (defun org-show-block-all ()
  6446. "Unfold all blocks in the current buffer."
  6447. (interactive)
  6448. (mapc #'delete-overlay org-hide-block-overlays)
  6449. (setq org-hide-block-overlays nil))
  6450. (defun org-hide-block-toggle-maybe ()
  6451. "Toggle visibility of block at point.
  6452. Unlike to `org-hide-block-toggle', this function does not throw
  6453. an error. Return a non-nil value when toggling is successful."
  6454. (interactive)
  6455. (ignore-errors (org-hide-block-toggle)))
  6456. (defun org-hide-block-toggle (&optional force)
  6457. "Toggle the visibility of the current block.
  6458. When optional argument FORCE is `off', make block visible. If it
  6459. is non-nil, hide it unconditionally. Throw an error when not at
  6460. a block. Return a non-nil value when toggling is successful."
  6461. (interactive)
  6462. (let ((element (org-element-at-point)))
  6463. (unless (memq (org-element-type element)
  6464. '(center-block comment-block dynamic-block example-block
  6465. export-block quote-block special-block
  6466. src-block verse-block))
  6467. (user-error "Not at a block"))
  6468. (let* ((start (save-excursion
  6469. (goto-char (org-element-property :post-affiliated element))
  6470. (line-end-position)))
  6471. (end (save-excursion
  6472. (goto-char (org-element-property :end element))
  6473. (skip-chars-backward " \r\t\n")
  6474. (line-end-position)))
  6475. (overlays (overlays-at start)))
  6476. (cond
  6477. ;; Do nothing when not before or at the block opening line or
  6478. ;; at the block closing line.
  6479. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6480. ((and (not (eq force 'off))
  6481. (not (memq t (mapcar
  6482. (lambda (o)
  6483. (eq (overlay-get o 'invisible) 'org-hide-block))
  6484. overlays))))
  6485. (let ((ov (make-overlay start end)))
  6486. (overlay-put ov 'invisible 'org-hide-block)
  6487. ;; Make the block accessible to `isearch'.
  6488. (overlay-put
  6489. ov 'isearch-open-invisible
  6490. (lambda (ov)
  6491. (when (memq ov org-hide-block-overlays)
  6492. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6493. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6494. (delete-overlay ov))))
  6495. (push ov org-hide-block-overlays)
  6496. ;; When the block is hidden away, make sure point is left in
  6497. ;; a visible part of the buffer.
  6498. (when (> (line-beginning-position) start)
  6499. (goto-char start)
  6500. (beginning-of-line))
  6501. ;; Signal successful toggling.
  6502. t))
  6503. ((or (not force) (eq force 'off))
  6504. (dolist (ov overlays t)
  6505. (when (memq ov org-hide-block-overlays)
  6506. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6507. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6508. (delete-overlay ov))))))))
  6509. ;; Remove overlays when changing major mode
  6510. (add-hook 'org-mode-hook
  6511. (lambda () (add-hook 'change-major-mode-hook
  6512. 'org-show-block-all 'append 'local)))
  6513. ;;; Org-goto
  6514. (defvar org-goto-window-configuration nil)
  6515. (defvar org-goto-marker nil)
  6516. (defvar org-goto-map)
  6517. (defun org-goto-map ()
  6518. "Set the keymap `org-goto'."
  6519. (setq org-goto-map
  6520. (let ((map (make-sparse-keymap)))
  6521. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6522. mouse-drag-region universal-argument org-occur)))
  6523. (dolist (cmd cmds)
  6524. (substitute-key-definition cmd cmd map global-map)))
  6525. (suppress-keymap map)
  6526. (org-defkey map "\C-m" 'org-goto-ret)
  6527. (org-defkey map [(return)] 'org-goto-ret)
  6528. (org-defkey map [(left)] 'org-goto-left)
  6529. (org-defkey map [(right)] 'org-goto-right)
  6530. (org-defkey map [(control ?g)] 'org-goto-quit)
  6531. (org-defkey map "\C-i" 'org-cycle)
  6532. (org-defkey map [(tab)] 'org-cycle)
  6533. (org-defkey map [(down)] 'outline-next-visible-heading)
  6534. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6535. (if org-goto-auto-isearch
  6536. (if (fboundp 'define-key-after)
  6537. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6538. nil)
  6539. (org-defkey map "q" 'org-goto-quit)
  6540. (org-defkey map "n" 'outline-next-visible-heading)
  6541. (org-defkey map "p" 'outline-previous-visible-heading)
  6542. (org-defkey map "f" 'outline-forward-same-level)
  6543. (org-defkey map "b" 'outline-backward-same-level)
  6544. (org-defkey map "u" 'outline-up-heading))
  6545. (org-defkey map "/" 'org-occur)
  6546. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6547. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6548. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6549. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6550. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6551. map)))
  6552. (defconst org-goto-help
  6553. "Browse buffer copy, to find location or copy text.%s
  6554. RET=jump to location C-g=quit and return to previous location
  6555. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6556. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6557. (defun org-goto (&optional alternative-interface)
  6558. "Look up a different location in the current file, keeping current visibility.
  6559. When you want look-up or go to a different location in a
  6560. document, the fastest way is often to fold the entire buffer and
  6561. then dive into the tree. This method has the disadvantage, that
  6562. the previous location will be folded, which may not be what you
  6563. want.
  6564. This command works around this by showing a copy of the current
  6565. buffer in an indirect buffer, in overview mode. You can dive
  6566. into the tree in that copy, use org-occur and incremental search
  6567. to find a location. When pressing RET or `Q', the command
  6568. returns to the original buffer in which the visibility is still
  6569. unchanged. After RET it will also jump to the location selected
  6570. in the indirect buffer and expose the headline hierarchy above.
  6571. With a prefix argument, use the alternative interface: e.g., if
  6572. `org-goto-interface' is `outline' use `outline-path-completion'."
  6573. (interactive "P")
  6574. (org-goto-map)
  6575. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6576. (org-refile-use-outline-path t)
  6577. (org-refile-target-verify-function nil)
  6578. (interface
  6579. (if (not alternative-interface)
  6580. org-goto-interface
  6581. (if (eq org-goto-interface 'outline)
  6582. 'outline-path-completion
  6583. 'outline)))
  6584. (org-goto-start-pos (point))
  6585. (selected-point
  6586. (if (eq interface 'outline)
  6587. (car (org-get-location (current-buffer) org-goto-help))
  6588. (let ((pa (org-refile-get-location "Goto")))
  6589. (org-refile-check-position pa)
  6590. (nth 3 pa)))))
  6591. (if selected-point
  6592. (progn
  6593. (org-mark-ring-push org-goto-start-pos)
  6594. (goto-char selected-point)
  6595. (when (or (org-invisible-p) (org-invisible-p2))
  6596. (org-show-context 'org-goto)))
  6597. (message "Quit"))))
  6598. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6599. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6600. (defvar org-goto-local-auto-isearch-map) ; defined below
  6601. (defun org-get-location (_buf help)
  6602. "Let the user select a location in current buffer.
  6603. This function uses a recursive edit. It returns the selected position
  6604. or nil."
  6605. (org-no-popups
  6606. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6607. (isearch-hide-immediately nil)
  6608. (isearch-search-fun-function
  6609. (lambda () 'org-goto-local-search-headings))
  6610. (org-goto-selected-point org-goto-exit-command))
  6611. (save-excursion
  6612. (save-window-excursion
  6613. (delete-other-windows)
  6614. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6615. (pop-to-buffer-same-window
  6616. (condition-case nil
  6617. (make-indirect-buffer (current-buffer) "*org-goto*")
  6618. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6619. (with-output-to-temp-buffer "*Org Help*"
  6620. (princ (format help (if org-goto-auto-isearch
  6621. " Just type for auto-isearch."
  6622. " n/p/f/b/u to navigate, q to quit."))))
  6623. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6624. (setq buffer-read-only nil)
  6625. (let ((org-startup-truncated t)
  6626. (org-startup-folded nil)
  6627. (org-startup-align-all-tables nil))
  6628. (org-mode)
  6629. (org-overview))
  6630. (setq buffer-read-only t)
  6631. (if (and (boundp 'org-goto-start-pos)
  6632. (integer-or-marker-p org-goto-start-pos))
  6633. (progn (goto-char org-goto-start-pos)
  6634. (when (org-invisible-p)
  6635. (org-show-set-visibility 'lineage)))
  6636. (goto-char (point-min)))
  6637. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6638. (message "Select location and press RET")
  6639. (use-local-map org-goto-map)
  6640. (recursive-edit)))
  6641. (kill-buffer "*org-goto*")
  6642. (cons org-goto-selected-point org-goto-exit-command))))
  6643. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6644. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6645. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6646. (if (fboundp 'isearch-other-control-char)
  6647. (progn
  6648. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6649. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6650. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6651. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6652. (define-key org-goto-local-auto-isearch-map [return] nil))
  6653. (defun org-goto-local-search-headings (string bound noerror)
  6654. "Search and make sure that any matches are in headlines."
  6655. (catch 'return
  6656. (while (if isearch-forward
  6657. (search-forward string bound noerror)
  6658. (search-backward string bound noerror))
  6659. (when (save-match-data
  6660. (and (save-excursion
  6661. (beginning-of-line)
  6662. (looking-at org-complex-heading-regexp))
  6663. (or (not (match-beginning 5))
  6664. (< (point) (match-beginning 5)))))
  6665. (throw 'return (point))))))
  6666. (defun org-goto-local-auto-isearch ()
  6667. "Start isearch."
  6668. (interactive)
  6669. (goto-char (point-min))
  6670. (let ((keys (this-command-keys)))
  6671. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6672. (isearch-mode t)
  6673. (isearch-process-search-char (string-to-char keys)))))
  6674. (defun org-goto-ret (&optional _arg)
  6675. "Finish `org-goto' by going to the new location."
  6676. (interactive "P")
  6677. (setq org-goto-selected-point (point))
  6678. (setq org-goto-exit-command 'return)
  6679. (throw 'exit nil))
  6680. (defun org-goto-left ()
  6681. "Finish `org-goto' by going to the new location."
  6682. (interactive)
  6683. (if (org-at-heading-p)
  6684. (progn
  6685. (beginning-of-line 1)
  6686. (setq org-goto-selected-point (point)
  6687. org-goto-exit-command 'left)
  6688. (throw 'exit nil))
  6689. (user-error "Not on a heading")))
  6690. (defun org-goto-right ()
  6691. "Finish `org-goto' by going to the new location."
  6692. (interactive)
  6693. (if (org-at-heading-p)
  6694. (progn
  6695. (setq org-goto-selected-point (point)
  6696. org-goto-exit-command 'right)
  6697. (throw 'exit nil))
  6698. (user-error "Not on a heading")))
  6699. (defun org-goto-quit ()
  6700. "Finish `org-goto' without cursor motion."
  6701. (interactive)
  6702. (setq org-goto-selected-point nil)
  6703. (setq org-goto-exit-command 'quit)
  6704. (throw 'exit nil))
  6705. ;;; Indirect buffer display of subtrees
  6706. (defvar org-indirect-dedicated-frame nil
  6707. "This is the frame being used for indirect tree display.")
  6708. (defvar org-last-indirect-buffer nil)
  6709. (defun org-tree-to-indirect-buffer (&optional arg)
  6710. "Create indirect buffer and narrow it to current subtree.
  6711. With a numerical prefix ARG, go up to this level and then take that tree.
  6712. If ARG is negative, go up that many levels.
  6713. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6714. indirect buffer previously made with this command, to avoid proliferation of
  6715. indirect buffers. However, when you call the command with a \
  6716. `\\[universal-argument]' prefix, or
  6717. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6718. so that you can work with several indirect buffers at the same time. If
  6719. `org-indirect-buffer-display' is `dedicated-frame', the \
  6720. `\\[universal-argument]' prefix also
  6721. requests that a new frame be made for the new buffer, so that the dedicated
  6722. frame is not changed."
  6723. (interactive "P")
  6724. (let ((cbuf (current-buffer))
  6725. (cwin (selected-window))
  6726. (pos (point))
  6727. beg end level heading ibuf)
  6728. (save-excursion
  6729. (org-back-to-heading t)
  6730. (when (numberp arg)
  6731. (setq level (org-outline-level))
  6732. (when (< arg 0) (setq arg (+ level arg)))
  6733. (while (> (setq level (org-outline-level)) arg)
  6734. (org-up-heading-safe)))
  6735. (setq beg (point)
  6736. heading (org-get-heading 'no-tags))
  6737. (org-end-of-subtree t t)
  6738. (when (org-at-heading-p) (backward-char 1))
  6739. (setq end (point)))
  6740. (when (and (buffer-live-p org-last-indirect-buffer)
  6741. (not (eq org-indirect-buffer-display 'new-frame))
  6742. (not arg))
  6743. (kill-buffer org-last-indirect-buffer))
  6744. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6745. org-last-indirect-buffer ibuf)
  6746. (cond
  6747. ((or (eq org-indirect-buffer-display 'new-frame)
  6748. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6749. (select-frame (make-frame))
  6750. (delete-other-windows)
  6751. (pop-to-buffer-same-window ibuf)
  6752. (org-set-frame-title heading))
  6753. ((eq org-indirect-buffer-display 'dedicated-frame)
  6754. (raise-frame
  6755. (select-frame (or (and org-indirect-dedicated-frame
  6756. (frame-live-p org-indirect-dedicated-frame)
  6757. org-indirect-dedicated-frame)
  6758. (setq org-indirect-dedicated-frame (make-frame)))))
  6759. (delete-other-windows)
  6760. (pop-to-buffer-same-window ibuf)
  6761. (org-set-frame-title (concat "Indirect: " heading)))
  6762. ((eq org-indirect-buffer-display 'current-window)
  6763. (pop-to-buffer-same-window ibuf))
  6764. ((eq org-indirect-buffer-display 'other-window)
  6765. (pop-to-buffer ibuf))
  6766. (t (error "Invalid value")))
  6767. (narrow-to-region beg end)
  6768. (outline-show-all)
  6769. (goto-char pos)
  6770. (run-hook-with-args 'org-cycle-hook 'all)
  6771. (and (window-live-p cwin) (select-window cwin))))
  6772. (defun org-get-indirect-buffer (&optional buffer heading)
  6773. (setq buffer (or buffer (current-buffer)))
  6774. (let ((n 1) (base (buffer-name buffer)) bname)
  6775. (while (buffer-live-p
  6776. (get-buffer
  6777. (setq bname
  6778. (concat base "-"
  6779. (if heading (concat heading "-" (number-to-string n))
  6780. (number-to-string n))))))
  6781. (setq n (1+ n)))
  6782. (condition-case nil
  6783. (make-indirect-buffer buffer bname 'clone)
  6784. (error (make-indirect-buffer buffer bname)))))
  6785. (defun org-set-frame-title (title)
  6786. "Set the title of the current frame to the string TITLE."
  6787. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6788. ;;;; Structure editing
  6789. ;;; Inserting headlines
  6790. (defun org--line-empty-p (n)
  6791. "Is the Nth next line empty?
  6792. Counts the current line as N = 1 and the previous line as N = 0;
  6793. see `beginning-of-line'."
  6794. (save-excursion
  6795. (and (not (bobp))
  6796. (or (beginning-of-line n) t)
  6797. (save-match-data
  6798. (looking-at "[ \t]*$")))))
  6799. (defun org-previous-line-empty-p ()
  6800. "Is the previous line a blank line?
  6801. When NEXT is non-nil, check the next line instead."
  6802. (org--line-empty-p 0))
  6803. (defun org-next-line-empty-p ()
  6804. "Is the previous line a blank line?
  6805. When NEXT is non-nil, check the next line instead."
  6806. (org--line-empty-p 2))
  6807. (defun org--blank-before-heading-p (&optional parent)
  6808. "Non-nil when an empty line should precede a new heading here.
  6809. When optional argument PARENT is non-nil, consider parent
  6810. headline instead of current one."
  6811. (pcase (assq 'heading org-blank-before-new-entry)
  6812. (`(heading . auto)
  6813. (save-excursion
  6814. (org-with-limited-levels
  6815. (unless (and (org-before-first-heading-p)
  6816. (not (outline-next-heading)))
  6817. (org-back-to-heading t)
  6818. (when parent (org-up-heading-safe))
  6819. (cond ((not (bobp))
  6820. (org-previous-line-empty-p))
  6821. ((outline-next-heading)
  6822. (org-previous-line-empty-p))
  6823. ;; Ignore trailing spaces on last buffer line.
  6824. ((progn (skip-chars-backward " \t") (bolp))
  6825. (org-previous-line-empty-p))
  6826. (t nil))))))
  6827. (`(heading . ,value) value)
  6828. (_ nil)))
  6829. (defun org-insert-heading (&optional arg invisible-ok top)
  6830. "Insert a new heading or an item with the same depth at point.
  6831. If point is at the beginning of a heading, insert a new heading
  6832. or a new headline above the current one. When at the beginning
  6833. of a regular line of text, turn it into a heading.
  6834. If point is in the middle of a line, split it and create a new
  6835. headline with the text in the current line after point (see
  6836. `org-M-RET-may-split-line' on how to modify this behavior). As
  6837. a special case, on a headline, splitting can only happen on the
  6838. title itself. E.g., this excludes breaking stars or tags.
  6839. With a `\\[universal-argument]' prefix, set \
  6840. `org-insert-heading-respect-content' to
  6841. a non-nil value for the duration of the command. This forces the
  6842. insertion of a heading after the current subtree, independently
  6843. on the location of point.
  6844. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6845. insert the heading at the end of the tree
  6846. above the current heading. For example, if point is within a
  6847. 2nd-level heading, then it will insert a 2nd-level heading at
  6848. the end of the 1st-level parent subtree.
  6849. When INVISIBLE-OK is set, stop at invisible headlines when going
  6850. back. This is important for non-interactive uses of the
  6851. command.
  6852. When optional argument TOP is non-nil, insert a level 1 heading,
  6853. unconditionally."
  6854. (interactive "P")
  6855. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6856. (level (org-current-level))
  6857. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6858. (cond
  6859. ((or org-insert-heading-respect-content
  6860. (member arg '((4) (16)))
  6861. (and (not invisible-ok)
  6862. (invisible-p (max (1- (point)) (point-min)))))
  6863. ;; Position point at the location of insertion.
  6864. (if (not level) ;before first headline
  6865. (org-with-limited-levels (outline-next-heading))
  6866. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6867. ;; is nil.
  6868. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6869. (cond ((equal arg '(16))
  6870. (org-up-heading-safe)
  6871. (org-end-of-subtree t t))
  6872. (t
  6873. (org-end-of-subtree t t))))
  6874. (unless (bolp) (insert "\n")) ;ensure final newline
  6875. (unless (and blank? (org-previous-line-empty-p))
  6876. (org-N-empty-lines-before-current (if blank? 1 0)))
  6877. (insert stars " \n")
  6878. (forward-char -1))
  6879. ;; At a headline...
  6880. ((org-at-heading-p)
  6881. (cond ((bolp)
  6882. (when blank? (save-excursion (insert "\n")))
  6883. (save-excursion (insert stars " \n"))
  6884. (unless (and blank? (org-previous-line-empty-p))
  6885. (org-N-empty-lines-before-current (if blank? 1 0)))
  6886. (end-of-line))
  6887. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6888. (org-match-line org-complex-heading-regexp)
  6889. (org-pos-in-match-range (point) 4))
  6890. ;; Grab the text that should moved to the new headline.
  6891. ;; Preserve tags.
  6892. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6893. (if (looking-at "[ \t]*$") (replace-match "")
  6894. (org-set-tags nil t))
  6895. (end-of-line)
  6896. (when blank? (insert "\n"))
  6897. (insert "\n" stars " ")
  6898. (when (org-string-nw-p split) (insert split))
  6899. (when (eobp) (save-excursion (insert "\n")))))
  6900. (t
  6901. (end-of-line)
  6902. (when blank? (insert "\n"))
  6903. (insert "\n" stars " ")
  6904. (when (eobp) (save-excursion (insert "\n"))))))
  6905. ;; On regular text, turn line into a headline or split, if
  6906. ;; appropriate.
  6907. ((bolp)
  6908. (insert stars " ")
  6909. (unless (and blank? (org-previous-line-empty-p))
  6910. (org-N-empty-lines-before-current (if blank? 1 0))))
  6911. (t
  6912. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6913. (end-of-line))
  6914. (insert "\n" stars " ")
  6915. (unless (and blank? (org-previous-line-empty-p))
  6916. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6917. (run-hooks 'org-insert-heading-hook))
  6918. (defun org-N-empty-lines-before-current (n)
  6919. "Make the number of empty lines before current exactly N.
  6920. So this will delete or add empty lines."
  6921. (let ((column (current-column)))
  6922. (beginning-of-line)
  6923. (unless (bobp)
  6924. (let ((start (save-excursion
  6925. (skip-chars-backward " \r\t\n")
  6926. (line-end-position))))
  6927. (delete-region start (line-end-position 0))))
  6928. (insert (make-string n ?\n))
  6929. (move-to-column column)))
  6930. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6931. "Return the heading of the current entry, without the stars.
  6932. When NO-TAGS is non-nil, don't include tags.
  6933. When NO-TODO is non-nil, don't include TODO keywords.
  6934. When NO-PRIORITY is non-nil, don't include priority cookie.
  6935. When NO-COMMENT is non-nil, don't include COMMENT string."
  6936. (save-excursion
  6937. (org-back-to-heading t)
  6938. (let ((case-fold-search nil))
  6939. (looking-at org-complex-heading-regexp)
  6940. (let ((todo (and (not no-todo) (match-string 2)))
  6941. (priority (and (not no-priority) (match-string 3)))
  6942. (headline (pcase (match-string 4)
  6943. (`nil "")
  6944. ((and (guard no-comment) h)
  6945. (replace-regexp-in-string
  6946. (eval-when-compile
  6947. (format "\\`%s[ \t]+" org-comment-string))
  6948. "" h))
  6949. (h h)))
  6950. (tags (and (not no-tags) (match-string 5))))
  6951. (mapconcat #'identity
  6952. (delq nil (list todo priority headline tags))
  6953. " ")))))
  6954. (defvar orgstruct-mode) ; defined below
  6955. (defun org-heading-components ()
  6956. "Return the components of the current heading.
  6957. This is a list with the following elements:
  6958. - the level as an integer
  6959. - the reduced level, different if `org-odd-levels-only' is set.
  6960. - the TODO keyword, or nil
  6961. - the priority character, like ?A, or nil if no priority is given
  6962. - the headline text itself, or the tags string if no headline text
  6963. - the tags string, or nil."
  6964. (save-excursion
  6965. (org-back-to-heading t)
  6966. (when (let (case-fold-search)
  6967. (looking-at
  6968. (if orgstruct-mode
  6969. org-heading-regexp
  6970. org-complex-heading-regexp)))
  6971. (if orgstruct-mode
  6972. (list (length (match-string 1))
  6973. (org-reduced-level (length (match-string 1)))
  6974. nil
  6975. nil
  6976. (match-string 2)
  6977. nil)
  6978. (list (length (match-string 1))
  6979. (org-reduced-level (length (match-string 1)))
  6980. (match-string-no-properties 2)
  6981. (and (match-end 3) (aref (match-string 3) 2))
  6982. (match-string-no-properties 4)
  6983. (match-string-no-properties 5))))))
  6984. (defun org-get-entry ()
  6985. "Get the entry text, after heading, entire subtree."
  6986. (save-excursion
  6987. (org-back-to-heading t)
  6988. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6989. (defun org-edit-headline (&optional heading)
  6990. "Edit the current headline.
  6991. Set it to HEADING when provided."
  6992. (interactive)
  6993. (org-with-wide-buffer
  6994. (org-back-to-heading t)
  6995. (let ((case-fold-search nil))
  6996. (when (looking-at org-complex-heading-regexp)
  6997. (let* ((old (match-string-no-properties 4))
  6998. (new (save-match-data
  6999. (org-trim (or heading (read-string "Edit: " old))))))
  7000. (unless (equal old new)
  7001. (if old (replace-match new t t nil 4)
  7002. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7003. (insert " " new))
  7004. (org-set-tags nil t)
  7005. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7006. (defun org-insert-heading-after-current ()
  7007. "Insert a new heading with same level as current, after current subtree."
  7008. (interactive)
  7009. (org-back-to-heading)
  7010. (org-insert-heading)
  7011. (org-move-subtree-down)
  7012. (end-of-line 1))
  7013. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7014. "Insert heading with `org-insert-heading-respect-content' set to t."
  7015. (interactive)
  7016. (org-insert-heading '(4) invisible-ok))
  7017. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7018. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7019. (interactive)
  7020. (org-insert-todo-heading force-state '(4)))
  7021. (defun org-insert-todo-heading (arg &optional force-heading)
  7022. "Insert a new heading with the same level and TODO state as current heading.
  7023. If the heading has no TODO state, or if the state is DONE, use
  7024. the first state (TODO by default). Also with one prefix arg,
  7025. force first state. With two prefix args, force inserting at the
  7026. end of the parent subtree.
  7027. When called at a plain list item, insert a new item with an
  7028. unchecked check box."
  7029. (interactive "P")
  7030. (when (or force-heading (not (org-insert-item 'checkbox)))
  7031. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7032. force-heading))
  7033. (save-excursion
  7034. (org-back-to-heading)
  7035. (outline-previous-heading)
  7036. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7037. (let* ((new-mark-x
  7038. (if (or (equal arg '(4))
  7039. (not (match-beginning 2))
  7040. (member (match-string 2) org-done-keywords))
  7041. (car org-todo-keywords-1)
  7042. (match-string 2)))
  7043. (new-mark
  7044. (or
  7045. (run-hook-with-args-until-success
  7046. 'org-todo-get-default-hook new-mark-x nil)
  7047. new-mark-x)))
  7048. (beginning-of-line 1)
  7049. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7050. (if org-treat-insert-todo-heading-as-state-change
  7051. (org-todo new-mark)
  7052. (insert new-mark " "))))
  7053. (when org-provide-todo-statistics
  7054. (org-update-parent-todo-statistics))))
  7055. (defun org-insert-subheading (arg)
  7056. "Insert a new subheading and demote it.
  7057. Works for outline headings and for plain lists alike."
  7058. (interactive "P")
  7059. (org-insert-heading arg)
  7060. (cond
  7061. ((org-at-heading-p) (org-do-demote))
  7062. ((org-at-item-p) (org-indent-item))))
  7063. (defun org-insert-todo-subheading (arg)
  7064. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7065. Works for outline headings and for plain lists alike."
  7066. (interactive "P")
  7067. (org-insert-todo-heading arg)
  7068. (cond
  7069. ((org-at-heading-p) (org-do-demote))
  7070. ((org-at-item-p) (org-indent-item))))
  7071. ;;; Promotion and Demotion
  7072. (defvar org-after-demote-entry-hook nil
  7073. "Hook run after an entry has been demoted.
  7074. The cursor will be at the beginning of the entry.
  7075. When a subtree is being demoted, the hook will be called for each node.")
  7076. (defvar org-after-promote-entry-hook nil
  7077. "Hook run after an entry has been promoted.
  7078. The cursor will be at the beginning of the entry.
  7079. When a subtree is being promoted, the hook will be called for each node.")
  7080. (defun org-promote-subtree ()
  7081. "Promote the entire subtree.
  7082. See also `org-promote'."
  7083. (interactive)
  7084. (save-excursion
  7085. (org-with-limited-levels (org-map-tree 'org-promote)))
  7086. (org-fix-position-after-promote))
  7087. (defun org-demote-subtree ()
  7088. "Demote the entire subtree.
  7089. See `org-demote' and `org-promote'."
  7090. (interactive)
  7091. (save-excursion
  7092. (org-with-limited-levels (org-map-tree 'org-demote)))
  7093. (org-fix-position-after-promote))
  7094. (defun org-do-promote ()
  7095. "Promote the current heading higher up the tree.
  7096. If the region is active in `transient-mark-mode', promote all
  7097. headings in the region."
  7098. (interactive)
  7099. (save-excursion
  7100. (if (org-region-active-p)
  7101. (org-map-region 'org-promote (region-beginning) (region-end))
  7102. (org-promote)))
  7103. (org-fix-position-after-promote))
  7104. (defun org-do-demote ()
  7105. "Demote the current heading lower down the tree.
  7106. If the region is active in `transient-mark-mode', demote all
  7107. headings in the region."
  7108. (interactive)
  7109. (save-excursion
  7110. (if (org-region-active-p)
  7111. (org-map-region 'org-demote (region-beginning) (region-end))
  7112. (org-demote)))
  7113. (org-fix-position-after-promote))
  7114. (defun org-fix-position-after-promote ()
  7115. "Fix cursor position and indentation after demoting/promoting."
  7116. (let ((pos (point)))
  7117. (when (save-excursion
  7118. (beginning-of-line)
  7119. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7120. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7121. (cond ((eobp) (insert " "))
  7122. ((eolp) (insert " "))
  7123. ((equal (char-after) ?\s) (forward-char 1))))))
  7124. (defun org-current-level ()
  7125. "Return the level of the current entry, or nil if before the first headline.
  7126. The level is the number of stars at the beginning of the
  7127. headline. Use `org-reduced-level' to remove the effect of
  7128. `org-odd-levels'. Unlike to `org-outline-level', this function
  7129. ignores inlinetasks."
  7130. (let ((level (org-with-limited-levels (org-outline-level))))
  7131. (and (> level 0) level)))
  7132. (defun org-get-previous-line-level ()
  7133. "Return the outline depth of the last headline before the current line.
  7134. Returns 0 for the first headline in the buffer, and nil if before the
  7135. first headline."
  7136. (and (org-current-level)
  7137. (or (and (/= (line-beginning-position) (point-min))
  7138. (save-excursion (beginning-of-line 0) (org-current-level)))
  7139. 0)))
  7140. (defun org-reduced-level (l)
  7141. "Compute the effective level of a heading.
  7142. This takes into account the setting of `org-odd-levels-only'."
  7143. (cond
  7144. ((zerop l) 0)
  7145. (org-odd-levels-only (1+ (floor (/ l 2))))
  7146. (t l)))
  7147. (defun org-level-increment ()
  7148. "Return the number of stars that will be added or removed at a
  7149. time to headlines when structure editing, based on the value of
  7150. `org-odd-levels-only'."
  7151. (if org-odd-levels-only 2 1))
  7152. (defun org-get-valid-level (level &optional change)
  7153. "Rectify a level change under the influence of `org-odd-levels-only'.
  7154. LEVEL is a current level, CHANGE is by how much the level should
  7155. be modified. Even if CHANGE is nil, LEVEL may be returned
  7156. modified because even level numbers will become the next higher
  7157. odd number. Returns values greater than 0."
  7158. (if org-odd-levels-only
  7159. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7160. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7161. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7162. (max 1 (+ level (or change 0)))))
  7163. (defun org-promote ()
  7164. "Promote the current heading higher up the tree."
  7165. (org-with-wide-buffer
  7166. (org-back-to-heading t)
  7167. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7168. after-change-functions))
  7169. (level (save-match-data (funcall outline-level)))
  7170. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7171. (diff (abs (- level (length up-head) -1))))
  7172. (cond
  7173. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7174. (replace-match "# " nil t))
  7175. ((= level 1)
  7176. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7177. (t (replace-match up-head nil t)))
  7178. (unless (= level 1)
  7179. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7180. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7181. (run-hooks 'org-after-promote-entry-hook))))
  7182. (defun org-demote ()
  7183. "Demote the current heading lower down the tree."
  7184. (org-with-wide-buffer
  7185. (org-back-to-heading t)
  7186. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7187. after-change-functions))
  7188. (level (save-match-data (funcall outline-level)))
  7189. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7190. (diff (abs (- level (length down-head) -1))))
  7191. (replace-match down-head nil t)
  7192. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7193. (when org-adapt-indentation (org-fixup-indentation diff))
  7194. (run-hooks 'org-after-demote-entry-hook))))
  7195. (defun org-cycle-level ()
  7196. "Cycle the level of an empty headline through possible states.
  7197. This goes first to child, then to parent, level, then up the hierarchy.
  7198. After top level, it switches back to sibling level."
  7199. (interactive)
  7200. (let ((org-adapt-indentation nil))
  7201. (when (org-point-at-end-of-empty-headline)
  7202. (setq this-command 'org-cycle-level) ; Only needed for caching
  7203. (let ((cur-level (org-current-level))
  7204. (prev-level (org-get-previous-line-level)))
  7205. (cond
  7206. ;; If first headline in file, promote to top-level.
  7207. ((= prev-level 0)
  7208. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7209. do (org-do-promote)))
  7210. ;; If same level as prev, demote one.
  7211. ((= prev-level cur-level)
  7212. (org-do-demote))
  7213. ;; If parent is top-level, promote to top level if not already.
  7214. ((= prev-level 1)
  7215. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7216. do (org-do-promote)))
  7217. ;; If top-level, return to prev-level.
  7218. ((= cur-level 1)
  7219. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7220. do (org-do-demote)))
  7221. ;; If less than prev-level, promote one.
  7222. ((< cur-level prev-level)
  7223. (org-do-promote))
  7224. ;; If deeper than prev-level, promote until higher than
  7225. ;; prev-level.
  7226. ((> cur-level prev-level)
  7227. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7228. do (org-do-promote))))
  7229. t))))
  7230. (defun org-map-tree (fun)
  7231. "Call FUN for every heading underneath the current one."
  7232. (org-back-to-heading t)
  7233. (let ((level (funcall outline-level)))
  7234. (save-excursion
  7235. (funcall fun)
  7236. (while (and (progn
  7237. (outline-next-heading)
  7238. (> (funcall outline-level) level))
  7239. (not (eobp)))
  7240. (funcall fun)))))
  7241. (defun org-map-region (fun beg end)
  7242. "Call FUN for every heading between BEG and END."
  7243. (let ((org-ignore-region t))
  7244. (save-excursion
  7245. (setq end (copy-marker end))
  7246. (goto-char beg)
  7247. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7248. (< (point) end))
  7249. (funcall fun))
  7250. (while (and (progn
  7251. (outline-next-heading)
  7252. (< (point) end))
  7253. (not (eobp)))
  7254. (funcall fun)))))
  7255. (defun org-fixup-indentation (diff)
  7256. "Change the indentation in the current entry by DIFF.
  7257. DIFF is an integer. Indentation is done according to the
  7258. following rules:
  7259. - Planning information and property drawers are always indented
  7260. according to the new level of the headline;
  7261. - Footnote definitions and their contents are ignored;
  7262. - Inlinetasks' boundaries are not shifted;
  7263. - Empty lines are ignored;
  7264. - Other lines' indentation are shifted by DIFF columns, unless
  7265. it would introduce a structural change in the document, in
  7266. which case no shifting is done at all.
  7267. Assume point is at a heading or an inlinetask beginning."
  7268. (org-with-wide-buffer
  7269. (narrow-to-region (line-beginning-position)
  7270. (save-excursion
  7271. (if (org-with-limited-levels (org-at-heading-p))
  7272. (org-with-limited-levels (outline-next-heading))
  7273. (org-inlinetask-goto-end))
  7274. (point)))
  7275. (forward-line)
  7276. ;; Indent properly planning info and property drawer.
  7277. (when (looking-at-p org-planning-line-re)
  7278. (org-indent-line)
  7279. (forward-line))
  7280. (when (looking-at org-property-drawer-re)
  7281. (goto-char (match-end 0))
  7282. (forward-line)
  7283. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7284. (catch 'no-shift
  7285. (when (zerop diff) (throw 'no-shift nil))
  7286. ;; If DIFF is negative, first check if a shift is possible at all
  7287. ;; (e.g., it doesn't break structure). This can only happen if
  7288. ;; some contents are not properly indented.
  7289. (let ((case-fold-search t))
  7290. (when (< diff 0)
  7291. (let ((diff (- diff))
  7292. (forbidden-re (concat org-outline-regexp
  7293. "\\|"
  7294. (substring org-footnote-definition-re 1))))
  7295. (save-excursion
  7296. (while (not (eobp))
  7297. (cond
  7298. ((looking-at-p "[ \t]*$") (forward-line))
  7299. ((and (looking-at-p org-footnote-definition-re)
  7300. (let ((e (org-element-at-point)))
  7301. (and (eq (org-element-type e) 'footnote-definition)
  7302. (goto-char (org-element-property :end e))))))
  7303. ((looking-at-p org-outline-regexp) (forward-line))
  7304. ;; Give up if shifting would move before column 0 or
  7305. ;; if it would introduce a headline or a footnote
  7306. ;; definition.
  7307. (t
  7308. (skip-chars-forward " \t")
  7309. (let ((ind (current-column)))
  7310. (when (or (< ind diff)
  7311. (and (= ind diff) (looking-at-p forbidden-re)))
  7312. (throw 'no-shift nil)))
  7313. ;; Ignore contents of example blocks and source
  7314. ;; blocks if their indentation is meant to be
  7315. ;; preserved. Jump to block's closing line.
  7316. (beginning-of-line)
  7317. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7318. (let ((e (org-element-at-point)))
  7319. (and (memq (org-element-type e)
  7320. '(example-block src-block))
  7321. (or org-src-preserve-indentation
  7322. (org-element-property :preserve-indent e))
  7323. (goto-char (org-element-property :end e))
  7324. (progn (skip-chars-backward " \r\t\n")
  7325. (beginning-of-line)
  7326. t))))
  7327. (forward-line))))))))
  7328. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7329. ;; by DIFF. Also skip contents of source or example blocks
  7330. ;; when indentation is meant to be preserved.
  7331. (while (not (eobp))
  7332. (cond
  7333. ((and (looking-at-p org-footnote-definition-re)
  7334. (let ((e (org-element-at-point)))
  7335. (and (eq (org-element-type e) 'footnote-definition)
  7336. (goto-char (org-element-property :end e))))))
  7337. ((looking-at-p org-outline-regexp) (forward-line))
  7338. ((looking-at-p "[ \t]*$") (forward-line))
  7339. (t
  7340. (indent-line-to (+ (org-get-indentation) diff))
  7341. (beginning-of-line)
  7342. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7343. (let ((e (org-element-at-point)))
  7344. (and (memq (org-element-type e)
  7345. '(example-block src-block))
  7346. (or org-src-preserve-indentation
  7347. (org-element-property :preserve-indent e))
  7348. (goto-char (org-element-property :end e))
  7349. (progn (skip-chars-backward " \r\t\n")
  7350. (beginning-of-line)
  7351. t))))
  7352. (forward-line)))))))))
  7353. (defun org-convert-to-odd-levels ()
  7354. "Convert an Org file with all levels allowed to one with odd levels.
  7355. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7356. level 5 etc."
  7357. (interactive)
  7358. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7359. (let ((outline-level 'org-outline-level)
  7360. (org-odd-levels-only nil) n)
  7361. (save-excursion
  7362. (goto-char (point-min))
  7363. (while (re-search-forward "^\\*\\*+ " nil t)
  7364. (setq n (- (length (match-string 0)) 2))
  7365. (while (>= (setq n (1- n)) 0)
  7366. (org-demote))
  7367. (end-of-line 1))))))
  7368. (defun org-convert-to-oddeven-levels ()
  7369. "Convert an Org file with only odd levels to one with odd/even levels.
  7370. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7371. file contains a section with an even level, conversion would
  7372. destroy the structure of the file. An error is signaled in this
  7373. case."
  7374. (interactive)
  7375. (goto-char (point-min))
  7376. ;; First check if there are no even levels
  7377. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7378. (org-show-set-visibility 'canonical)
  7379. (error "Not all levels are odd in this file. Conversion not possible"))
  7380. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7381. (let ((outline-regexp org-outline-regexp)
  7382. (outline-level 'org-outline-level)
  7383. (org-odd-levels-only nil) n)
  7384. (save-excursion
  7385. (goto-char (point-min))
  7386. (while (re-search-forward "^\\*\\*+ " nil t)
  7387. (setq n (/ (1- (length (match-string 0))) 2))
  7388. (while (>= (setq n (1- n)) 0)
  7389. (org-promote))
  7390. (end-of-line 1))))))
  7391. (defun org-tr-level (n)
  7392. "Make N odd if required."
  7393. (if org-odd-levels-only (1+ (/ n 2)) n))
  7394. ;;; Vertical tree motion, cutting and pasting of subtrees
  7395. (defun org-move-subtree-up (&optional arg)
  7396. "Move the current subtree up past ARG headlines of the same level."
  7397. (interactive "p")
  7398. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7399. (defun org-move-subtree-down (&optional arg)
  7400. "Move the current subtree down past ARG headlines of the same level."
  7401. (interactive "p")
  7402. (setq arg (prefix-numeric-value arg))
  7403. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7404. 'org-get-last-sibling))
  7405. (ins-point (make-marker))
  7406. (cnt (abs arg))
  7407. (col (current-column))
  7408. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7409. ;; Select the tree
  7410. (org-back-to-heading)
  7411. (setq beg0 (point))
  7412. (save-excursion
  7413. (setq ne-beg (org-back-over-empty-lines))
  7414. (setq beg (point)))
  7415. (save-match-data
  7416. (save-excursion (outline-end-of-heading)
  7417. (setq folded (org-invisible-p)))
  7418. (progn (org-end-of-subtree nil t)
  7419. (unless (eobp) (backward-char))))
  7420. (outline-next-heading)
  7421. (setq ne-end (org-back-over-empty-lines))
  7422. (setq end (point))
  7423. (goto-char beg0)
  7424. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7425. ;; include less whitespace
  7426. (save-excursion
  7427. (goto-char beg)
  7428. (forward-line (- ne-beg ne-end))
  7429. (setq beg (point))))
  7430. ;; Find insertion point, with error handling
  7431. (while (> cnt 0)
  7432. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7433. (progn (goto-char beg0)
  7434. (user-error "Cannot move past superior level or buffer limit")))
  7435. (setq cnt (1- cnt)))
  7436. (when (> arg 0)
  7437. ;; Moving forward - still need to move over subtree
  7438. (org-end-of-subtree t t)
  7439. (save-excursion
  7440. (org-back-over-empty-lines)
  7441. (or (bolp) (newline))))
  7442. (setq ne-ins (org-back-over-empty-lines))
  7443. (move-marker ins-point (point))
  7444. (setq txt (buffer-substring beg end))
  7445. (org-save-markers-in-region beg end)
  7446. (delete-region beg end)
  7447. (org-remove-empty-overlays-at beg)
  7448. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7449. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7450. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7451. (let ((bbb (point)))
  7452. (insert-before-markers txt)
  7453. (org-reinstall-markers-in-region bbb)
  7454. (move-marker ins-point bbb))
  7455. (or (bolp) (insert "\n"))
  7456. (setq ins-end (point))
  7457. (goto-char ins-point)
  7458. (org-skip-whitespace)
  7459. (when (and (< arg 0)
  7460. (org-first-sibling-p)
  7461. (> ne-ins ne-beg))
  7462. ;; Move whitespace back to beginning
  7463. (save-excursion
  7464. (goto-char ins-end)
  7465. (let ((kill-whole-line t))
  7466. (kill-line (- ne-ins ne-beg)) (point)))
  7467. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7468. (move-marker ins-point nil)
  7469. (if folded
  7470. (outline-hide-subtree)
  7471. (org-show-entry)
  7472. (org-show-children)
  7473. (org-cycle-hide-drawers 'children))
  7474. (org-clean-visibility-after-subtree-move)
  7475. ;; move back to the initial column we were at
  7476. (move-to-column col)))
  7477. (defvar org-subtree-clip ""
  7478. "Clipboard for cut and paste of subtrees.
  7479. This is actually only a copy of the kill, because we use the normal kill
  7480. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7481. (defvar org-subtree-clip-folded nil
  7482. "Was the last copied subtree folded?
  7483. This is used to fold the tree back after pasting.")
  7484. (defun org-cut-subtree (&optional n)
  7485. "Cut the current subtree into the clipboard.
  7486. With prefix arg N, cut this many sequential subtrees.
  7487. This is a short-hand for marking the subtree and then cutting it."
  7488. (interactive "p")
  7489. (org-copy-subtree n 'cut))
  7490. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7491. "Copy the current subtree it in the clipboard.
  7492. With prefix arg N, copy this many sequential subtrees.
  7493. This is a short-hand for marking the subtree and then copying it.
  7494. If CUT is non-nil, actually cut the subtree.
  7495. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7496. of some markers in the region, even if CUT is non-nil. This is
  7497. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7498. (interactive "p")
  7499. (let (beg end folded (beg0 (point)))
  7500. (if (called-interactively-p 'any)
  7501. (org-back-to-heading nil) ; take what looks like a subtree
  7502. (org-back-to-heading t)) ; take what is really there
  7503. (setq beg (point))
  7504. (skip-chars-forward " \t\r\n")
  7505. (save-match-data
  7506. (if nosubtrees
  7507. (outline-next-heading)
  7508. (save-excursion (outline-end-of-heading)
  7509. (setq folded (org-invisible-p)))
  7510. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7511. (org-end-of-subtree t t)))
  7512. ;; Include the end of an inlinetask
  7513. (when (and (featurep 'org-inlinetask)
  7514. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7515. "END[ \t]*$")))
  7516. (end-of-line))
  7517. (setq end (point))
  7518. (goto-char beg0)
  7519. (when (> end beg)
  7520. (setq org-subtree-clip-folded folded)
  7521. (when (or cut force-store-markers)
  7522. (org-save-markers-in-region beg end))
  7523. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7524. (setq org-subtree-clip (current-kill 0))
  7525. (message "%s: Subtree(s) with %d characters"
  7526. (if cut "Cut" "Copied")
  7527. (length org-subtree-clip)))))
  7528. (defun org-paste-subtree (&optional level tree for-yank remove)
  7529. "Paste the clipboard as a subtree, with modification of headline level.
  7530. The entire subtree is promoted or demoted in order to match a new headline
  7531. level.
  7532. If the cursor is at the beginning of a headline, the same level as
  7533. that headline is used to paste the tree.
  7534. If not, the new level is derived from the *visible* headings
  7535. before and after the insertion point, and taken to be the inferior headline
  7536. level of the two. So if the previous visible heading is level 3 and the
  7537. next is level 4 (or vice versa), level 4 will be used for insertion.
  7538. This makes sure that the subtree remains an independent subtree and does
  7539. not swallow low level entries.
  7540. You can also force a different level, either by using a numeric prefix
  7541. argument, or by inserting the heading marker by hand. For example, if the
  7542. cursor is after \"*****\", then the tree will be shifted to level 5.
  7543. If optional TREE is given, use this text instead of the kill ring.
  7544. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7545. move back over whitespace before inserting, and move point to the end of
  7546. the inserted text when done.
  7547. When REMOVE is non-nil, remove the subtree from the clipboard."
  7548. (interactive "P")
  7549. (setq tree (or tree (and kill-ring (current-kill 0))))
  7550. (unless (org-kill-is-subtree-p tree)
  7551. (user-error "%s"
  7552. (substitute-command-keys
  7553. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7554. (org-with-limited-levels
  7555. (let* ((visp (not (org-invisible-p)))
  7556. (txt tree)
  7557. (^re_ "\\(\\*+\\)[ \t]*")
  7558. (old-level (if (string-match org-outline-regexp-bol txt)
  7559. (- (match-end 0) (match-beginning 0) 1)
  7560. -1))
  7561. (force-level (cond (level (prefix-numeric-value level))
  7562. ((and (looking-at "[ \t]*$")
  7563. (string-match
  7564. "^\\*+$" (buffer-substring
  7565. (point-at-bol) (point))))
  7566. (- (match-end 0) (match-beginning 0)))
  7567. ((and (bolp)
  7568. (looking-at org-outline-regexp))
  7569. (- (match-end 0) (point) 1))))
  7570. (previous-level (save-excursion
  7571. (condition-case nil
  7572. (progn
  7573. (outline-previous-visible-heading 1)
  7574. (if (looking-at ^re_)
  7575. (- (match-end 0) (match-beginning 0) 1)
  7576. 1))
  7577. (error 1))))
  7578. (next-level (save-excursion
  7579. (condition-case nil
  7580. (progn
  7581. (or (looking-at org-outline-regexp)
  7582. (outline-next-visible-heading 1))
  7583. (if (looking-at ^re_)
  7584. (- (match-end 0) (match-beginning 0) 1)
  7585. 1))
  7586. (error 1))))
  7587. (new-level (or force-level (max previous-level next-level)))
  7588. (shift (if (or (= old-level -1)
  7589. (= new-level -1)
  7590. (= old-level new-level))
  7591. 0
  7592. (- new-level old-level)))
  7593. (delta (if (> shift 0) -1 1))
  7594. (func (if (> shift 0) 'org-demote 'org-promote))
  7595. (org-odd-levels-only nil)
  7596. beg end newend)
  7597. ;; Remove the forced level indicator
  7598. (when force-level
  7599. (delete-region (point-at-bol) (point)))
  7600. ;; Paste
  7601. (beginning-of-line (if (bolp) 1 2))
  7602. (setq beg (point))
  7603. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7604. (insert-before-markers txt)
  7605. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7606. (setq newend (point))
  7607. (org-reinstall-markers-in-region beg)
  7608. (setq end (point))
  7609. (goto-char beg)
  7610. (skip-chars-forward " \t\n\r")
  7611. (setq beg (point))
  7612. (when (and (org-invisible-p) visp)
  7613. (save-excursion (outline-show-heading)))
  7614. ;; Shift if necessary
  7615. (unless (= shift 0)
  7616. (save-restriction
  7617. (narrow-to-region beg end)
  7618. (while (not (= shift 0))
  7619. (org-map-region func (point-min) (point-max))
  7620. (setq shift (+ delta shift)))
  7621. (goto-char (point-min))
  7622. (setq newend (point-max))))
  7623. (when (or (called-interactively-p 'interactive) for-yank)
  7624. (message "Clipboard pasted as level %d subtree" new-level))
  7625. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7626. kill-ring
  7627. (eq org-subtree-clip (current-kill 0))
  7628. org-subtree-clip-folded)
  7629. ;; The tree was folded before it was killed/copied
  7630. (outline-hide-subtree))
  7631. (and for-yank (goto-char newend))
  7632. (and remove (setq kill-ring (cdr kill-ring))))))
  7633. (defun org-kill-is-subtree-p (&optional txt)
  7634. "Check if the current kill is an outline subtree, or a set of trees.
  7635. Returns nil if kill does not start with a headline, or if the first
  7636. headline level is not the largest headline level in the tree.
  7637. So this will actually accept several entries of equal levels as well,
  7638. which is OK for `org-paste-subtree'.
  7639. If optional TXT is given, check this string instead of the current kill."
  7640. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7641. (re (org-get-limited-outline-regexp))
  7642. (^re (concat "^" re))
  7643. (start-level (and kill
  7644. (string-match
  7645. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7646. kill)
  7647. (- (match-end 2) (match-beginning 2) 1)))
  7648. (start (1+ (or (match-beginning 2) -1))))
  7649. (if (not start-level)
  7650. (progn
  7651. nil) ;; does not even start with a heading
  7652. (catch 'exit
  7653. (while (setq start (string-match ^re kill (1+ start)))
  7654. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7655. (throw 'exit nil)))
  7656. t))))
  7657. (defvar org-markers-to-move nil
  7658. "Markers that should be moved with a cut-and-paste operation.
  7659. Those markers are stored together with their positions relative to
  7660. the start of the region.")
  7661. (defun org-save-markers-in-region (beg end)
  7662. "Check markers in region.
  7663. If these markers are between BEG and END, record their position relative
  7664. to BEG, so that after moving the block of text, we can put the markers back
  7665. into place.
  7666. This function gets called just before an entry or tree gets cut from the
  7667. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7668. called immediately, to move the markers with the entries."
  7669. (setq org-markers-to-move nil)
  7670. (when (featurep 'org-clock)
  7671. (org-clock-save-markers-for-cut-and-paste beg end))
  7672. (when (featurep 'org-agenda)
  7673. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7674. (defun org-check-and-save-marker (marker beg end)
  7675. "Check if MARKER is between BEG and END.
  7676. If yes, remember the marker and the distance to BEG."
  7677. (when (and (marker-buffer marker)
  7678. (equal (marker-buffer marker) (current-buffer))
  7679. (>= marker beg) (< marker end))
  7680. (push (cons marker (- marker beg)) org-markers-to-move)))
  7681. (defun org-reinstall-markers-in-region (beg)
  7682. "Move all remembered markers to their position relative to BEG."
  7683. (dolist (x org-markers-to-move)
  7684. (move-marker (car x) (+ beg (cdr x))))
  7685. (setq org-markers-to-move nil))
  7686. (defun org-narrow-to-subtree ()
  7687. "Narrow buffer to the current subtree."
  7688. (interactive)
  7689. (save-excursion
  7690. (save-match-data
  7691. (org-with-limited-levels
  7692. (narrow-to-region
  7693. (progn (org-back-to-heading t) (point))
  7694. (progn (org-end-of-subtree t t)
  7695. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7696. (point)))))))
  7697. (defun org-narrow-to-block ()
  7698. "Narrow buffer to the current block."
  7699. (interactive)
  7700. (let* ((case-fold-search t)
  7701. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7702. "^[ \t]*#\\+end_.*")))
  7703. (if blockp
  7704. (narrow-to-region (car blockp) (cdr blockp))
  7705. (user-error "Not in a block"))))
  7706. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7707. "Clone the task (subtree) at point N times.
  7708. The clones will be inserted as siblings.
  7709. In interactive use, the user will be prompted for the number of
  7710. clones to be produced. If the entry has a timestamp, the user
  7711. will also be prompted for a time shift, which may be a repeater
  7712. as used in time stamps, for example `+3d'. To disable this,
  7713. you can call the function with a universal prefix argument.
  7714. When a valid repeater is given and the entry contains any time
  7715. stamps, the clones will become a sequence in time, with time
  7716. stamps in the subtree shifted for each clone produced. If SHIFT
  7717. is nil or the empty string, time stamps will be left alone. The
  7718. ID property of the original subtree is removed.
  7719. In each clone, all the CLOCK entries will be removed. This
  7720. prevents Org from considering that the clocked times overlap.
  7721. If the original subtree did contain time stamps with a repeater,
  7722. the following will happen:
  7723. - the repeater will be removed in each clone
  7724. - an additional clone will be produced, with the current, unshifted
  7725. date(s) in the entry.
  7726. - the original entry will be placed *after* all the clones, with
  7727. repeater intact.
  7728. - the start days in the repeater in the original entry will be shifted
  7729. to past the last clone.
  7730. In this way you can spell out a number of instances of a repeating task,
  7731. and still retain the repeater to cover future instances of the task.
  7732. As described above, N+1 clones are produced when the original
  7733. subtree has a repeater. Setting N to 0, then, can be used to
  7734. remove the repeater from a subtree and create a shifted clone
  7735. with the original repeater."
  7736. (interactive "nNumber of clones to produce: ")
  7737. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7738. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7739. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7740. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7741. (shift
  7742. (or shift
  7743. (if (and (not (equal current-prefix-arg '(4)))
  7744. (save-excursion
  7745. (goto-char beg)
  7746. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7747. (read-from-minibuffer
  7748. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7749. ""))) ;No time shift
  7750. (doshift
  7751. (and (org-string-nw-p shift)
  7752. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7753. shift)
  7754. (user-error "Invalid shift specification %s" shift)))))
  7755. (goto-char end-of-tree)
  7756. (unless (bolp) (insert "\n"))
  7757. (let* ((end (point))
  7758. (template (buffer-substring beg end))
  7759. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7760. (shift-what (pcase (and doshift (match-string 2 shift))
  7761. (`nil nil)
  7762. ("d" 'day)
  7763. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7764. ("m" 'month)
  7765. ("y" 'year)
  7766. (_ (error "Unsupported time unit"))))
  7767. (nmin 1)
  7768. (nmax n)
  7769. (n-no-remove -1)
  7770. (idprop (org-entry-get nil "ID")))
  7771. (when (and doshift
  7772. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7773. template))
  7774. (delete-region beg end)
  7775. (setq end beg)
  7776. (setq nmin 0)
  7777. (setq nmax (1+ nmax))
  7778. (setq n-no-remove nmax))
  7779. (goto-char end)
  7780. (cl-loop for n from nmin to nmax do
  7781. (insert
  7782. ;; Prepare clone.
  7783. (with-temp-buffer
  7784. (insert template)
  7785. (org-mode)
  7786. (goto-char (point-min))
  7787. (org-show-subtree)
  7788. (and idprop (if org-clone-delete-id
  7789. (org-entry-delete nil "ID")
  7790. (org-id-get-create t)))
  7791. (unless (= n 0)
  7792. (while (re-search-forward org-clock-line-re nil t)
  7793. (delete-region (line-beginning-position)
  7794. (line-beginning-position 2)))
  7795. (goto-char (point-min))
  7796. (while (re-search-forward org-drawer-regexp nil t)
  7797. (org-remove-empty-drawer-at (point))))
  7798. (goto-char (point-min))
  7799. (when doshift
  7800. (while (re-search-forward org-ts-regexp-both nil t)
  7801. (org-timestamp-change (* n shift-n) shift-what))
  7802. (unless (= n n-no-remove)
  7803. (goto-char (point-min))
  7804. (while (re-search-forward org-ts-regexp nil t)
  7805. (save-excursion
  7806. (goto-char (match-beginning 0))
  7807. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7808. (delete-region (match-beginning 1) (match-end 1)))))))
  7809. (buffer-string)))))
  7810. (goto-char beg)))
  7811. ;;; Outline Sorting
  7812. (defun org-sort (&optional with-case)
  7813. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7814. Optional argument WITH-CASE means sort case-sensitively."
  7815. (interactive "P")
  7816. (org-call-with-arg
  7817. (cond ((org-at-table-p) #'org-table-sort-lines)
  7818. ((org-at-item-p) #'org-sort-list)
  7819. (t #'org-sort-entries))
  7820. with-case))
  7821. (defun org-sort-remove-invisible (s)
  7822. "Remove invisible part of links and emphasis markers from string S."
  7823. (remove-text-properties 0 (length s) org-rm-props s)
  7824. (replace-regexp-in-string
  7825. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7826. (replace-regexp-in-string
  7827. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7828. (org-link-display-format s)
  7829. t t) t t))
  7830. (defvar org-priority-regexp) ; defined later in the file
  7831. (defvar org-after-sorting-entries-or-items-hook nil
  7832. "Hook that is run after a bunch of entries or items have been sorted.
  7833. When children are sorted, the cursor is in the parent line when this
  7834. hook gets called. When a region or a plain list is sorted, the cursor
  7835. will be in the first entry of the sorted region/list.")
  7836. (defun org-sort-entries
  7837. (&optional with-case sorting-type getkey-func compare-func property
  7838. interactive?)
  7839. "Sort entries on a certain level of an outline tree.
  7840. If there is an active region, the entries in the region are sorted.
  7841. Else, if the cursor is before the first entry, sort the top-level items.
  7842. Else, the children of the entry at point are sorted.
  7843. Sorting can be alphabetically, numerically, by date/time as given by
  7844. a time stamp, by a property, by priority order, or by a custom function.
  7845. The command prompts for the sorting type unless it has been given to the
  7846. function through the SORTING-TYPE argument, which needs to be a character,
  7847. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7848. the precise meaning of each character:
  7849. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7850. c By creation time, which is assumed to be the first inactive time stamp
  7851. at the beginning of a line.
  7852. d By deadline date/time.
  7853. k By clocking time.
  7854. n Numerically, by converting the beginning of the entry/item to a number.
  7855. o By order of TODO keywords.
  7856. p By priority according to the cookie.
  7857. r By the value of a property.
  7858. s By scheduled date/time.
  7859. t By date/time, either the first active time stamp in the entry, or, if
  7860. none exist, by the first inactive one.
  7861. Capital letters will reverse the sort order.
  7862. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7863. called with point at the beginning of the record. It must return a
  7864. value that is compatible with COMPARE-FUNC, the function used to
  7865. compare entries.
  7866. Comparing entries ignores case by default. However, with an optional argument
  7867. WITH-CASE, the sorting considers case as well.
  7868. Sorting is done against the visible part of the headlines, it ignores hidden
  7869. links.
  7870. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7871. A non-nil value for INTERACTIVE? is used to signal that this
  7872. function is being called interactively."
  7873. (interactive (list current-prefix-arg nil nil nil nil t))
  7874. (let ((case-func (if with-case 'identity 'downcase))
  7875. start beg end stars re re2
  7876. txt what tmp)
  7877. ;; Find beginning and end of region to sort
  7878. (cond
  7879. ((org-region-active-p)
  7880. ;; we will sort the region
  7881. (setq end (region-end)
  7882. what "region")
  7883. (goto-char (region-beginning))
  7884. (unless (org-at-heading-p) (outline-next-heading))
  7885. (setq start (point)))
  7886. ((or (org-at-heading-p)
  7887. (ignore-errors (progn (org-back-to-heading) t)))
  7888. ;; we will sort the children of the current headline
  7889. (org-back-to-heading)
  7890. (setq start (point)
  7891. end (progn (org-end-of-subtree t t)
  7892. (or (bolp) (insert "\n"))
  7893. (when (>= (org-back-over-empty-lines) 1)
  7894. (forward-line 1))
  7895. (point))
  7896. what "children")
  7897. (goto-char start)
  7898. (outline-show-subtree)
  7899. (outline-next-heading))
  7900. (t
  7901. ;; we will sort the top-level entries in this file
  7902. (goto-char (point-min))
  7903. (or (org-at-heading-p) (outline-next-heading))
  7904. (setq start (point))
  7905. (goto-char (point-max))
  7906. (beginning-of-line 1)
  7907. (when (looking-at ".*?\\S-")
  7908. ;; File ends in a non-white line
  7909. (end-of-line 1)
  7910. (insert "\n"))
  7911. (setq end (point-max))
  7912. (setq what "top-level")
  7913. (goto-char start)
  7914. (outline-show-all)))
  7915. (setq beg (point))
  7916. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7917. (looking-at "\\(\\*+\\)")
  7918. (setq stars (match-string 1)
  7919. re (concat "^" (regexp-quote stars) " +")
  7920. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7921. txt (buffer-substring beg end))
  7922. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7923. (when (and (not (equal stars "*")) (string-match re2 txt))
  7924. (user-error "Region to sort contains a level above the first entry"))
  7925. (unless sorting-type
  7926. (message
  7927. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7928. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7929. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7930. what)
  7931. (setq sorting-type (read-char-exclusive)))
  7932. (unless getkey-func
  7933. (and (= (downcase sorting-type) ?f)
  7934. (setq getkey-func
  7935. (or (and interactive?
  7936. (org-read-function
  7937. "Function for extracting keys: "))
  7938. (error "Missing key extractor")))))
  7939. (and (= (downcase sorting-type) ?r)
  7940. (not property)
  7941. (setq property
  7942. (completing-read "Property: "
  7943. (mapcar #'list (org-buffer-property-keys t))
  7944. nil t)))
  7945. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7946. (message "Sorting entries...")
  7947. (save-restriction
  7948. (narrow-to-region start end)
  7949. (let ((restore-clock?
  7950. ;; The clock marker is lost when using `sort-subr'; mark
  7951. ;; the clock with temporary `:org-clock-marker-backup'
  7952. ;; text property.
  7953. (when (and (eq (org-clock-is-active) (current-buffer))
  7954. (<= start (marker-position org-clock-marker))
  7955. (>= end (marker-position org-clock-marker)))
  7956. (org-with-silent-modifications
  7957. (put-text-property (1- org-clock-marker) org-clock-marker
  7958. :org-clock-marker-backup t))
  7959. t))
  7960. (dcst (downcase sorting-type))
  7961. (case-fold-search nil)
  7962. (now (current-time)))
  7963. (sort-subr
  7964. (/= dcst sorting-type)
  7965. ;; This function moves to the beginning character of the "record" to
  7966. ;; be sorted.
  7967. (lambda nil
  7968. (if (re-search-forward re nil t)
  7969. (goto-char (match-beginning 0))
  7970. (goto-char (point-max))))
  7971. ;; This function moves to the last character of the "record" being
  7972. ;; sorted.
  7973. (lambda nil
  7974. (save-match-data
  7975. (condition-case nil
  7976. (outline-forward-same-level 1)
  7977. (error
  7978. (goto-char (point-max))))))
  7979. ;; This function returns the value that gets sorted against.
  7980. (lambda nil
  7981. (cond
  7982. ((= dcst ?n)
  7983. (if (looking-at org-complex-heading-regexp)
  7984. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7985. nil))
  7986. ((= dcst ?a)
  7987. (if (looking-at org-complex-heading-regexp)
  7988. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7989. nil))
  7990. ((= dcst ?k)
  7991. (or (get-text-property (point) :org-clock-minutes) 0))
  7992. ((= dcst ?t)
  7993. (let ((end (save-excursion (outline-next-heading) (point))))
  7994. (if (or (re-search-forward org-ts-regexp end t)
  7995. (re-search-forward org-ts-regexp-both end t))
  7996. (org-time-string-to-seconds (match-string 0))
  7997. (float-time now))))
  7998. ((= dcst ?c)
  7999. (let ((end (save-excursion (outline-next-heading) (point))))
  8000. (if (re-search-forward
  8001. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8002. end t)
  8003. (org-time-string-to-seconds (match-string 0))
  8004. (float-time now))))
  8005. ((= dcst ?s)
  8006. (let ((end (save-excursion (outline-next-heading) (point))))
  8007. (if (re-search-forward org-scheduled-time-regexp end t)
  8008. (org-time-string-to-seconds (match-string 1))
  8009. (float-time now))))
  8010. ((= dcst ?d)
  8011. (let ((end (save-excursion (outline-next-heading) (point))))
  8012. (if (re-search-forward org-deadline-time-regexp end t)
  8013. (org-time-string-to-seconds (match-string 1))
  8014. (float-time now))))
  8015. ((= dcst ?p)
  8016. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8017. (string-to-char (match-string 2))
  8018. org-default-priority))
  8019. ((= dcst ?r)
  8020. (or (org-entry-get nil property) ""))
  8021. ((= dcst ?o)
  8022. (when (looking-at org-complex-heading-regexp)
  8023. (let* ((m (match-string 2))
  8024. (s (if (member m org-done-keywords) '- '+)))
  8025. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8026. ((= dcst ?f)
  8027. (if getkey-func
  8028. (progn
  8029. (setq tmp (funcall getkey-func))
  8030. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8031. tmp)
  8032. (error "Invalid key function `%s'" getkey-func)))
  8033. (t (error "Invalid sorting type `%c'" sorting-type))))
  8034. nil
  8035. (cond
  8036. ((= dcst ?a) 'string<)
  8037. ((= dcst ?f)
  8038. (or compare-func
  8039. (and interactive?
  8040. (org-read-function
  8041. (concat "Function for comparing keys "
  8042. "(empty for default `sort-subr' predicate): ")
  8043. 'allow-empty))))
  8044. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  8045. (when restore-clock?
  8046. (move-marker org-clock-marker
  8047. (1+ (next-single-property-change
  8048. start :org-clock-marker-backup)))
  8049. (remove-text-properties (1- org-clock-marker) org-clock-marker
  8050. '(:org-clock-marker-backup t)))))
  8051. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8052. (message "Sorting entries...done")))
  8053. ;;; The orgstruct minor mode
  8054. ;; Define a minor mode which can be used in other modes in order to
  8055. ;; integrate the Org mode structure editing commands.
  8056. ;; This is really a hack, because the Org mode structure commands use
  8057. ;; keys which normally belong to the major mode. Here is how it
  8058. ;; works: The minor mode defines all the keys necessary to operate the
  8059. ;; structure commands, but wraps the commands into a function which
  8060. ;; tests if the cursor is currently at a headline or a plain list
  8061. ;; item. If that is the case, the structure command is used,
  8062. ;; temporarily setting many Org mode variables like regular
  8063. ;; expressions for filling etc. However, when any of those keys is
  8064. ;; used at a different location, function uses `key-binding' to look
  8065. ;; up if the key has an associated command in another currently active
  8066. ;; keymap (minor modes, major mode, global), and executes that
  8067. ;; command. There might be problems if any of the keys is otherwise
  8068. ;; used as a prefix key.
  8069. (defcustom orgstruct-heading-prefix-regexp ""
  8070. "Regexp that matches the custom prefix of Org headlines in
  8071. orgstruct(++)-mode."
  8072. :group 'org
  8073. :version "26.1"
  8074. :package-version '(Org . "8.3")
  8075. :type 'regexp)
  8076. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8077. (defcustom orgstruct-setup-hook nil
  8078. "Hook run after orgstruct-mode-map is filled."
  8079. :group 'org
  8080. :version "24.4"
  8081. :package-version '(Org . "8.0")
  8082. :type 'hook)
  8083. (defvar orgstruct-initialized nil)
  8084. (defvar org-local-vars nil
  8085. "List of local variables, for use by `orgstruct-mode'.")
  8086. ;;;###autoload
  8087. (define-minor-mode orgstruct-mode
  8088. "Toggle the minor mode `orgstruct-mode'.
  8089. This mode is for using Org mode structure commands in other
  8090. modes. The following keys behave as if Org mode were active, if
  8091. the cursor is on a headline, or on a plain list item (both as
  8092. defined by Org mode)."
  8093. nil " OrgStruct" (make-sparse-keymap)
  8094. (funcall (if orgstruct-mode
  8095. 'add-to-invisibility-spec
  8096. 'remove-from-invisibility-spec)
  8097. '(outline . t))
  8098. (when orgstruct-mode
  8099. (org-load-modules-maybe)
  8100. (unless orgstruct-initialized
  8101. (orgstruct-setup)
  8102. (setq orgstruct-initialized t))))
  8103. ;;;###autoload
  8104. (defun turn-on-orgstruct ()
  8105. "Unconditionally turn on `orgstruct-mode'."
  8106. (orgstruct-mode 1))
  8107. (defvar-local orgstruct-is-++ nil
  8108. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8109. (defvar-local org-fb-vars nil)
  8110. (defun orgstruct++-mode (&optional arg)
  8111. "Toggle `orgstruct-mode', the enhanced version of it.
  8112. In addition to setting orgstruct-mode, this also exports all
  8113. indentation and autofilling variables from Org mode into the
  8114. buffer. It will also recognize item context in multiline items."
  8115. (interactive "P")
  8116. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8117. (if (< arg 1)
  8118. (progn (orgstruct-mode -1)
  8119. (dolist (v org-fb-vars)
  8120. (set (make-local-variable (car v))
  8121. (if (eq (car-safe (cadr v)) 'quote)
  8122. (cl-cadadr v)
  8123. (nth 1 v)))))
  8124. (orgstruct-mode 1)
  8125. (setq org-fb-vars nil)
  8126. (unless org-local-vars
  8127. (setq org-local-vars (org-get-local-variables)))
  8128. (let (var val)
  8129. (dolist (x org-local-vars)
  8130. (when (string-match
  8131. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8132. \\|fill-prefix\\|indent-\\)"
  8133. (symbol-name (car x)))
  8134. (setq var (car x) val (nth 1 x))
  8135. (push (list var `(quote ,(eval var))) org-fb-vars)
  8136. (set (make-local-variable var)
  8137. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8138. (setq-local orgstruct-is-++ t))))
  8139. ;;;###autoload
  8140. (defun turn-on-orgstruct++ ()
  8141. "Unconditionally turn on `orgstruct++-mode'."
  8142. (orgstruct++-mode 1))
  8143. (defun orgstruct-error ()
  8144. "Error when there is no default binding for a structure key."
  8145. (interactive)
  8146. (funcall (if (fboundp 'user-error)
  8147. 'user-error
  8148. 'error)
  8149. "This key has no function outside structure elements"))
  8150. (defun orgstruct-setup ()
  8151. "Setup orgstruct keymap."
  8152. (dolist (cell '((org-demote . t)
  8153. (org-metaleft . t)
  8154. (org-metaright . t)
  8155. (org-promote . t)
  8156. (org-shiftmetaleft . t)
  8157. (org-shiftmetaright . t)
  8158. org-backward-element
  8159. org-backward-heading-same-level
  8160. org-ctrl-c-ret
  8161. org-ctrl-c-minus
  8162. org-ctrl-c-star
  8163. org-cycle
  8164. org-force-cycle-archived
  8165. org-forward-heading-same-level
  8166. org-insert-heading
  8167. org-insert-heading-respect-content
  8168. org-kill-note-or-show-branches
  8169. org-mark-subtree
  8170. org-meta-return
  8171. org-metadown
  8172. org-metaup
  8173. org-narrow-to-subtree
  8174. org-promote-subtree
  8175. org-reveal
  8176. org-shiftdown
  8177. org-shiftleft
  8178. org-shiftmetadown
  8179. org-shiftmetaup
  8180. org-shiftright
  8181. org-shifttab
  8182. org-shifttab
  8183. org-shiftup
  8184. org-show-children
  8185. org-show-subtree
  8186. org-sort
  8187. org-up-element
  8188. outline-demote
  8189. outline-next-visible-heading
  8190. outline-previous-visible-heading
  8191. outline-promote
  8192. outline-up-heading))
  8193. (let ((f (or (car-safe cell) cell))
  8194. (disable-when-heading-prefix (cdr-safe cell)))
  8195. (when (fboundp f)
  8196. (let ((new-bindings))
  8197. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8198. (where-is-internal f outline-mode-map)))
  8199. (push binding new-bindings)
  8200. ;; TODO use local-function-key-map
  8201. (dolist (rep '(("<tab>" . "TAB")
  8202. ("<return>" . "RET")
  8203. ("<escape>" . "ESC")
  8204. ("<delete>" . "DEL")))
  8205. (setq binding (read-kbd-macro
  8206. (let ((case-fold-search))
  8207. (replace-regexp-in-string
  8208. (regexp-quote (cdr rep))
  8209. (car rep)
  8210. (key-description binding)))))
  8211. (cl-pushnew binding new-bindings :test 'equal)))
  8212. (dolist (binding new-bindings)
  8213. (let ((key (lookup-key orgstruct-mode-map binding)))
  8214. (when (or (not key) (numberp key))
  8215. (ignore-errors
  8216. (org-defkey orgstruct-mode-map
  8217. binding
  8218. (orgstruct-make-binding
  8219. f binding disable-when-heading-prefix))))))))))
  8220. (run-hooks 'orgstruct-setup-hook))
  8221. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8222. "Create a function for binding in the structure minor mode.
  8223. FUN is the command to call inside a table. KEY is the key that
  8224. should be checked in for a command to execute outside of tables.
  8225. Non-nil `disable-when-heading-prefix' means to disable the command
  8226. if `orgstruct-heading-prefix-regexp' is not empty."
  8227. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8228. (let ((nname name)
  8229. (i 0))
  8230. (while (fboundp (intern nname))
  8231. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8232. (setq name (intern nname)))
  8233. (eval
  8234. (let ((bindings '((org-heading-regexp
  8235. (concat "^"
  8236. orgstruct-heading-prefix-regexp
  8237. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8238. (org-outline-regexp
  8239. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8240. (org-outline-regexp-bol
  8241. (concat "^" org-outline-regexp))
  8242. (outline-regexp org-outline-regexp)
  8243. (outline-heading-end-regexp "\n")
  8244. (outline-level 'org-outline-level)
  8245. (outline-heading-alist))))
  8246. `(defun ,name (arg)
  8247. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8248. "Outside of structure, run the binding of `"
  8249. (key-description key) "'."
  8250. (when disable-when-heading-prefix
  8251. (concat
  8252. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8253. "back to the default binding due to limitations of Org's implementation of\n"
  8254. "`" (symbol-name fun) "'.")))
  8255. (interactive "p")
  8256. (let* ((disable
  8257. ,(and disable-when-heading-prefix
  8258. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8259. (fallback
  8260. (or disable
  8261. (not
  8262. (let* ,bindings
  8263. (org-context-p 'headline 'item
  8264. ,(when (memq fun
  8265. '(org-insert-heading
  8266. org-insert-heading-respect-content
  8267. org-meta-return))
  8268. '(when orgstruct-is-++
  8269. 'item-body))))))))
  8270. (if fallback
  8271. (let* ((orgstruct-mode)
  8272. (binding
  8273. (let ((key ,key))
  8274. (catch 'exit
  8275. (dolist
  8276. (rep
  8277. '(nil
  8278. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8279. ("<\\([^>]*\\)return>" . "\\1RET")
  8280. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8281. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8282. nil)
  8283. (when rep
  8284. (setq key (read-kbd-macro
  8285. (let ((case-fold-search))
  8286. (replace-regexp-in-string
  8287. (car rep)
  8288. (cdr rep)
  8289. (key-description key))))))
  8290. (when (key-binding key)
  8291. (throw 'exit (key-binding key))))))))
  8292. (if (keymapp binding)
  8293. (org-set-transient-map binding)
  8294. (let ((func (or binding
  8295. (unless disable
  8296. 'orgstruct-error))))
  8297. (when func
  8298. (call-interactively func)))))
  8299. (org-run-like-in-org-mode
  8300. (lambda ()
  8301. (interactive)
  8302. (let* ,bindings
  8303. (call-interactively ',fun)))))))))
  8304. name))
  8305. (defun org-contextualize-keys (alist contexts)
  8306. "Return valid elements in ALIST depending on CONTEXTS.
  8307. `org-agenda-custom-commands' or `org-capture-templates' are the
  8308. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8309. or `org-capture-templates-contexts' are the associated contexts
  8310. definitions."
  8311. (let ((contexts
  8312. ;; normalize contexts
  8313. (mapcar
  8314. (lambda(c) (cond ((listp (cadr c))
  8315. (list (car c) (car c) (nth 1 c)))
  8316. ((string= "" (cadr c))
  8317. (list (car c) (car c) (nth 2 c)))
  8318. (t c)))
  8319. contexts))
  8320. (a alist) r s)
  8321. ;; loop over all commands or templates
  8322. (dolist (c a)
  8323. (let (vrules repl)
  8324. (cond
  8325. ((not (assoc (car c) contexts))
  8326. (push c r))
  8327. ((and (assoc (car c) contexts)
  8328. (setq vrules (org-contextualize-validate-key
  8329. (car c) contexts)))
  8330. (mapc (lambda (vr)
  8331. (unless (equal (car vr) (cadr vr))
  8332. (setq repl vr)))
  8333. vrules)
  8334. (if (not repl) (push c r)
  8335. (push (cadr repl) s)
  8336. (push
  8337. (cons (car c)
  8338. (cdr (or (assoc (cadr repl) alist)
  8339. (error "Undefined key `%s' as contextual replacement for `%s'"
  8340. (cadr repl) (car c)))))
  8341. r))))))
  8342. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8343. (delq
  8344. nil
  8345. (delete-dups
  8346. (mapcar (lambda (x)
  8347. (let ((tpl (car x)))
  8348. (unless (delq
  8349. nil
  8350. (mapcar (lambda (y)
  8351. (equal y tpl))
  8352. s))
  8353. x)))
  8354. (reverse r))))))
  8355. (defun org-contextualize-validate-key (key contexts)
  8356. "Check CONTEXTS for agenda or capture KEY."
  8357. (let (res)
  8358. (dolist (r contexts)
  8359. (dolist (rr (car (last r)))
  8360. (when
  8361. (and (equal key (car r))
  8362. (if (functionp rr) (funcall rr)
  8363. (or (and (eq (car rr) 'in-file)
  8364. (buffer-file-name)
  8365. (string-match (cdr rr) (buffer-file-name)))
  8366. (and (eq (car rr) 'in-mode)
  8367. (string-match (cdr rr) (symbol-name major-mode)))
  8368. (and (eq (car rr) 'in-buffer)
  8369. (string-match (cdr rr) (buffer-name)))
  8370. (when (and (eq (car rr) 'not-in-file)
  8371. (buffer-file-name))
  8372. (not (string-match (cdr rr) (buffer-file-name))))
  8373. (when (eq (car rr) 'not-in-mode)
  8374. (not (string-match (cdr rr) (symbol-name major-mode))))
  8375. (when (eq (car rr) 'not-in-buffer)
  8376. (not (string-match (cdr rr) (buffer-name)))))))
  8377. (push r res))))
  8378. (delete-dups (delq nil res))))
  8379. (defun org-context-p (&rest contexts)
  8380. "Check if local context is any of CONTEXTS.
  8381. Possible values in the list of contexts are `table', `headline', and `item'."
  8382. (let ((pos (point)))
  8383. (goto-char (point-at-bol))
  8384. (prog1 (or (and (memq 'table contexts)
  8385. (looking-at "[ \t]*|"))
  8386. (and (memq 'headline contexts)
  8387. (looking-at org-outline-regexp))
  8388. (and (memq 'item contexts)
  8389. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8390. (and (memq 'item-body contexts)
  8391. (org-in-item-p)))
  8392. (goto-char pos))))
  8393. ;;;###autoload
  8394. (defun org-run-like-in-org-mode (cmd)
  8395. "Run a command, pretending that the current buffer is in Org mode.
  8396. This will temporarily bind local variables that are typically bound in
  8397. Org mode to the values they have in Org mode, and then interactively
  8398. call CMD."
  8399. (org-load-modules-maybe)
  8400. (unless org-local-vars
  8401. (setq org-local-vars (org-get-local-variables)))
  8402. (let (binds)
  8403. (dolist (var org-local-vars)
  8404. (when (or (not (boundp (car var)))
  8405. (eq (symbol-value (car var))
  8406. (default-value (car var))))
  8407. (push (list (car var) `(quote ,(cadr var))) binds)))
  8408. (eval `(let ,binds
  8409. (call-interactively (quote ,cmd))))))
  8410. (defun org-get-category (&optional pos force-refresh)
  8411. "Get the category applying to position POS."
  8412. (save-match-data
  8413. (when force-refresh (org-refresh-category-properties))
  8414. (let ((pos (or pos (point))))
  8415. (or (get-text-property pos 'org-category)
  8416. (progn (org-refresh-category-properties)
  8417. (get-text-property pos 'org-category))))))
  8418. ;;; Refresh properties
  8419. (defun org-refresh-properties (dprop tprop)
  8420. "Refresh buffer text properties.
  8421. DPROP is the drawer property and TPROP is either the
  8422. corresponding text property to set, or an alist with each element
  8423. being a text property (as a symbol) and a function to apply to
  8424. the value of the drawer property."
  8425. (let* ((case-fold-search t)
  8426. (inhibit-read-only t)
  8427. (inherit? (org-property-inherit-p dprop))
  8428. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8429. (global (and inherit? (org--property-global-value dprop nil))))
  8430. (org-with-silent-modifications
  8431. (org-with-point-at 1
  8432. ;; Set global values (e.g., values defined through
  8433. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8434. (when global (put-text-property (point-min) (point-max) tprop global))
  8435. ;; Set local values.
  8436. (while (re-search-forward property-re nil t)
  8437. (when (org-at-property-p)
  8438. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8439. (outline-next-heading))))))
  8440. (defun org-refresh-property (tprop p &optional inherit)
  8441. "Refresh the buffer text property TPROP from the drawer property P.
  8442. The refresh happens only for the current headline, or the whole
  8443. sub-tree if optional argument INHERIT is non-nil."
  8444. (unless (org-before-first-heading-p)
  8445. (save-excursion
  8446. (org-back-to-heading t)
  8447. (let ((start (point))
  8448. (end (save-excursion
  8449. (if inherit (org-end-of-subtree t t)
  8450. (or (outline-next-heading) (point-max))))))
  8451. (if (symbolp tprop)
  8452. ;; TPROP is a text property symbol.
  8453. (put-text-property start end tprop p)
  8454. ;; TPROP is an alist with (property . function) elements.
  8455. (pcase-dolist (`(,prop . ,f) tprop)
  8456. (put-text-property start end prop (funcall f p))))))))
  8457. (defun org-refresh-category-properties ()
  8458. "Refresh category text properties in the buffer."
  8459. (let ((case-fold-search t)
  8460. (inhibit-read-only t)
  8461. (default-category
  8462. (cond ((null org-category)
  8463. (if buffer-file-name
  8464. (file-name-sans-extension
  8465. (file-name-nondirectory buffer-file-name))
  8466. "???"))
  8467. ((symbolp org-category) (symbol-name org-category))
  8468. (t org-category))))
  8469. (org-with-silent-modifications
  8470. (org-with-wide-buffer
  8471. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8472. ;; This is the default category for the buffer. If none is
  8473. ;; found, fall-back to `org-category' or buffer file name.
  8474. (put-text-property
  8475. (point-min) (point-max)
  8476. 'org-category
  8477. (catch 'buffer-category
  8478. (goto-char (point-max))
  8479. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8480. (let ((element (org-element-at-point)))
  8481. (when (eq (org-element-type element) 'keyword)
  8482. (throw 'buffer-category
  8483. (org-element-property :value element)))))
  8484. default-category))
  8485. ;; Set sub-tree specific categories.
  8486. (goto-char (point-min))
  8487. (let ((regexp (org-re-property "CATEGORY")))
  8488. (while (re-search-forward regexp nil t)
  8489. (let ((value (match-string-no-properties 3)))
  8490. (when (org-at-property-p)
  8491. (put-text-property
  8492. (save-excursion (org-back-to-heading t) (point))
  8493. (save-excursion (org-end-of-subtree t t) (point))
  8494. 'org-category
  8495. value)))))))))
  8496. (defun org-refresh-stats-properties ()
  8497. "Refresh stats text properties in the buffer."
  8498. (org-with-silent-modifications
  8499. (org-with-point-at 1
  8500. (let ((regexp (concat org-outline-regexp-bol
  8501. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8502. (while (re-search-forward regexp nil t)
  8503. (let* ((numerator (string-to-number (match-string 1)))
  8504. (denominator (and (match-end 2)
  8505. (string-to-number (match-string 2))))
  8506. (stats (cond ((not denominator) numerator) ;percent
  8507. ((= denominator 0) 0)
  8508. (t (/ (* numerator 100) denominator)))))
  8509. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8510. 'org-stats stats)))))))
  8511. (defun org-refresh-effort-properties ()
  8512. "Refresh effort properties"
  8513. (org-refresh-properties
  8514. org-effort-property
  8515. '((effort . identity)
  8516. (effort-minutes . org-duration-to-minutes))))
  8517. ;;;; Link Stuff
  8518. ;;; Link abbreviations
  8519. (defun org-link-expand-abbrev (link)
  8520. "Apply replacements as defined in `org-link-abbrev-alist'."
  8521. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8522. (let* ((key (match-string 1 link))
  8523. (as (or (assoc key org-link-abbrev-alist-local)
  8524. (assoc key org-link-abbrev-alist)))
  8525. (tag (and (match-end 2) (match-string 3 link)))
  8526. rpl)
  8527. (if (not as)
  8528. link
  8529. (setq rpl (cdr as))
  8530. (cond
  8531. ((symbolp rpl) (funcall rpl tag))
  8532. ((string-match "%(\\([^)]+\\))" rpl)
  8533. (replace-match
  8534. (save-match-data
  8535. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8536. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8537. ((string-match "%h" rpl)
  8538. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8539. (t (concat rpl tag)))))
  8540. link))
  8541. ;;; Storing and inserting links
  8542. (defvar org-insert-link-history nil
  8543. "Minibuffer history for links inserted with `org-insert-link'.")
  8544. (defvar org-stored-links nil
  8545. "Contains the links stored with `org-store-link'.")
  8546. (defvar org-store-link-plist nil
  8547. "Plist with info about the most recently link created with `org-store-link'.")
  8548. (defun org-store-link-functions ()
  8549. "Return a list of functions that are called to create and store a link.
  8550. The functions defined in the :store property of
  8551. `org-link-parameters'.
  8552. Each function will be called in turn until one returns a non-nil
  8553. value. Each function should check if it is responsible for
  8554. creating this link (for example by looking at the major mode).
  8555. If not, it must exit and return nil. If yes, it should return
  8556. a non-nil value after calling `org-store-link-props' with a list
  8557. of properties and values. Special properties are:
  8558. :type The link prefix, like \"http\". This must be given.
  8559. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8560. This is obligatory as well.
  8561. :description Optional default description for the second pair
  8562. of brackets in an Org mode link. The user can still change
  8563. this when inserting this link into an Org mode buffer.
  8564. In addition to these, any additional properties can be specified
  8565. and then used in capture templates."
  8566. (cl-loop for link in org-link-parameters
  8567. with store-func
  8568. do (setq store-func (org-link-get-parameter (car link) :store))
  8569. if store-func
  8570. collect store-func))
  8571. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8572. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8573. ;;;###autoload
  8574. (defun org-store-link (arg)
  8575. "Store an org-link to the current location.
  8576. \\<org-mode-map>
  8577. This link is added to `org-stored-links' and can later be inserted
  8578. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8579. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8580. A single
  8581. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8582. `org-gnus-prefer-web-links' for links to Usenet articles.
  8583. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8584. skipping storing functions that are not
  8585. part of Org core.
  8586. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8587. prefix ARG forces storing a link for each line in the
  8588. active region."
  8589. (interactive "P")
  8590. (org-load-modules-maybe)
  8591. (if (and (equal arg '(64)) (org-region-active-p))
  8592. (save-excursion
  8593. (let ((end (region-end)))
  8594. (goto-char (region-beginning))
  8595. (set-mark (point))
  8596. (while (< (point-at-eol) end)
  8597. (move-end-of-line 1) (activate-mark)
  8598. (let (current-prefix-arg)
  8599. (call-interactively 'org-store-link))
  8600. (move-beginning-of-line 2)
  8601. (set-mark (point)))))
  8602. (setq org-store-link-plist nil)
  8603. (let (link cpltxt desc description search
  8604. txt custom-id agenda-link sfuns sfunsn)
  8605. (cond
  8606. ;; Store a link using an external link type
  8607. ((and (not (equal arg '(16)))
  8608. (setq sfuns
  8609. (delq
  8610. nil (mapcar (lambda (f)
  8611. (let (fs) (if (funcall f) (push f fs))))
  8612. (org-store-link-functions)))
  8613. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8614. (or (and (cdr sfuns)
  8615. (funcall (intern
  8616. (completing-read
  8617. "Which function for creating the link? "
  8618. sfunsn nil t (car sfunsn)))))
  8619. (funcall (caar sfuns)))
  8620. (setq link (plist-get org-store-link-plist :link)
  8621. desc (or (plist-get org-store-link-plist
  8622. :description)
  8623. link))))
  8624. ;; Store a link from a source code buffer.
  8625. ((org-src-edit-buffer-p)
  8626. (let ((coderef-format (org-src-coderef-format)))
  8627. (cond ((save-excursion
  8628. (beginning-of-line)
  8629. (looking-at (org-src-coderef-regexp coderef-format)))
  8630. (setq link (format "(%s)" (match-string-no-properties 3))))
  8631. ((called-interactively-p 'any)
  8632. (let ((label (read-string "Code line label: ")))
  8633. (end-of-line)
  8634. (setq link (format coderef-format label))
  8635. (let ((gc (- 79 (length link))))
  8636. (if (< (current-column) gc)
  8637. (org-move-to-column gc t)
  8638. (insert " ")))
  8639. (insert link)
  8640. (setq link (concat "(" label ")"))
  8641. (setq desc nil)))
  8642. (t (setq link nil)))))
  8643. ;; We are in the agenda, link to referenced location
  8644. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8645. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8646. (get-text-property (point) 'org-marker))))
  8647. (when m
  8648. (org-with-point-at m
  8649. (setq agenda-link
  8650. (if (called-interactively-p 'any)
  8651. (call-interactively 'org-store-link)
  8652. (org-store-link nil)))))))
  8653. ((eq major-mode 'calendar-mode)
  8654. (let ((cd (calendar-cursor-to-date)))
  8655. (setq link
  8656. (format-time-string
  8657. (car org-time-stamp-formats)
  8658. (apply 'encode-time
  8659. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8660. nil nil nil))))
  8661. (org-store-link-props :type "calendar" :date cd)))
  8662. ((eq major-mode 'help-mode)
  8663. (setq link (concat "help:" (save-excursion
  8664. (goto-char (point-min))
  8665. (looking-at "^[^ ]+")
  8666. (match-string 0))))
  8667. (org-store-link-props :type "help"))
  8668. ((eq major-mode 'w3-mode)
  8669. (setq cpltxt (if (and (buffer-name)
  8670. (not (string-match "Untitled" (buffer-name))))
  8671. (buffer-name)
  8672. (url-view-url t))
  8673. link (url-view-url t))
  8674. (org-store-link-props :type "w3" :url (url-view-url t)))
  8675. ((eq major-mode 'image-mode)
  8676. (setq cpltxt (concat "file:"
  8677. (abbreviate-file-name buffer-file-name))
  8678. link cpltxt)
  8679. (org-store-link-props :type "image" :file buffer-file-name))
  8680. ;; In dired, store a link to the file of the current line
  8681. ((derived-mode-p 'dired-mode)
  8682. (let ((file (dired-get-filename nil t)))
  8683. (setq file (if file
  8684. (abbreviate-file-name
  8685. (expand-file-name (dired-get-filename nil t)))
  8686. ;; otherwise, no file so use current directory.
  8687. default-directory))
  8688. (setq cpltxt (concat "file:" file)
  8689. link cpltxt)))
  8690. ((setq search (run-hook-with-args-until-success
  8691. 'org-create-file-search-functions))
  8692. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8693. "::" search))
  8694. (setq cpltxt (or description link)))
  8695. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8696. (org-with-limited-levels
  8697. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8698. (cond
  8699. ;; Store a link using the target at point
  8700. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8701. (setq cpltxt
  8702. (concat "file:"
  8703. (abbreviate-file-name
  8704. (buffer-file-name (buffer-base-buffer)))
  8705. "::" (match-string 1))
  8706. link cpltxt))
  8707. ((and (featurep 'org-id)
  8708. (or (eq org-id-link-to-org-use-id t)
  8709. (and (called-interactively-p 'any)
  8710. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8711. (and (eq org-id-link-to-org-use-id
  8712. 'create-if-interactive-and-no-custom-id)
  8713. (not custom-id))))
  8714. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8715. ;; Store a link using the ID at point
  8716. (setq link (condition-case nil
  8717. (prog1 (org-id-store-link)
  8718. (setq desc (or (plist-get org-store-link-plist
  8719. :description)
  8720. "")))
  8721. (error
  8722. ;; Probably before first headline, link only to file
  8723. (concat "file:"
  8724. (abbreviate-file-name
  8725. (buffer-file-name (buffer-base-buffer))))))))
  8726. (t
  8727. ;; Just link to current headline
  8728. (setq cpltxt (concat "file:"
  8729. (abbreviate-file-name
  8730. (buffer-file-name (buffer-base-buffer)))))
  8731. ;; Add a context search string
  8732. (when (org-xor org-context-in-file-links
  8733. (equal arg '(4)))
  8734. (let* ((element (org-element-at-point))
  8735. (name (org-element-property :name element)))
  8736. (setq txt (cond
  8737. ((org-at-heading-p) nil)
  8738. (name)
  8739. ((org-region-active-p)
  8740. (buffer-substring (region-beginning) (region-end)))))
  8741. (when (or (null txt) (string-match "\\S-" txt))
  8742. (setq cpltxt
  8743. (concat cpltxt "::"
  8744. (condition-case nil
  8745. (org-make-org-heading-search-string txt)
  8746. (error "")))
  8747. desc (or name
  8748. (nth 4 (ignore-errors (org-heading-components)))
  8749. "NONE")))))
  8750. (when (string-match "::\\'" cpltxt)
  8751. (setq cpltxt (substring cpltxt 0 -2)))
  8752. (setq link cpltxt)))))
  8753. ((buffer-file-name (buffer-base-buffer))
  8754. ;; Just link to this file here.
  8755. (setq cpltxt (concat "file:"
  8756. (abbreviate-file-name
  8757. (buffer-file-name (buffer-base-buffer)))))
  8758. ;; Add a context string.
  8759. (when (org-xor org-context-in-file-links
  8760. (equal arg '(4)))
  8761. (setq txt (if (org-region-active-p)
  8762. (buffer-substring (region-beginning) (region-end))
  8763. (buffer-substring (point-at-bol) (point-at-eol))))
  8764. ;; Only use search option if there is some text.
  8765. (when (string-match "\\S-" txt)
  8766. (setq cpltxt
  8767. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8768. desc "NONE")))
  8769. (setq link cpltxt))
  8770. ((called-interactively-p 'interactive)
  8771. (user-error "No method for storing a link from this buffer"))
  8772. (t (setq link nil)))
  8773. ;; We're done setting link and desc, clean up
  8774. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8775. (setq link (or link cpltxt)
  8776. desc (or desc cpltxt))
  8777. (cond ((not desc))
  8778. ((equal desc "NONE") (setq desc nil))
  8779. (t (setq desc
  8780. (replace-regexp-in-string
  8781. org-bracket-link-analytic-regexp
  8782. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8783. desc))))
  8784. ;; Return the link
  8785. (if (not (and (or (called-interactively-p 'any)
  8786. executing-kbd-macro)
  8787. link))
  8788. (or agenda-link (and link (org-make-link-string link desc)))
  8789. (push (list link desc) org-stored-links)
  8790. (message "Stored: %s" (or desc link))
  8791. (when custom-id
  8792. (setq link (concat "file:" (abbreviate-file-name
  8793. (buffer-file-name)) "::#" custom-id))
  8794. (push (list link desc) org-stored-links))
  8795. (car org-stored-links)))))
  8796. (defun org-store-link-props (&rest plist)
  8797. "Store link properties, extract names, addresses and dates."
  8798. (let ((x (plist-get plist :from)))
  8799. (when x
  8800. (let ((adr (mail-extract-address-components x)))
  8801. (setq plist (plist-put plist :fromname (car adr)))
  8802. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8803. (let ((x (plist-get plist :to)))
  8804. (when x
  8805. (let ((adr (mail-extract-address-components x)))
  8806. (setq plist (plist-put plist :toname (car adr)))
  8807. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8808. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8809. (when x
  8810. (setq plist (plist-put plist :date-timestamp
  8811. (format-time-string
  8812. (org-time-stamp-format t) x)))
  8813. (setq plist (plist-put plist :date-timestamp-inactive
  8814. (format-time-string
  8815. (org-time-stamp-format t t) x)))))
  8816. (let ((from (plist-get plist :from))
  8817. (to (plist-get plist :to)))
  8818. (when (and from to org-from-is-user-regexp)
  8819. (setq plist
  8820. (plist-put plist :fromto
  8821. (if (string-match org-from-is-user-regexp from)
  8822. (concat "to %t")
  8823. (concat "from %f"))))))
  8824. (setq org-store-link-plist plist))
  8825. (defun org-add-link-props (&rest plist)
  8826. "Add these properties to the link property list."
  8827. (let (key value)
  8828. (while plist
  8829. (setq key (pop plist) value (pop plist))
  8830. (setq org-store-link-plist
  8831. (plist-put org-store-link-plist key value)))))
  8832. (defun org-email-link-description (&optional fmt)
  8833. "Return the description part of an email link.
  8834. This takes information from `org-store-link-plist' and formats it
  8835. according to FMT (default from `org-email-link-description-format')."
  8836. (setq fmt (or fmt org-email-link-description-format))
  8837. (let* ((p org-store-link-plist)
  8838. (to (plist-get p :toaddress))
  8839. (from (plist-get p :fromaddress))
  8840. (table
  8841. (list
  8842. (cons "%c" (plist-get p :fromto))
  8843. (cons "%F" (plist-get p :from))
  8844. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8845. (cons "%T" (plist-get p :to))
  8846. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8847. (cons "%s" (plist-get p :subject))
  8848. (cons "%d" (plist-get p :date))
  8849. (cons "%m" (plist-get p :message-id)))))
  8850. (when (string-match "%c" fmt)
  8851. ;; Check if the user wrote this message
  8852. (if (and org-from-is-user-regexp from to
  8853. (save-match-data (string-match org-from-is-user-regexp from)))
  8854. (setq fmt (replace-match "to %t" t t fmt))
  8855. (setq fmt (replace-match "from %f" t t fmt))))
  8856. (org-replace-escapes fmt table)))
  8857. (defun org-make-org-heading-search-string (&optional string)
  8858. "Make search string for the current headline or STRING."
  8859. (let ((s (or string
  8860. (and (derived-mode-p 'org-mode)
  8861. (save-excursion
  8862. (org-back-to-heading t)
  8863. (org-element-property :raw-value (org-element-at-point))))))
  8864. (lines org-context-in-file-links))
  8865. (unless string (setq s (concat "*" s))) ;Add * for headlines
  8866. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8867. (when (and string (integerp lines) (> lines 0))
  8868. (let ((slines (org-split-string s "\n")))
  8869. (when (< lines (length slines))
  8870. (setq s (mapconcat
  8871. 'identity
  8872. (reverse (nthcdr (- (length slines) lines)
  8873. (reverse slines))) "\n")))))
  8874. (mapconcat #'identity (split-string s) " ")))
  8875. (defun org-make-link-string (link &optional description)
  8876. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8877. (unless (org-string-nw-p link) (error "Empty link"))
  8878. (let ((uri (cond ((string-match org-link-types-re link)
  8879. (concat (match-string 1 link)
  8880. (org-link-escape (substring link (match-end 1)))))
  8881. ;; For readability, url-encode internal links only
  8882. ;; when absolutely needed (i.e, when they contain
  8883. ;; square brackets). File links however, are
  8884. ;; encoded since, e.g., spaces are significant.
  8885. ((or (file-name-absolute-p link)
  8886. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8887. (org-link-escape link))
  8888. (t link)))
  8889. (description
  8890. (and (org-string-nw-p description)
  8891. ;; Remove brackets from description, as they are fatal.
  8892. (replace-regexp-in-string
  8893. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8894. (org-trim description)))))
  8895. (format "[[%s]%s]"
  8896. uri
  8897. (if description (format "[%s]" description) ""))))
  8898. (defconst org-link-escape-chars
  8899. ;;%20 %5B %5D %25
  8900. '(?\s ?\[ ?\] ?%)
  8901. "List of characters that should be escaped in a link when stored to Org.
  8902. This is the list that is used for internal purposes.")
  8903. (defun org-link-escape (text &optional table merge)
  8904. "Return percent escaped representation of TEXT.
  8905. TEXT is a string with the text to escape.
  8906. Optional argument TABLE is a list with characters that should be
  8907. escaped. When nil, `org-link-escape-chars' is used.
  8908. If optional argument MERGE is set, merge TABLE into
  8909. `org-link-escape-chars'."
  8910. (let ((characters-to-encode
  8911. (cond ((null table) org-link-escape-chars)
  8912. (merge (append org-link-escape-chars table))
  8913. (t table))))
  8914. (mapconcat
  8915. (lambda (c)
  8916. (if (or (memq c characters-to-encode)
  8917. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8918. (mapconcat (lambda (e) (format "%%%.2X" e))
  8919. (or (encode-coding-char c 'utf-8)
  8920. (error "Unable to percent escape character: %c" c))
  8921. "")
  8922. (char-to-string c)))
  8923. text "")))
  8924. (defun org-link-unescape (str)
  8925. "Unhex hexified Unicode parts in string STR.
  8926. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8927. reciprocal of `org-link-escape', which see."
  8928. (if (org-string-nw-p str)
  8929. (replace-regexp-in-string
  8930. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8931. str))
  8932. (defun org-link-unescape-compound (hex)
  8933. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8934. Note: this function also decodes single byte encodings like
  8935. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8936. (save-match-data
  8937. (let* ((bytes (cdr (split-string hex "%")))
  8938. (ret "")
  8939. (eat 0)
  8940. (sum 0))
  8941. (while bytes
  8942. (let* ((val (string-to-number (pop bytes) 16))
  8943. (shift-xor
  8944. (if (= 0 eat)
  8945. (cond
  8946. ((>= val 252) (cons 6 252))
  8947. ((>= val 248) (cons 5 248))
  8948. ((>= val 240) (cons 4 240))
  8949. ((>= val 224) (cons 3 224))
  8950. ((>= val 192) (cons 2 192))
  8951. (t (cons 0 0)))
  8952. (cons 6 128))))
  8953. (when (>= val 192) (setq eat (car shift-xor)))
  8954. (setq val (logxor val (cdr shift-xor)))
  8955. (setq sum (+ (lsh sum (car shift-xor)) val))
  8956. (when (> eat 0) (setq eat (- eat 1)))
  8957. (cond
  8958. ((= 0 eat) ;multi byte
  8959. (setq ret (concat ret (char-to-string sum)))
  8960. (setq sum 0))
  8961. ((not bytes) ; single byte(s)
  8962. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8963. ret)))
  8964. (defun org-link-unescape-single-byte-sequence (hex)
  8965. "Unhexify hex-encoded single byte character sequences."
  8966. (mapconcat (lambda (byte)
  8967. (char-to-string (string-to-number byte 16)))
  8968. (cdr (split-string hex "%")) ""))
  8969. (defun org-xor (a b)
  8970. "Exclusive or."
  8971. (if a (not b) b))
  8972. (defun org-fixup-message-id-for-http (s)
  8973. "Replace special characters in a message id, so it can be used in an http query."
  8974. (when (string-match "%" s)
  8975. (setq s (mapconcat (lambda (c)
  8976. (if (eq c ?%)
  8977. "%25"
  8978. (char-to-string c)))
  8979. s "")))
  8980. (while (string-match "<" s)
  8981. (setq s (replace-match "%3C" t t s)))
  8982. (while (string-match ">" s)
  8983. (setq s (replace-match "%3E" t t s)))
  8984. (while (string-match "@" s)
  8985. (setq s (replace-match "%40" t t s)))
  8986. s)
  8987. (defun org-link-prettify (link)
  8988. "Return a human-readable representation of LINK.
  8989. The car of LINK must be a raw link.
  8990. The cdr of LINK must be either a link description or nil."
  8991. (let ((desc (or (cadr link) "<no description>")))
  8992. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  8993. "<" (car link) ">")))
  8994. ;;;###autoload
  8995. (defun org-insert-link-global ()
  8996. "Insert a link like Org mode does.
  8997. This command can be called in any mode to insert a link in Org syntax."
  8998. (interactive)
  8999. (org-load-modules-maybe)
  9000. (org-run-like-in-org-mode 'org-insert-link))
  9001. (defun org-insert-all-links (arg &optional pre post)
  9002. "Insert all links in `org-stored-links'.
  9003. When a universal prefix, do not delete the links from `org-stored-links'.
  9004. When `ARG' is a number, insert the last N link(s).
  9005. `PRE' and `POST' are optional arguments to define a string to
  9006. prepend or to append."
  9007. (interactive "P")
  9008. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9009. (links (copy-sequence org-stored-links))
  9010. (pr (or pre "- "))
  9011. (po (or post "\n"))
  9012. (cnt 1) l)
  9013. (if (null org-stored-links)
  9014. (message "No link to insert")
  9015. (while (and (or (listp arg) (>= arg cnt))
  9016. (setq l (if (listp arg)
  9017. (pop links)
  9018. (pop org-stored-links))))
  9019. (setq cnt (1+ cnt))
  9020. (insert pr)
  9021. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9022. (insert po)))))
  9023. (defun org-insert-last-stored-link (arg)
  9024. "Insert the last link stored in `org-stored-links'."
  9025. (interactive "p")
  9026. (org-insert-all-links arg "" "\n"))
  9027. (defun org-link-fontify-links-to-this-file ()
  9028. "Fontify links to the current file in `org-stored-links'."
  9029. (let ((f (buffer-file-name)) a b)
  9030. (setq a (mapcar (lambda(l)
  9031. (let ((ll (car l)))
  9032. (when (and (string-match "^file:\\(.+\\)::" ll)
  9033. (equal f (expand-file-name (match-string 1 ll))))
  9034. ll)))
  9035. org-stored-links))
  9036. (when (featurep 'org-id)
  9037. (setq b (mapcar (lambda(l)
  9038. (let ((ll (car l)))
  9039. (when (and (string-match "^id:\\(.+\\)$" ll)
  9040. (equal f (expand-file-name
  9041. (or (org-id-find-id-file
  9042. (match-string 1 ll)) ""))))
  9043. ll)))
  9044. org-stored-links)))
  9045. (mapcar (lambda(l)
  9046. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9047. (delq nil (append a b)))))
  9048. (defvar org--links-history nil)
  9049. (defun org-insert-link (&optional complete-file link-location default-description)
  9050. "Insert a link. At the prompt, enter the link.
  9051. Completion can be used to insert any of the link protocol prefixes in use.
  9052. The history can be used to select a link previously stored with
  9053. `org-store-link'. When the empty string is entered (i.e. if you just
  9054. press `RET' at the prompt), the link defaults to the most recently
  9055. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9056. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9057. You will also be prompted for a description, and if one is given, it will
  9058. be displayed in the buffer instead of the link.
  9059. If there is already a link at point, this command will allow you to edit
  9060. link and description parts.
  9061. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9062. file name can be
  9063. selected using completion. The path to the file will be relative to the
  9064. current directory if the file is in the current directory or a subdirectory.
  9065. Otherwise, the link will be the absolute path as completed in the minibuffer
  9066. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9067. option `org-link-file-path-type'.
  9068. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9069. absolute path even if the file is in
  9070. the current directory or below.
  9071. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9072. prefix negates `org-keep-stored-link-after-insertion'.
  9073. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9074. the link location instead of reading one interactively.
  9075. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9076. be used as the default description. Otherwise, if
  9077. `org-make-link-description-function' is non-nil, this function
  9078. will be called with the link target, and the result will be the
  9079. default link description."
  9080. (interactive "P")
  9081. (let* ((wcf (current-window-configuration))
  9082. (origbuf (current-buffer))
  9083. (region (when (org-region-active-p)
  9084. (buffer-substring (region-beginning) (region-end))))
  9085. (remove (and region (list (region-beginning) (region-end))))
  9086. (desc region)
  9087. (link link-location)
  9088. (abbrevs org-link-abbrev-alist-local)
  9089. entry all-prefixes auto-desc)
  9090. (cond
  9091. (link-location) ; specified by arg, just use it.
  9092. ((org-in-regexp org-bracket-link-regexp 1)
  9093. ;; We do have a link at point, and we are going to edit it.
  9094. (setq remove (list (match-beginning 0) (match-end 0)))
  9095. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9096. (setq link (read-string "Link: "
  9097. (org-link-unescape
  9098. (match-string-no-properties 1)))))
  9099. ((or (org-in-regexp org-angle-link-re)
  9100. (org-in-regexp org-plain-link-re))
  9101. ;; Convert to bracket link
  9102. (setq remove (list (match-beginning 0) (match-end 0))
  9103. link (read-string "Link: "
  9104. (org-unbracket-string "<" ">" (match-string 0)))))
  9105. ((member complete-file '((4) (16)))
  9106. ;; Completing read for file names.
  9107. (setq link (org-file-complete-link complete-file)))
  9108. (t
  9109. ;; Read link, with completion for stored links.
  9110. (org-link-fontify-links-to-this-file)
  9111. (org-switch-to-buffer-other-window "*Org Links*")
  9112. (with-current-buffer "*Org Links*"
  9113. (erase-buffer)
  9114. (insert "Insert a link.
  9115. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9116. (when org-stored-links
  9117. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9118. (insert (mapconcat 'org-link-prettify
  9119. (reverse org-stored-links) "\n")))
  9120. (goto-char (point-min)))
  9121. (let ((cw (selected-window)))
  9122. (select-window (get-buffer-window "*Org Links*" 'visible))
  9123. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9124. (unless (pos-visible-in-window-p (point-max))
  9125. (org-fit-window-to-buffer))
  9126. (and (window-live-p cw) (select-window cw)))
  9127. (setq all-prefixes (append (mapcar 'car abbrevs)
  9128. (mapcar 'car org-link-abbrev-alist)
  9129. (org-link-types)))
  9130. (unwind-protect
  9131. ;; Fake a link history, containing the stored links.
  9132. (let ((org--links-history
  9133. (append (mapcar #'car org-stored-links)
  9134. org-insert-link-history)))
  9135. (setq link
  9136. (org-completing-read
  9137. "Link: "
  9138. (append
  9139. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9140. (mapcar #'car org-stored-links))
  9141. nil nil nil
  9142. 'org--links-history
  9143. (caar org-stored-links)))
  9144. (unless (org-string-nw-p link) (user-error "No link selected"))
  9145. (dolist (l org-stored-links)
  9146. (when (equal link (cadr l))
  9147. (setq link (car l))
  9148. (setq auto-desc t)))
  9149. (when (or (member link all-prefixes)
  9150. (and (equal ":" (substring link -1))
  9151. (member (substring link 0 -1) all-prefixes)
  9152. (setq link (substring link 0 -1))))
  9153. (setq link (with-current-buffer origbuf
  9154. (org-link-try-special-completion link)))))
  9155. (set-window-configuration wcf)
  9156. (kill-buffer "*Org Links*"))
  9157. (setq entry (assoc link org-stored-links))
  9158. (or entry (push link org-insert-link-history))
  9159. (setq desc (or desc (nth 1 entry)))))
  9160. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9161. (not org-keep-stored-link-after-insertion))
  9162. (setq org-stored-links (delq (assoc link org-stored-links)
  9163. org-stored-links)))
  9164. (when (and (string-match org-plain-link-re link)
  9165. (not (string-match org-ts-regexp link)))
  9166. ;; URL-like link, normalize the use of angular brackets.
  9167. (setq link (org-unbracket-string "<" ">" link)))
  9168. ;; Check if we are linking to the current file with a search
  9169. ;; option If yes, simplify the link by using only the search
  9170. ;; option.
  9171. (when (and buffer-file-name
  9172. (let ((case-fold-search nil))
  9173. (string-match "\\`file:\\(.+?\\)::" link)))
  9174. (let ((path (match-string-no-properties 1 link))
  9175. (search (substring-no-properties link (match-end 0))))
  9176. (save-match-data
  9177. (when (equal (file-truename buffer-file-name) (file-truename path))
  9178. ;; We are linking to this same file, with a search option
  9179. (setq link search)))))
  9180. ;; Check if we can/should use a relative path. If yes, simplify the link
  9181. (let ((case-fold-search nil))
  9182. (when (string-match "\\`\\(file\\|docview\\):" link)
  9183. (let* ((type (match-string-no-properties 0 link))
  9184. (path (substring-no-properties link (match-end 0)))
  9185. (origpath path))
  9186. (cond
  9187. ((or (eq org-link-file-path-type 'absolute)
  9188. (equal complete-file '(16)))
  9189. (setq path (abbreviate-file-name (expand-file-name path))))
  9190. ((eq org-link-file-path-type 'noabbrev)
  9191. (setq path (expand-file-name path)))
  9192. ((eq org-link-file-path-type 'relative)
  9193. (setq path (file-relative-name path)))
  9194. (t
  9195. (save-match-data
  9196. (if (string-match (concat "^" (regexp-quote
  9197. (expand-file-name
  9198. (file-name-as-directory
  9199. default-directory))))
  9200. (expand-file-name path))
  9201. ;; We are linking a file with relative path name.
  9202. (setq path (substring (expand-file-name path)
  9203. (match-end 0)))
  9204. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9205. (setq link (concat type path))
  9206. (when (equal desc origpath)
  9207. (setq desc path)))))
  9208. (unless auto-desc
  9209. (let ((initial-input
  9210. (cond
  9211. (default-description)
  9212. ((not org-make-link-description-function) desc)
  9213. (t (condition-case nil
  9214. (funcall org-make-link-description-function link desc)
  9215. (error
  9216. (message "Can't get link description from `%s'"
  9217. (symbol-name org-make-link-description-function))
  9218. (sit-for 2)
  9219. nil))))))
  9220. (setq desc (read-string "Description: " initial-input))))
  9221. (unless (string-match "\\S-" desc) (setq desc nil))
  9222. (when remove (apply 'delete-region remove))
  9223. (insert (org-make-link-string link desc))
  9224. ;; Redisplay so as the new link has proper invisible characters.
  9225. (sit-for 0)))
  9226. (defun org-link-try-special-completion (type)
  9227. "If there is completion support for link type TYPE, offer it."
  9228. (let ((fun (org-link-get-parameter type :complete)))
  9229. (if (functionp fun)
  9230. (funcall fun)
  9231. (read-string "Link (no completion support): " (concat type ":")))))
  9232. (defun org-file-complete-link (&optional arg)
  9233. "Create a file link using completion."
  9234. (let ((file (read-file-name "File: "))
  9235. (pwd (file-name-as-directory (expand-file-name ".")))
  9236. (pwd1 (file-name-as-directory (abbreviate-file-name
  9237. (expand-file-name ".")))))
  9238. (cond ((equal arg '(16))
  9239. (concat "file:"
  9240. (abbreviate-file-name (expand-file-name file))))
  9241. ((string-match
  9242. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9243. (concat "file:" (match-string 1 file)))
  9244. ((string-match
  9245. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9246. (expand-file-name file))
  9247. (concat "file:"
  9248. (match-string 1 (expand-file-name file))))
  9249. (t (concat "file:" file)))))
  9250. (defun org-completing-read (&rest args)
  9251. "Completing-read with SPACE being a normal character."
  9252. (let ((enable-recursive-minibuffers t)
  9253. (minibuffer-local-completion-map
  9254. (copy-keymap minibuffer-local-completion-map)))
  9255. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9256. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9257. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9258. 'org-time-stamp-inactive)
  9259. (apply #'completing-read args)))
  9260. ;;; Opening/following a link
  9261. (defvar org-link-search-failed nil)
  9262. (defvar org-open-link-functions nil
  9263. "Hook for functions finding a plain text link.
  9264. These functions must take a single argument, the link content.
  9265. They will be called for links that look like [[link text][description]]
  9266. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9267. like a filename (e.g. \"./blue.png\").
  9268. These functions will be called *before* Org attempts to resolve the
  9269. link by doing text searches in the current buffer - so if you want a
  9270. link \"[[target]]\" to still find \"<<target>>\", your function should
  9271. handle this as a special case.
  9272. When the function does handle the link, it must return a non-nil value.
  9273. If it decides that it is not responsible for this link, it must return
  9274. nil to indicate that that Org can continue with other options like
  9275. exact and fuzzy text search.")
  9276. (defun org-next-link (&optional search-backward)
  9277. "Move forward to the next link.
  9278. If the link is in hidden text, expose it."
  9279. (interactive "P")
  9280. (when (and org-link-search-failed (eq this-command last-command))
  9281. (goto-char (point-min))
  9282. (message "Link search wrapped back to beginning of buffer"))
  9283. (setq org-link-search-failed nil)
  9284. (let* ((pos (point))
  9285. (ct (org-context))
  9286. (a (assq :link ct))
  9287. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9288. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9289. ((looking-at org-any-link-re)
  9290. ;; Don't stay stuck at link without an org-link face
  9291. (forward-char (if search-backward -1 1))))
  9292. (if (funcall srch-fun org-any-link-re nil t)
  9293. (progn
  9294. (goto-char (match-beginning 0))
  9295. (when (org-invisible-p) (org-show-context)))
  9296. (goto-char pos)
  9297. (setq org-link-search-failed t)
  9298. (message "No further link found"))))
  9299. (defun org-previous-link ()
  9300. "Move backward to the previous link.
  9301. If the link is in hidden text, expose it."
  9302. (interactive)
  9303. (funcall 'org-next-link t))
  9304. (defun org-translate-link (s)
  9305. "Translate a link string if a translation function has been defined."
  9306. (with-temp-buffer
  9307. (insert (org-trim s))
  9308. (org-trim (org-element-interpret-data (org-element-context)))))
  9309. (defun org-translate-link-from-planner (type path)
  9310. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9311. This is still an experimental function, your mileage may vary."
  9312. (cond
  9313. ((member type '("http" "https" "news" "ftp"))
  9314. ;; standard Internet links are the same.
  9315. nil)
  9316. ((and (equal type "irc") (string-match "^//" path))
  9317. ;; Planner has two / at the beginning of an irc link, we have 1.
  9318. ;; We should have zero, actually....
  9319. (setq path (substring path 1)))
  9320. ((and (equal type "lisp") (string-match "^/" path))
  9321. ;; Planner has a slash, we do not.
  9322. (setq type "elisp" path (substring path 1)))
  9323. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9324. ;; A typical message link. Planner has the id after the final slash,
  9325. ;; we separate it with a hash mark
  9326. (setq path (concat (match-string 1 path) "#"
  9327. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9328. (cons type path))
  9329. (defun org-find-file-at-mouse (ev)
  9330. "Open file link or URL at mouse."
  9331. (interactive "e")
  9332. (mouse-set-point ev)
  9333. (org-open-at-point 'in-emacs))
  9334. (defun org-open-at-mouse (ev)
  9335. "Open file link or URL at mouse.
  9336. See the docstring of `org-open-file' for details."
  9337. (interactive "e")
  9338. (mouse-set-point ev)
  9339. (when (eq major-mode 'org-agenda-mode)
  9340. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9341. (org-open-at-point))
  9342. (defvar org-window-config-before-follow-link nil
  9343. "The window configuration before following a link.
  9344. This is saved in case the need arises to restore it.")
  9345. ;;;###autoload
  9346. (defun org-open-at-point-global ()
  9347. "Follow a link or time-stamp like Org mode does.
  9348. This command can be called in any mode to follow an external link
  9349. or a time-stamp that has Org mode syntax. Its behavior is
  9350. undefined when called on internal links (e.g., fuzzy links).
  9351. Raise an error when there is nothing to follow. "
  9352. (interactive)
  9353. (cond ((org-in-regexp org-any-link-re)
  9354. (org-open-link-from-string (match-string-no-properties 0)))
  9355. ((or (org-in-regexp org-ts-regexp-both nil t)
  9356. (org-in-regexp org-tsr-regexp-both nil t))
  9357. (org-follow-timestamp-link))
  9358. (t (user-error "No link found"))))
  9359. ;;;###autoload
  9360. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9361. "Open a link in the string S, as if it was in Org mode."
  9362. (interactive "sLink: \nP")
  9363. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9364. (with-temp-buffer
  9365. (let ((org-inhibit-startup (not reference-buffer)))
  9366. (org-mode)
  9367. (insert s)
  9368. (goto-char (point-min))
  9369. (when reference-buffer
  9370. (setq org-link-abbrev-alist-local
  9371. (with-current-buffer reference-buffer
  9372. org-link-abbrev-alist-local)))
  9373. (org-open-at-point arg reference-buffer)))))
  9374. (defvar org-open-at-point-functions nil
  9375. "Hook that is run when following a link at point.
  9376. Functions in this hook must return t if they identify and follow
  9377. a link at point. If they don't find anything interesting at point,
  9378. they must return nil.")
  9379. (defvar org-link-search-inhibit-query nil)
  9380. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9381. (defun org--open-doi-link (path)
  9382. "Open a \"doi\" type link.
  9383. PATH is a the path to search for, as a string."
  9384. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9385. (defun org--open-elisp-link (path)
  9386. "Open a \"elisp\" type link.
  9387. PATH is the sexp to evaluate, as a string."
  9388. (let ((cmd path))
  9389. (if (or (and (org-string-nw-p
  9390. org-confirm-elisp-link-not-regexp)
  9391. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9392. (not org-confirm-elisp-link-function)
  9393. (funcall org-confirm-elisp-link-function
  9394. (format "Execute \"%s\" as elisp? "
  9395. (org-add-props cmd nil 'face 'org-warning))))
  9396. (message "%s => %s" cmd
  9397. (if (eq (string-to-char cmd) ?\()
  9398. (eval (read cmd))
  9399. (call-interactively (read cmd))))
  9400. (user-error "Abort"))))
  9401. (defun org--open-help-link (path)
  9402. "Open a \"help\" type link.
  9403. PATH is a symbol name, as a string."
  9404. (pcase (intern path)
  9405. ((and (pred fboundp) variable) (describe-function variable))
  9406. ((and (pred boundp) function) (describe-variable function))
  9407. (name (user-error "Unknown function or variable: %s" name))))
  9408. (defun org--open-shell-link (path)
  9409. "Open a \"shell\" type link.
  9410. PATH is the command to execute, as a string."
  9411. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9412. (cmd path))
  9413. (if (or (and (org-string-nw-p
  9414. org-confirm-shell-link-not-regexp)
  9415. (string-match
  9416. org-confirm-shell-link-not-regexp cmd))
  9417. (not org-confirm-shell-link-function)
  9418. (funcall org-confirm-shell-link-function
  9419. (format "Execute \"%s\" in shell? "
  9420. (org-add-props cmd nil
  9421. 'face 'org-warning))))
  9422. (progn
  9423. (message "Executing %s" cmd)
  9424. (shell-command cmd buf)
  9425. (when (featurep 'midnight)
  9426. (setq clean-buffer-list-kill-buffer-names
  9427. (cons (buffer-name buf)
  9428. clean-buffer-list-kill-buffer-names))))
  9429. (user-error "Abort"))))
  9430. (defun org-open-at-point (&optional arg reference-buffer)
  9431. "Open link, timestamp, footnote or tags at point.
  9432. When point is on a link, follow it. Normally, files will be
  9433. opened by an appropriate application. If the optional prefix
  9434. argument ARG is non-nil, Emacs will visit the file. With
  9435. a double prefix argument, try to open outside of Emacs, in the
  9436. application the system uses for this file type.
  9437. When point is on a timestamp, open the agenda at the day
  9438. specified.
  9439. When point is a footnote definition, move to the first reference
  9440. found. If it is on a reference, move to the associated
  9441. definition.
  9442. When point is on a headline, display a list of every link in the
  9443. entry, so it is possible to pick one, or all, of them. If point
  9444. is on a tag, call `org-tags-view' instead.
  9445. When optional argument REFERENCE-BUFFER is non-nil, it should
  9446. specify a buffer from where the link search should happen. This
  9447. is used internally by `org-open-link-from-string'.
  9448. On top of syntactically correct links, this function will also
  9449. try to open links and time-stamps in comments, example
  9450. blocks... i.e., whenever point is on something looking like
  9451. a timestamp or a link."
  9452. (interactive "P")
  9453. ;; On a code block, open block's results.
  9454. (unless (call-interactively 'org-babel-open-src-block-result)
  9455. (org-load-modules-maybe)
  9456. (setq org-window-config-before-follow-link (current-window-configuration))
  9457. (org-remove-occur-highlights nil nil t)
  9458. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9459. (let* ((context
  9460. ;; Only consider supported types, even if they are not
  9461. ;; the closest one.
  9462. (org-element-lineage
  9463. (org-element-context)
  9464. '(clock footnote-definition footnote-reference headline
  9465. inlinetask link timestamp)
  9466. t))
  9467. (type (org-element-type context))
  9468. (value (org-element-property :value context)))
  9469. (cond
  9470. ;; On a headline or an inlinetask, but not on a timestamp,
  9471. ;; a link, a footnote reference.
  9472. ((memq type '(headline inlinetask))
  9473. (org-match-line org-complex-heading-regexp)
  9474. (if (and (match-beginning 5)
  9475. (>= (point) (match-beginning 5))
  9476. (< (point) (match-end 5)))
  9477. ;; On tags.
  9478. (org-tags-view arg (substring (match-string 5) 0 -1))
  9479. ;; Not on tags.
  9480. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9481. (`(nil . ,_)
  9482. (require 'org-attach)
  9483. (org-attach-reveal 'if-exists))
  9484. (`(,links . ,links-end)
  9485. (dolist (link (if (stringp links) (list links) links))
  9486. (search-forward link nil links-end)
  9487. (goto-char (match-beginning 0))
  9488. (org-open-at-point))))))
  9489. ;; On a footnote reference or at definition's label.
  9490. ((or (eq type 'footnote-reference)
  9491. (and (eq type 'footnote-definition)
  9492. (save-excursion
  9493. ;; Do not validate action when point is on the
  9494. ;; spaces right after the footnote label, in
  9495. ;; order to be on par with behaviour on links.
  9496. (skip-chars-forward " \t")
  9497. (let ((begin
  9498. (org-element-property :contents-begin context)))
  9499. (if begin (< (point) begin)
  9500. (= (org-element-property :post-affiliated context)
  9501. (line-beginning-position)))))))
  9502. (org-footnote-action))
  9503. ;; No valid context. Ignore catch-all types like `headline'.
  9504. ;; If point is on something looking like a link or
  9505. ;; a time-stamp, try opening it. It may be useful in
  9506. ;; comments, example blocks...
  9507. ((memq type '(footnote-definition headline inlinetask nil))
  9508. (call-interactively #'org-open-at-point-global))
  9509. ;; On a clock line, make sure point is on the timestamp
  9510. ;; before opening it.
  9511. ((and (eq type 'clock)
  9512. value
  9513. (>= (point) (org-element-property :begin value))
  9514. (<= (point) (org-element-property :end value)))
  9515. (org-follow-timestamp-link))
  9516. ;; Do nothing on white spaces after an object.
  9517. ((>= (point)
  9518. (save-excursion
  9519. (goto-char (org-element-property :end context))
  9520. (skip-chars-backward " \t")
  9521. (point)))
  9522. (user-error "No link found"))
  9523. ((eq type 'timestamp) (org-follow-timestamp-link))
  9524. ((eq type 'link)
  9525. (let ((type (org-element-property :type context))
  9526. (path (org-link-unescape (org-element-property :path context))))
  9527. ;; Switch back to REFERENCE-BUFFER needed when called in
  9528. ;; a temporary buffer through `org-open-link-from-string'.
  9529. (with-current-buffer (or reference-buffer (current-buffer))
  9530. (cond
  9531. ((equal type "file")
  9532. (if (string-match "[*?{]" (file-name-nondirectory path))
  9533. (dired path)
  9534. ;; Look into `org-link-parameters' in order to find
  9535. ;; a DEDICATED-FUNCTION to open file. The function
  9536. ;; will be applied on raw link instead of parsed
  9537. ;; link due to the limitation in `org-add-link-type'
  9538. ;; ("open" function called with a single argument).
  9539. ;; If no such function is found, fallback to
  9540. ;; `org-open-file'.
  9541. (let* ((option (org-element-property :search-option context))
  9542. (app (org-element-property :application context))
  9543. (dedicated-function
  9544. (org-link-get-parameter
  9545. (if app (concat type "+" app) type)
  9546. :follow)))
  9547. (if dedicated-function
  9548. (funcall dedicated-function
  9549. (concat path
  9550. (and option (concat "::" option))))
  9551. (apply #'org-open-file
  9552. path
  9553. (cond (arg)
  9554. ((equal app "emacs") 'emacs)
  9555. ((equal app "sys") 'system))
  9556. (cond ((not option) nil)
  9557. ((string-match-p "\\`[0-9]+\\'" option)
  9558. (list (string-to-number option)))
  9559. (t (list nil
  9560. (org-link-unescape option)))))))))
  9561. ((functionp (org-link-get-parameter type :follow))
  9562. (funcall (org-link-get-parameter type :follow) path))
  9563. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9564. (unless (run-hook-with-args-until-success
  9565. 'org-open-link-functions path)
  9566. (if (not arg) (org-mark-ring-push)
  9567. (switch-to-buffer-other-window
  9568. (org-get-buffer-for-internal-link (current-buffer))))
  9569. (let ((destination
  9570. (org-with-wide-buffer
  9571. (if (equal type "radio")
  9572. (org-search-radio-target
  9573. (org-element-property :path context))
  9574. (org-link-search
  9575. (if (member type '("custom-id" "coderef"))
  9576. (org-element-property :raw-link context)
  9577. path)
  9578. ;; Prevent fuzzy links from matching
  9579. ;; themselves.
  9580. (and (equal type "fuzzy")
  9581. (+ 2 (org-element-property :begin context)))))
  9582. (point))))
  9583. (unless (and (<= (point-min) destination)
  9584. (>= (point-max) destination))
  9585. (widen))
  9586. (goto-char destination))))
  9587. (t (browse-url-at-point))))))
  9588. (t (user-error "No link found")))))
  9589. (run-hook-with-args 'org-follow-link-hook)))
  9590. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9591. "Offer links in the current entry and return the selected link.
  9592. If there is only one link, return it.
  9593. If NTH is an integer, return the NTH link found.
  9594. If ZERO is a string, check also this string for a link, and if
  9595. there is one, return it."
  9596. (with-current-buffer buffer
  9597. (org-with-wide-buffer
  9598. (goto-char marker)
  9599. (let ((cnt ?0)
  9600. have-zero end links link c)
  9601. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9602. (push (match-string 0 zero) links)
  9603. (setq cnt (1- cnt) have-zero t))
  9604. (save-excursion
  9605. (org-back-to-heading t)
  9606. (setq end (save-excursion (outline-next-heading) (point)))
  9607. (while (re-search-forward org-any-link-re end t)
  9608. (push (match-string 0) links))
  9609. (setq links (org-uniquify (reverse links))))
  9610. (cond
  9611. ((null links)
  9612. (message "No links"))
  9613. ((equal (length links) 1)
  9614. (setq link (car links)))
  9615. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9616. (setq link (nth (if have-zero nth (1- nth)) links)))
  9617. (t ; we have to select a link
  9618. (save-excursion
  9619. (save-window-excursion
  9620. (delete-other-windows)
  9621. (with-output-to-temp-buffer "*Select Link*"
  9622. (dolist (l links)
  9623. (cond
  9624. ((not (string-match org-bracket-link-regexp l))
  9625. (princ (format "[%c] %s\n" (cl-incf cnt)
  9626. (org-unbracket-string "<" ">" l))))
  9627. ((match-end 3)
  9628. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9629. (match-string 3 l) (match-string 1 l))))
  9630. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9631. (match-string 1 l)))))))
  9632. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9633. (message "Select link to open, RET to open all:")
  9634. (setq c (read-char-exclusive))
  9635. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9636. (when (equal c ?q) (user-error "Abort"))
  9637. (if (equal c ?\C-m)
  9638. (setq link links)
  9639. (setq nth (- c ?0))
  9640. (when have-zero (setq nth (1+ nth)))
  9641. (unless (and (integerp nth) (>= (length links) nth))
  9642. (user-error "Invalid link selection"))
  9643. (setq link (nth (1- nth) links)))))
  9644. (cons link end)))))
  9645. ;; TODO: These functions are deprecated since `org-open-at-point'
  9646. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9647. (defun org-open-file-with-system (path)
  9648. "Open file at PATH using the system way of opening it."
  9649. (org-open-file path 'system))
  9650. (defun org-open-file-with-emacs (path)
  9651. "Open file at PATH in Emacs."
  9652. (org-open-file path 'emacs))
  9653. ;;; File search
  9654. (defvar org-create-file-search-functions nil
  9655. "List of functions to construct the right search string for a file link.
  9656. These functions are called in turn with point at the location to
  9657. which the link should point.
  9658. A function in the hook should first test if it would like to
  9659. handle this file type, for example by checking the `major-mode'
  9660. or the file extension. If it decides not to handle this file, it
  9661. should just return nil to give other functions a chance. If it
  9662. does handle the file, it must return the search string to be used
  9663. when following the link. The search string will be part of the
  9664. file link, given after a double colon, and `org-open-at-point'
  9665. will automatically search for it. If special measures must be
  9666. taken to make the search successful, another function should be
  9667. added to the companion hook `org-execute-file-search-functions',
  9668. which see.
  9669. A function in this hook may also use `setq' to set the variable
  9670. `description' to provide a suggestion for the descriptive text to
  9671. be used for this link when it gets inserted into an Org buffer
  9672. with \\[org-insert-link].")
  9673. (defvar org-execute-file-search-functions nil
  9674. "List of functions to execute a file search triggered by a link.
  9675. Functions added to this hook must accept a single argument, the
  9676. search string that was part of the file link, the part after the
  9677. double colon. The function must first check if it would like to
  9678. handle this search, for example by checking the `major-mode' or
  9679. the file extension. If it decides not to handle this search, it
  9680. should just return nil to give other functions a chance. If it
  9681. does handle the search, it must return a non-nil value to keep
  9682. other functions from trying.
  9683. Each function can access the current prefix argument through the
  9684. variable `current-prefix-arg'. Note that a single prefix is used
  9685. to force opening a link in Emacs, so it may be good to only use a
  9686. numeric or double prefix to guide the search function.
  9687. In case this is needed, a function in this hook can also restore
  9688. the window configuration before `org-open-at-point' was called using:
  9689. (set-window-configuration org-window-config-before-follow-link)")
  9690. (defun org-search-radio-target (target)
  9691. "Search a radio target matching TARGET in current buffer.
  9692. White spaces are not significant."
  9693. (let ((re (format "<<<%s>>>"
  9694. (mapconcat #'regexp-quote
  9695. (split-string target)
  9696. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9697. (origin (point)))
  9698. (goto-char (point-min))
  9699. (catch :radio-match
  9700. (while (re-search-forward re nil t)
  9701. (backward-char)
  9702. (let ((object (org-element-context)))
  9703. (when (eq (org-element-type object) 'radio-target)
  9704. (goto-char (org-element-property :begin object))
  9705. (org-show-context 'link-search)
  9706. (throw :radio-match nil))))
  9707. (goto-char origin)
  9708. (user-error "No match for radio target: %s" target))))
  9709. (defun org-link-search (s &optional avoid-pos stealth)
  9710. "Search for a search string S.
  9711. If S starts with \"#\", it triggers a custom ID search.
  9712. If S is enclosed within parenthesis, it initiates a coderef
  9713. search.
  9714. If S is surrounded by forward slashes, it is interpreted as
  9715. a regular expression. In Org mode files, this will create an
  9716. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9717. to list matches. If the current buffer is in `dired-mode', grep
  9718. will be used to search in all files.
  9719. When AVOID-POS is given, ignore matches near that position.
  9720. When optional argument STEALTH is non-nil, do not modify
  9721. visibility around point, thus ignoring `org-show-context-detail'
  9722. variable.
  9723. Search is case-insensitive and ignores white spaces. Return type
  9724. of matched result, which is either `dedicated' or `fuzzy'."
  9725. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9726. (let* ((case-fold-search t)
  9727. (origin (point))
  9728. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9729. (starred (eq (string-to-char normalized) ?*))
  9730. (words (split-string (if starred (substring s 1) s)))
  9731. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9732. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9733. type)
  9734. (cond
  9735. ;; Check if there are any special search functions.
  9736. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9737. ((eq (string-to-char s) ?#)
  9738. ;; Look for a custom ID S if S starts with "#".
  9739. (let* ((id (substring normalized 1))
  9740. (match (org-find-property "CUSTOM_ID" id)))
  9741. (if match (progn (goto-char match) (setf type 'dedicated))
  9742. (error "No match for custom ID: %s" id))))
  9743. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9744. ;; Look for coderef targets if S is enclosed within parenthesis.
  9745. (let ((coderef (match-string-no-properties 1 normalized))
  9746. (re (substring s-single-re 1 -1)))
  9747. (goto-char (point-min))
  9748. (catch :coderef-match
  9749. (while (re-search-forward re nil t)
  9750. (let ((element (org-element-at-point)))
  9751. (when (and (memq (org-element-type element)
  9752. '(example-block src-block))
  9753. ;; Build proper regexp according to current
  9754. ;; block's label format.
  9755. (let ((label-fmt
  9756. (regexp-quote
  9757. (or (org-element-property :label-fmt element)
  9758. org-coderef-label-format))))
  9759. (save-excursion
  9760. (beginning-of-line)
  9761. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9762. (format label-fmt coderef))))))
  9763. (setq type 'dedicated)
  9764. (goto-char (match-beginning 1))
  9765. (throw :coderef-match nil))))
  9766. (goto-char origin)
  9767. (error "No match for coderef: %s" coderef))))
  9768. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9769. ;; Look for a regular expression.
  9770. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9771. (match-string 1 s)))
  9772. ;; From here, we handle fuzzy links.
  9773. ;;
  9774. ;; Look for targets, only if not in a headline search.
  9775. ((and (not starred)
  9776. (let ((target (format "<<%s>>" s-multi-re)))
  9777. (catch :target-match
  9778. (goto-char (point-min))
  9779. (while (re-search-forward target nil t)
  9780. (backward-char)
  9781. (let ((context (org-element-context)))
  9782. (when (eq (org-element-type context) 'target)
  9783. (setq type 'dedicated)
  9784. (goto-char (org-element-property :begin context))
  9785. (throw :target-match t))))
  9786. nil))))
  9787. ;; Look for elements named after S, only if not in a headline
  9788. ;; search.
  9789. ((and (not starred)
  9790. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9791. (catch :name-match
  9792. (goto-char (point-min))
  9793. (while (re-search-forward name nil t)
  9794. (let ((element (org-element-at-point)))
  9795. (when (equal words
  9796. (split-string
  9797. (org-element-property :name element)))
  9798. (setq type 'dedicated)
  9799. (beginning-of-line)
  9800. (throw :name-match t))))
  9801. nil))))
  9802. ;; Regular text search. Prefer headlines in Org mode buffers.
  9803. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9804. ;; statistics cookies and tags.
  9805. ((and (derived-mode-p 'org-mode)
  9806. (let ((title-re
  9807. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9808. org-outline-regexp-bol
  9809. org-comment-string
  9810. (mapconcat #'regexp-quote words ".+")))
  9811. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9812. (comment-re (eval-when-compile
  9813. (format "\\`%s[ \t]+" org-comment-string))))
  9814. (goto-char (point-min))
  9815. (catch :found
  9816. (while (re-search-forward title-re nil t)
  9817. (when (equal words
  9818. (split-string
  9819. (replace-regexp-in-string
  9820. cookie-re ""
  9821. (replace-regexp-in-string
  9822. comment-re "" (org-get-heading t t t)))))
  9823. (throw :found t)))
  9824. nil)))
  9825. (beginning-of-line)
  9826. (setq type 'dedicated))
  9827. ;; Offer to create non-existent headline depending on
  9828. ;; `org-link-search-must-match-exact-headline'.
  9829. ((and (derived-mode-p 'org-mode)
  9830. (not org-link-search-inhibit-query)
  9831. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9832. (yes-or-no-p "No match - create this as a new heading? "))
  9833. (goto-char (point-max))
  9834. (unless (bolp) (newline))
  9835. (org-insert-heading nil t t)
  9836. (insert s "\n")
  9837. (beginning-of-line 0))
  9838. ;; Only headlines are looked after. No need to process
  9839. ;; further: throw an error.
  9840. ((and (derived-mode-p 'org-mode)
  9841. (or starred org-link-search-must-match-exact-headline))
  9842. (goto-char origin)
  9843. (error "No match for fuzzy expression: %s" normalized))
  9844. ;; Regular text search.
  9845. ((catch :fuzzy-match
  9846. (goto-char (point-min))
  9847. (while (re-search-forward s-multi-re nil t)
  9848. ;; Skip match if it contains AVOID-POS or it is included in
  9849. ;; a link with a description but outside the description.
  9850. (unless (or (and avoid-pos
  9851. (<= (match-beginning 0) avoid-pos)
  9852. (> (match-end 0) avoid-pos))
  9853. (and (save-match-data
  9854. (org-in-regexp org-bracket-link-regexp))
  9855. (match-beginning 3)
  9856. (or (> (match-beginning 3) (point))
  9857. (<= (match-end 3) (point)))
  9858. (org-element-lineage
  9859. (save-match-data (org-element-context))
  9860. '(link) t)))
  9861. (goto-char (match-beginning 0))
  9862. (setq type 'fuzzy)
  9863. (throw :fuzzy-match t)))
  9864. nil))
  9865. ;; All failed. Throw an error.
  9866. (t (goto-char origin)
  9867. (error "No match for fuzzy expression: %s" normalized)))
  9868. ;; Disclose surroundings of match, if appropriate.
  9869. (when (and (derived-mode-p 'org-mode) (not stealth))
  9870. (org-show-context 'link-search))
  9871. type))
  9872. (defun org-get-buffer-for-internal-link (buffer)
  9873. "Return a buffer to be used for displaying the link target of internal links."
  9874. (cond
  9875. ((not org-display-internal-link-with-indirect-buffer)
  9876. buffer)
  9877. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9878. (message "Buffer is already a clone, not making another one")
  9879. ;; we also do not modify visibility in this case
  9880. buffer)
  9881. (t ; make a new indirect buffer for displaying the link
  9882. (let* ((bn (buffer-name buffer))
  9883. (ibn (concat bn "(Clone)"))
  9884. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9885. (with-current-buffer ib (org-overview))
  9886. ib))))
  9887. (defun org-do-occur (regexp &optional cleanup)
  9888. "Call the Emacs command `occur'.
  9889. If CLEANUP is non-nil, remove the printout of the regular expression
  9890. in the *Occur* buffer. This is useful if the regex is long and not useful
  9891. to read."
  9892. (occur regexp)
  9893. (when cleanup
  9894. (let ((cwin (selected-window)) win beg end)
  9895. (when (setq win (get-buffer-window "*Occur*"))
  9896. (select-window win))
  9897. (goto-char (point-min))
  9898. (when (re-search-forward "match[a-z]+" nil t)
  9899. (setq beg (match-end 0))
  9900. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9901. (setq end (1- (match-beginning 0)))))
  9902. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9903. (goto-char (point-min))
  9904. (select-window cwin))))
  9905. ;;; The mark ring for links jumps
  9906. (defvar org-mark-ring nil
  9907. "Mark ring for positions before jumps in Org mode.")
  9908. (defvar org-mark-ring-last-goto nil
  9909. "Last position in the mark ring used to go back.")
  9910. ;; Fill and close the ring
  9911. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9912. (dotimes (_ org-mark-ring-length)
  9913. (push (make-marker) org-mark-ring))
  9914. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9915. org-mark-ring)
  9916. (defun org-mark-ring-push (&optional pos buffer)
  9917. "Put the current position or POS into the mark ring and rotate it."
  9918. (interactive)
  9919. (setq pos (or pos (point)))
  9920. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9921. (move-marker (car org-mark-ring)
  9922. (or pos (point))
  9923. (or buffer (current-buffer)))
  9924. (message "%s"
  9925. (substitute-command-keys
  9926. "Position saved to mark ring, go back with \
  9927. `\\[org-mark-ring-goto]'.")))
  9928. (defun org-mark-ring-goto (&optional n)
  9929. "Jump to the previous position in the mark ring.
  9930. With prefix arg N, jump back that many stored positions. When
  9931. called several times in succession, walk through the entire ring.
  9932. Org mode commands jumping to a different position in the current file,
  9933. or to another Org file, automatically push the old position onto the ring."
  9934. (interactive "p")
  9935. (let (p m)
  9936. (if (eq last-command this-command)
  9937. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9938. (setq p org-mark-ring))
  9939. (setq org-mark-ring-last-goto p)
  9940. (setq m (car p))
  9941. (pop-to-buffer-same-window (marker-buffer m))
  9942. (goto-char m)
  9943. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9944. (defun org-add-angle-brackets (s)
  9945. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9946. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9947. s)
  9948. ;;; Following specific links
  9949. (defvar org-agenda-buffer-tmp-name)
  9950. (defvar org-agenda-start-on-weekday)
  9951. (defun org-follow-timestamp-link ()
  9952. "Open an agenda view for the time-stamp date/range at point."
  9953. (cond
  9954. ((org-at-date-range-p t)
  9955. (let ((org-agenda-start-on-weekday)
  9956. (t1 (match-string 1))
  9957. (t2 (match-string 2)) tt1 tt2)
  9958. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9959. tt2 (time-to-days (org-time-string-to-time t2)))
  9960. (let ((org-agenda-buffer-tmp-name
  9961. (format "*Org Agenda(a:%s)"
  9962. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9963. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9964. ((org-at-timestamp-p 'lax)
  9965. (let ((org-agenda-buffer-tmp-name
  9966. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9967. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9968. (substring (match-string 1) 0 10)))
  9969. 1)))
  9970. (t (error "This should not happen"))))
  9971. ;;; Following file links
  9972. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9973. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9974. (declare-function mailcap-mime-info
  9975. "mailcap" (string &optional request no-decode))
  9976. (defvar org-wait nil)
  9977. (defun org-open-file (path &optional in-emacs line search)
  9978. "Open the file at PATH.
  9979. First, this expands any special file name abbreviations. Then the
  9980. configuration variable `org-file-apps' is checked if it contains an
  9981. entry for this file type, and if yes, the corresponding command is launched.
  9982. If no application is found, Emacs simply visits the file.
  9983. With optional prefix argument IN-EMACS, Emacs will visit the file.
  9984. With a double \\[universal-argument] \\[universal-argument] \
  9985. prefix arg, Org tries to avoid opening in Emacs
  9986. and to use an external application to visit the file.
  9987. Optional LINE specifies a line to go to, optional SEARCH a string
  9988. to search for. If LINE or SEARCH is given, the file will be
  9989. opened in Emacs, unless an entry from org-file-apps that makes
  9990. use of groups in a regexp matches.
  9991. If you want to change the way frames are used when following a
  9992. link, please customize `org-link-frame-setup'.
  9993. If the file does not exist, an error is thrown."
  9994. (let* ((file (if (equal path "")
  9995. buffer-file-name
  9996. (substitute-in-file-name (expand-file-name path))))
  9997. (file-apps (append org-file-apps (org-default-apps)))
  9998. (apps (cl-remove-if
  9999. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10000. (apps-dlink (cl-remove-if-not
  10001. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10002. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10003. (dirp (unless remp (file-directory-p file)))
  10004. (file (if (and dirp org-open-directory-means-index-dot-org)
  10005. (concat (file-name-as-directory file) "index.org")
  10006. file))
  10007. (a-m-a-p (assq 'auto-mode apps))
  10008. (dfile (downcase file))
  10009. ;; Reconstruct the original link from the PATH, LINE and
  10010. ;; SEARCH args.
  10011. (link (cond (line (concat file "::" (number-to-string line)))
  10012. (search (concat file "::" search))
  10013. (t file)))
  10014. (dlink (downcase link))
  10015. (ext
  10016. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10017. (match-string 1 dfile)))
  10018. (save-position-maybe
  10019. (let ((old-buffer (current-buffer))
  10020. (old-pos (point))
  10021. (old-mode major-mode))
  10022. (lambda ()
  10023. (and (derived-mode-p 'org-mode)
  10024. (eq old-mode 'org-mode)
  10025. (or (not (eq old-buffer (current-buffer)))
  10026. (not (eq old-pos (point))))
  10027. (org-mark-ring-push old-pos old-buffer)))))
  10028. cmd link-match-data)
  10029. (cond
  10030. ((member in-emacs '((16) system))
  10031. (setq cmd (cdr (assq 'system apps))))
  10032. (in-emacs (setq cmd 'emacs))
  10033. (t
  10034. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10035. (and dirp (cdr (assq 'directory apps)))
  10036. ;; First, try matching against apps-dlink if we
  10037. ;; get a match here, store the match data for
  10038. ;; later.
  10039. (let ((match (assoc-default dlink apps-dlink
  10040. 'string-match)))
  10041. (if match
  10042. (progn (setq link-match-data (match-data))
  10043. match)
  10044. (progn (setq in-emacs (or in-emacs line search))
  10045. nil))) ; if we have no match in apps-dlink,
  10046. ; always open the file in emacs if line or search
  10047. ; is given (for backwards compatibility)
  10048. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10049. 'string-match)
  10050. (cdr (assoc ext apps))
  10051. (cdr (assq t apps))))))
  10052. (when (eq cmd 'system)
  10053. (setq cmd (cdr (assq 'system apps))))
  10054. (when (eq cmd 'default)
  10055. (setq cmd (cdr (assoc t apps))))
  10056. (when (eq cmd 'mailcap)
  10057. (require 'mailcap)
  10058. (mailcap-parse-mailcaps)
  10059. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10060. (command (mailcap-mime-info mime-type)))
  10061. (if (stringp command)
  10062. (setq cmd command)
  10063. (setq cmd 'emacs))))
  10064. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10065. (not (file-exists-p file))
  10066. (not org-open-non-existing-files))
  10067. (user-error "No such file: %s" file))
  10068. (cond
  10069. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10070. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10071. (while (string-match "['\"]%s['\"]" cmd)
  10072. (setq cmd (replace-match "%s" t t cmd)))
  10073. (setq cmd (replace-regexp-in-string
  10074. "%s"
  10075. (shell-quote-argument (convert-standard-filename file))
  10076. cmd
  10077. nil t))
  10078. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10079. (save-match-data
  10080. (let ((match-index 1)
  10081. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10082. (set-match-data link-match-data)
  10083. (while (<= match-index number-of-groups)
  10084. (let ((regex (concat "%" (number-to-string match-index)))
  10085. (replace-with (match-string match-index dlink)))
  10086. (while (string-match regex cmd)
  10087. (setq cmd (replace-match replace-with t t cmd))))
  10088. (setq match-index (+ match-index 1)))))
  10089. (save-window-excursion
  10090. (message "Running %s...done" cmd)
  10091. (start-process-shell-command cmd nil cmd)
  10092. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10093. ((or (stringp cmd)
  10094. (eq cmd 'emacs))
  10095. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10096. (widen)
  10097. (cond (line (org-goto-line line)
  10098. (when (derived-mode-p 'org-mode) (org-reveal)))
  10099. (search (condition-case err
  10100. (org-link-search search)
  10101. ;; Save position before error-ing out so user
  10102. ;; can easily move back to the original buffer.
  10103. (error (funcall save-position-maybe)
  10104. (error (nth 1 err)))))))
  10105. ((functionp cmd)
  10106. (save-match-data
  10107. (set-match-data link-match-data)
  10108. (condition-case nil
  10109. (funcall cmd file link)
  10110. ;; FIXME: Remove this check when most default installations
  10111. ;; of Emacs have at least Org 9.0.
  10112. ((debug wrong-number-of-arguments wrong-type-argument
  10113. invalid-function)
  10114. (user-error "Please see Org News for version 9.0 about \
  10115. `org-file-apps'--Lisp error: %S" cmd)))))
  10116. ((consp cmd)
  10117. ;; FIXME: Remove this check when most default installations of
  10118. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10119. ;; fall back to `org-link-frame-setup' for an old usage of
  10120. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10121. (user-error "Please see Org News for version 9.0 about \
  10122. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10123. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10124. (funcall save-position-maybe)))
  10125. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10126. "This function returns non-nil if `entry' uses a regular
  10127. expression which should be matched against the whole link by
  10128. org-open-file.
  10129. It assumes that is the case when the entry uses a regular
  10130. expression which has at least one grouping construct and the
  10131. action is either a lisp form or a command string containing
  10132. `%1', i.e. using at least one subexpression match as a
  10133. parameter."
  10134. (let ((selector (car entry))
  10135. (action (cdr entry)))
  10136. (if (stringp selector)
  10137. (and (> (regexp-opt-depth selector) 0)
  10138. (or (and (stringp action)
  10139. (string-match "%[0-9]" action))
  10140. (consp action)))
  10141. nil)))
  10142. (defun org-default-apps ()
  10143. "Return the default applications for this operating system."
  10144. (cond
  10145. ((eq system-type 'darwin)
  10146. org-file-apps-defaults-macosx)
  10147. ((eq system-type 'windows-nt)
  10148. org-file-apps-defaults-windowsnt)
  10149. (t org-file-apps-defaults-gnu)))
  10150. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10151. "Convert extensions to regular expressions in the cars of LIST.
  10152. Also, weed out any non-string entries, because the return value is used
  10153. only for regexp matching.
  10154. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10155. point to the symbol `emacs', indicating that the file should
  10156. be opened in Emacs."
  10157. (append
  10158. (delq nil
  10159. (mapcar (lambda (x)
  10160. (unless (not (stringp (car x)))
  10161. (if (string-match "\\W" (car x))
  10162. x
  10163. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10164. list))
  10165. (when add-auto-mode
  10166. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10167. (defvar ange-ftp-name-format)
  10168. (defun org-file-remote-p (file)
  10169. "Test whether FILE specifies a location on a remote system.
  10170. Return non-nil if the location is indeed remote.
  10171. For example, the filename \"/user@host:/foo\" specifies a location
  10172. on the system \"/user@host:\"."
  10173. (cond ((fboundp 'file-remote-p)
  10174. (file-remote-p file))
  10175. ((fboundp 'tramp-handle-file-remote-p)
  10176. (tramp-handle-file-remote-p file))
  10177. ((and (boundp 'ange-ftp-name-format)
  10178. (string-match (car ange-ftp-name-format) file))
  10179. t)))
  10180. ;;;; Refiling
  10181. (defun org-get-org-file ()
  10182. "Read a filename, with default directory `org-directory'."
  10183. (let ((default (or org-default-notes-file remember-data-file)))
  10184. (read-file-name (format "File name [%s]: " default)
  10185. (file-name-as-directory org-directory)
  10186. default)))
  10187. (defun org-notes-order-reversed-p ()
  10188. "Check if the current file should receive notes in reversed order."
  10189. (cond
  10190. ((not org-reverse-note-order) nil)
  10191. ((eq t org-reverse-note-order) t)
  10192. ((not (listp org-reverse-note-order)) nil)
  10193. (t (catch 'exit
  10194. (dolist (entry org-reverse-note-order)
  10195. (when (string-match (car entry) buffer-file-name)
  10196. (throw 'exit (cdr entry))))))))
  10197. (defvar org-refile-target-table nil
  10198. "The list of refile targets, created by `org-refile'.")
  10199. (defvar org-agenda-new-buffers nil
  10200. "Buffers created to visit agenda files.")
  10201. (defvar org-refile-cache nil
  10202. "Cache for refile targets.")
  10203. (defvar org-refile-markers nil
  10204. "All the markers used for caching refile locations.")
  10205. (defun org-refile-marker (pos)
  10206. "Get a new refile marker, but only if caching is in use."
  10207. (if (not org-refile-use-cache)
  10208. pos
  10209. (let ((m (make-marker)))
  10210. (move-marker m pos)
  10211. (push m org-refile-markers)
  10212. m)))
  10213. (defun org-refile-cache-clear ()
  10214. "Clear the refile cache and disable all the markers."
  10215. (dolist (m org-refile-markers) (move-marker m nil))
  10216. (setq org-refile-markers nil)
  10217. (setq org-refile-cache nil)
  10218. (message "Refile cache has been cleared"))
  10219. (defun org-refile-cache-check-set (set)
  10220. "Check if all the markers in the cache still have live buffers."
  10221. (let (marker)
  10222. (catch 'exit
  10223. (while (and set (setq marker (nth 3 (pop set))))
  10224. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10225. (when (and marker (null (marker-buffer marker)))
  10226. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10227. (sit-for 3)
  10228. (throw 'exit nil)))
  10229. t)))
  10230. (defun org-refile-cache-put (set &rest identifiers)
  10231. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10232. (let* ((key (sha1 (prin1-to-string identifiers)))
  10233. (entry (assoc key org-refile-cache)))
  10234. (if entry
  10235. (setcdr entry set)
  10236. (push (cons key set) org-refile-cache))))
  10237. (defun org-refile-cache-get (&rest identifiers)
  10238. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10239. (cond
  10240. ((not org-refile-cache) nil)
  10241. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10242. (t
  10243. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10244. org-refile-cache))))
  10245. (and set (org-refile-cache-check-set set) set)))))
  10246. (defvar org-outline-path-cache nil
  10247. "Alist between buffer positions and outline paths.
  10248. It value is an alist (POSITION . PATH) where POSITION is the
  10249. buffer position at the beginning of an entry and PATH is a list
  10250. of strings describing the outline path for that entry, in reverse
  10251. order.")
  10252. (defun org-refile-get-targets (&optional default-buffer)
  10253. "Produce a table with refile targets."
  10254. (let ((case-fold-search nil)
  10255. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10256. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10257. targets tgs files desc descre)
  10258. (message "Getting targets...")
  10259. (with-current-buffer (or default-buffer (current-buffer))
  10260. (dolist (entry entries)
  10261. (setq files (car entry) desc (cdr entry))
  10262. (cond
  10263. ((null files) (setq files (list (current-buffer))))
  10264. ((eq files 'org-agenda-files)
  10265. (setq files (org-agenda-files 'unrestricted)))
  10266. ((and (symbolp files) (fboundp files))
  10267. (setq files (funcall files)))
  10268. ((and (symbolp files) (boundp files))
  10269. (setq files (symbol-value files))))
  10270. (when (stringp files) (setq files (list files)))
  10271. (cond
  10272. ((eq (car desc) :tag)
  10273. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10274. ((eq (car desc) :todo)
  10275. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10276. ((eq (car desc) :regexp)
  10277. (setq descre (cdr desc)))
  10278. ((eq (car desc) :level)
  10279. (setq descre (concat "^\\*\\{" (number-to-string
  10280. (if org-odd-levels-only
  10281. (1- (* 2 (cdr desc)))
  10282. (cdr desc)))
  10283. "\\}[ \t]")))
  10284. ((eq (car desc) :maxlevel)
  10285. (setq descre (concat "^\\*\\{1," (number-to-string
  10286. (if org-odd-levels-only
  10287. (1- (* 2 (cdr desc)))
  10288. (cdr desc)))
  10289. "\\}[ \t]")))
  10290. (t (error "Bad refiling target description %s" desc)))
  10291. (dolist (f files)
  10292. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10293. (or
  10294. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10295. (progn
  10296. (when (bufferp f)
  10297. (setq f (buffer-file-name (buffer-base-buffer f))))
  10298. (setq f (and f (expand-file-name f)))
  10299. (when (eq org-refile-use-outline-path 'file)
  10300. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10301. (when (eq org-refile-use-outline-path 'buffer-name)
  10302. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10303. (when (eq org-refile-use-outline-path 'full-file-path)
  10304. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10305. (org-with-wide-buffer
  10306. (goto-char (point-min))
  10307. (setq org-outline-path-cache nil)
  10308. (while (re-search-forward descre nil t)
  10309. (beginning-of-line)
  10310. (let ((case-fold-search nil))
  10311. (looking-at org-complex-heading-regexp))
  10312. (let ((begin (point))
  10313. (heading (match-string-no-properties 4)))
  10314. (unless (or (and
  10315. org-refile-target-verify-function
  10316. (not
  10317. (funcall org-refile-target-verify-function)))
  10318. (not heading))
  10319. (let ((re (format org-complex-heading-regexp-format
  10320. (regexp-quote heading)))
  10321. (target
  10322. (if (not org-refile-use-outline-path) heading
  10323. (mapconcat
  10324. #'identity
  10325. (append
  10326. (pcase org-refile-use-outline-path
  10327. (`file (list (file-name-nondirectory
  10328. (buffer-file-name
  10329. (buffer-base-buffer)))))
  10330. (`full-file-path
  10331. (list (buffer-file-name
  10332. (buffer-base-buffer))))
  10333. (`buffer-name
  10334. (list (buffer-name
  10335. (buffer-base-buffer))))
  10336. (_ nil))
  10337. (mapcar (lambda (s) (replace-regexp-in-string
  10338. "/" "\\/" s nil t))
  10339. (org-get-outline-path t t)))
  10340. "/"))))
  10341. (push (list target f re (org-refile-marker (point)))
  10342. tgs)))
  10343. (when (= (point) begin)
  10344. ;; Verification function has not moved point.
  10345. (end-of-line)))))))
  10346. (when org-refile-use-cache
  10347. (org-refile-cache-put tgs (buffer-file-name) descre))
  10348. (setq targets (append tgs targets))))))
  10349. (message "Getting targets...done")
  10350. (delete-dups (nreverse targets))))
  10351. (defun org--get-outline-path-1 (&optional use-cache)
  10352. "Return outline path to current headline.
  10353. Outline path is a list of strings, in reverse order. When
  10354. optional argument USE-CACHE is non-nil, make use of a cache. See
  10355. `org-get-outline-path' for details.
  10356. Assume buffer is widened and point is on a headline."
  10357. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10358. (let ((p (point))
  10359. (heading (let ((case-fold-search nil))
  10360. (looking-at org-complex-heading-regexp)
  10361. (if (not (match-end 4)) ""
  10362. ;; Remove statistics cookies.
  10363. (org-trim
  10364. (org-link-display-format
  10365. (replace-regexp-in-string
  10366. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10367. (match-string-no-properties 4))))))))
  10368. (if (org-up-heading-safe)
  10369. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10370. (when use-cache
  10371. (push (cons p path) org-outline-path-cache))
  10372. path)
  10373. ;; This is a new root node. Since we assume we are moving
  10374. ;; forward, we can drop previous cache so as to limit number
  10375. ;; of associations there.
  10376. (let ((path (list heading)))
  10377. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10378. path)))))
  10379. (defun org-get-outline-path (&optional with-self use-cache)
  10380. "Return the outline path to the current entry.
  10381. An outline path is a list of ancestors for current headline, as
  10382. a list of strings. Statistics cookies are removed and links are
  10383. replaced with their description, if any, or their path otherwise.
  10384. When optional argument WITH-SELF is non-nil, the path also
  10385. includes the current headline.
  10386. When optional argument USE-CACHE is non-nil, cache outline paths
  10387. between calls to this function so as to avoid backtracking. This
  10388. argument is useful when planning to find more than one outline
  10389. path in the same document. In that case, there are two
  10390. conditions to satisfy:
  10391. - `org-outline-path-cache' is set to nil before starting the
  10392. process;
  10393. - outline paths are computed by increasing buffer positions."
  10394. (org-with-wide-buffer
  10395. (and (or (and with-self (org-back-to-heading t))
  10396. (org-up-heading-safe))
  10397. (reverse (org--get-outline-path-1 use-cache)))))
  10398. (defun org-format-outline-path (path &optional width prefix separator)
  10399. "Format the outline path PATH for display.
  10400. WIDTH is the maximum number of characters that is available.
  10401. PREFIX is a prefix to be included in the returned string,
  10402. such as the file name.
  10403. SEPARATOR is inserted between the different parts of the path,
  10404. the default is \"/\"."
  10405. (setq width (or width 79))
  10406. (setq path (delq nil path))
  10407. (unless (> width 0)
  10408. (user-error "Argument `width' must be positive"))
  10409. (setq separator (or separator "/"))
  10410. (let* ((org-odd-levels-only nil)
  10411. (fpath (concat
  10412. prefix (and prefix path separator)
  10413. (mapconcat
  10414. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10415. (cl-loop for head in path
  10416. for n from 0
  10417. collect (org-add-props
  10418. head nil 'face
  10419. (nth (% n org-n-level-faces) org-level-faces)))
  10420. separator))))
  10421. (when (> (length fpath) width)
  10422. (if (< width 7)
  10423. ;; It's unlikely that `width' will be this small, but don't
  10424. ;; waste characters by adding ".." if it is.
  10425. (setq fpath (substring fpath 0 width))
  10426. (setf (substring fpath (- width 2)) "..")))
  10427. fpath))
  10428. (defun org-display-outline-path (&optional file current separator just-return-string)
  10429. "Display the current outline path in the echo area.
  10430. If FILE is non-nil, prepend the output with the file name.
  10431. If CURRENT is non-nil, append the current heading to the output.
  10432. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10433. the different parts of the path and defaults to \"/\".
  10434. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10435. (interactive "P")
  10436. (let* (case-fold-search
  10437. (bfn (buffer-file-name (buffer-base-buffer)))
  10438. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10439. res)
  10440. (when current (setq path (append path
  10441. (save-excursion
  10442. (org-back-to-heading t)
  10443. (when (looking-at org-complex-heading-regexp)
  10444. (list (match-string 4)))))))
  10445. (setq res
  10446. (org-format-outline-path
  10447. path
  10448. (1- (frame-width))
  10449. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10450. separator))
  10451. (if just-return-string
  10452. (org-no-properties res)
  10453. (org-unlogged-message "%s" res))))
  10454. (defvar org-refile-history nil
  10455. "History for refiling operations.")
  10456. (defvar org-after-refile-insert-hook nil
  10457. "Hook run after `org-refile' has inserted its stuff at the new location.
  10458. Note that this is still *before* the stuff will be removed from
  10459. the *old* location.")
  10460. (defvar org-capture-last-stored-marker)
  10461. (defvar org-refile-keep nil
  10462. "Non-nil means `org-refile' will copy instead of refile.")
  10463. (defun org-copy ()
  10464. "Like `org-refile', but copy."
  10465. (interactive)
  10466. (let ((org-refile-keep t))
  10467. (funcall 'org-refile nil nil nil "Copy")))
  10468. (defun org-refile (&optional arg default-buffer rfloc msg)
  10469. "Move the entry or entries at point to another heading.
  10470. The list of target headings is compiled using the information in
  10471. `org-refile-targets', which see.
  10472. At the target location, the entry is filed as a subitem of the
  10473. target heading. Depending on `org-reverse-note-order', the new
  10474. subitem will either be the first or the last subitem.
  10475. If there is an active region, all entries in that region will be
  10476. refiled. However, the region must fulfill the requirement that
  10477. the first heading sets the top-level of the moved text.
  10478. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10479. location
  10480. and not actually move anything.
  10481. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10482. location where the last
  10483. refiling operation has put the subtree.
  10484. With a numeric prefix argument of `2', refile to the running clock.
  10485. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10486. being set to t and copy to the target location, don't move it.
  10487. Beware that keeping refiled entries may result in duplicated ID
  10488. properties.
  10489. RFLOC can be a refile location obtained in a different way.
  10490. MSG is a string to replace \"Refile\" in the default prompt with
  10491. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10492. See also `org-refile-use-outline-path'.
  10493. If you are using target caching (see `org-refile-use-cache'), you
  10494. have to clear the target cache in order to find new targets.
  10495. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10496. prefix argument (`C-u C-u C-u C-c C-w')."
  10497. (interactive "P")
  10498. (if (member arg '(0 (64)))
  10499. (org-refile-cache-clear)
  10500. (let* ((actionmsg (cond (msg msg)
  10501. ((equal arg 3) "Refile (and keep)")
  10502. (t "Refile")))
  10503. (regionp (org-region-active-p))
  10504. (region-start (and regionp (region-beginning)))
  10505. (region-end (and regionp (region-end)))
  10506. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10507. pos it nbuf file level reversed)
  10508. (setq last-command nil)
  10509. (when regionp
  10510. (goto-char region-start)
  10511. (or (bolp) (goto-char (point-at-bol)))
  10512. (setq region-start (point))
  10513. (unless (or (org-kill-is-subtree-p
  10514. (buffer-substring region-start region-end))
  10515. (prog1 org-refile-active-region-within-subtree
  10516. (let ((s (point-at-eol)))
  10517. (org-toggle-heading)
  10518. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10519. (user-error "The region is not a (sequence of) subtree(s)")))
  10520. (if (equal arg '(16))
  10521. (org-refile-goto-last-stored)
  10522. (when (or
  10523. (and (equal arg 2)
  10524. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10525. (prog1
  10526. (setq it (list (or org-clock-heading "running clock")
  10527. (buffer-file-name
  10528. (marker-buffer org-clock-hd-marker))
  10529. ""
  10530. (marker-position org-clock-hd-marker)))
  10531. (setq arg nil)))
  10532. (setq it
  10533. (or rfloc
  10534. (let (heading-text)
  10535. (save-excursion
  10536. (unless (and arg (listp arg))
  10537. (org-back-to-heading t)
  10538. (setq heading-text
  10539. (replace-regexp-in-string
  10540. org-bracket-link-regexp
  10541. "\\3"
  10542. (or (nth 4 (org-heading-components))
  10543. ""))))
  10544. (org-refile-get-location
  10545. (cond ((and arg (listp arg)) "Goto")
  10546. (regionp (concat actionmsg " region to"))
  10547. (t (concat actionmsg " subtree \""
  10548. heading-text "\" to")))
  10549. default-buffer
  10550. (and (not (equal '(4) arg))
  10551. org-refile-allow-creating-parent-nodes)))))))
  10552. (setq file (nth 1 it)
  10553. pos (nth 3 it))
  10554. (when (and (not arg)
  10555. pos
  10556. (equal (buffer-file-name) file)
  10557. (if regionp
  10558. (and (>= pos region-start)
  10559. (<= pos region-end))
  10560. (and (>= pos (point))
  10561. (< pos (save-excursion
  10562. (org-end-of-subtree t t))))))
  10563. (error "Cannot refile to position inside the tree or region"))
  10564. (setq nbuf (or (find-buffer-visiting file)
  10565. (find-file-noselect file)))
  10566. (if (and arg (not (equal arg 3)))
  10567. (progn
  10568. (pop-to-buffer-same-window nbuf)
  10569. (goto-char (cond (pos)
  10570. ((org-notes-order-reversed-p) (point-min))
  10571. (t (point-max))))
  10572. (org-show-context 'org-goto))
  10573. (if regionp
  10574. (progn
  10575. (org-kill-new (buffer-substring region-start region-end))
  10576. (org-save-markers-in-region region-start region-end))
  10577. (org-copy-subtree 1 nil t))
  10578. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10579. (find-file-noselect file)))
  10580. (setq reversed (org-notes-order-reversed-p))
  10581. (org-with-wide-buffer
  10582. (if pos
  10583. (progn
  10584. (goto-char pos)
  10585. (setq level (org-get-valid-level (funcall outline-level) 1))
  10586. (goto-char
  10587. (if reversed
  10588. (or (outline-next-heading) (point-max))
  10589. (or (save-excursion (org-get-next-sibling))
  10590. (org-end-of-subtree t t)
  10591. (point-max)))))
  10592. (setq level 1)
  10593. (if (not reversed)
  10594. (goto-char (point-max))
  10595. (goto-char (point-min))
  10596. (or (outline-next-heading) (goto-char (point-max)))))
  10597. (unless (bolp) (newline))
  10598. (org-paste-subtree level nil nil t)
  10599. (when org-log-refile
  10600. (org-add-log-setup 'refile nil nil org-log-refile)
  10601. (unless (eq org-log-refile 'note)
  10602. (save-excursion (org-add-log-note))))
  10603. (and org-auto-align-tags
  10604. (let ((org-loop-over-headlines-in-active-region nil))
  10605. (org-set-tags nil t)))
  10606. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10607. :last-refile)))
  10608. (when bookmark-name
  10609. (with-demoted-errors
  10610. (bookmark-set bookmark-name))))
  10611. ;; If we are refiling for capture, make sure that the
  10612. ;; last-capture pointers point here
  10613. (when (bound-and-true-p org-capture-is-refiling)
  10614. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10615. :last-capture-marker)))
  10616. (when bookmark-name
  10617. (with-demoted-errors
  10618. (bookmark-set bookmark-name))))
  10619. (move-marker org-capture-last-stored-marker (point)))
  10620. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10621. (run-hooks 'org-after-refile-insert-hook)))
  10622. (unless org-refile-keep
  10623. (if regionp
  10624. (delete-region (point) (+ (point) (- region-end region-start)))
  10625. (delete-region
  10626. (and (org-back-to-heading t) (point))
  10627. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10628. (when (featurep 'org-inlinetask)
  10629. (org-inlinetask-remove-END-maybe))
  10630. (setq org-markers-to-move nil)
  10631. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10632. (defun org-refile-goto-last-stored ()
  10633. "Go to the location where the last refile was stored."
  10634. (interactive)
  10635. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10636. (message "This is the location of the last refile"))
  10637. (defun org-refile--get-location (refloc tbl)
  10638. "When user refile to REFLOC, find the associated target in TBL.
  10639. Also check `org-refile-target-table'."
  10640. (car (delq
  10641. nil
  10642. (mapcar
  10643. (lambda (r) (or (assoc r tbl)
  10644. (assoc r org-refile-target-table)))
  10645. (list (replace-regexp-in-string "/$" "" refloc)
  10646. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10647. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10648. "Prompt the user for a refile location, using PROMPT.
  10649. PROMPT should not be suffixed with a colon and a space, because
  10650. this function appends the default value from
  10651. `org-refile-history' automatically, if that is not empty."
  10652. (let ((org-refile-targets org-refile-targets)
  10653. (org-refile-use-outline-path org-refile-use-outline-path))
  10654. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10655. (unless org-refile-target-table
  10656. (user-error "No refile targets"))
  10657. (let* ((cbuf (current-buffer))
  10658. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10659. (cfunc (if (and org-refile-use-outline-path
  10660. org-outline-path-complete-in-steps)
  10661. #'org-olpath-completing-read
  10662. #'completing-read))
  10663. (extra (if org-refile-use-outline-path "/" ""))
  10664. (cbnex (concat (buffer-name) extra))
  10665. (filename (and cfn (expand-file-name cfn)))
  10666. (tbl (mapcar
  10667. (lambda (x)
  10668. (if (and (not (member org-refile-use-outline-path
  10669. '(file full-file-path)))
  10670. (not (equal filename (nth 1 x))))
  10671. (cons (concat (car x) extra " ("
  10672. (file-name-nondirectory (nth 1 x)) ")")
  10673. (cdr x))
  10674. (cons (concat (car x) extra) (cdr x))))
  10675. org-refile-target-table))
  10676. (completion-ignore-case t)
  10677. cdef
  10678. (prompt (concat prompt
  10679. (or (and (car org-refile-history)
  10680. (concat " (default " (car org-refile-history) ")"))
  10681. (and (assoc cbnex tbl) (setq cdef cbnex)
  10682. (concat " (default " cbnex ")"))) ": "))
  10683. pa answ parent-target child parent old-hist)
  10684. (setq old-hist org-refile-history)
  10685. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10686. nil 'org-refile-history (or cdef (car org-refile-history))))
  10687. (if (setq pa (org-refile--get-location answ tbl))
  10688. (progn
  10689. (org-refile-check-position pa)
  10690. (when (or (not org-refile-history)
  10691. (not (eq old-hist org-refile-history))
  10692. (not (equal (car pa) (car org-refile-history))))
  10693. (setq org-refile-history
  10694. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10695. org-refile-history
  10696. (cdr org-refile-history))))
  10697. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10698. (pop org-refile-history)))
  10699. pa)
  10700. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10701. (progn
  10702. (setq parent (match-string 1 answ)
  10703. child (match-string 2 answ))
  10704. (setq parent-target (org-refile--get-location parent tbl))
  10705. (when (and parent-target
  10706. (or (eq new-nodes t)
  10707. (and (eq new-nodes 'confirm)
  10708. (y-or-n-p (format "Create new node \"%s\"? "
  10709. child)))))
  10710. (org-refile-new-child parent-target child)))
  10711. (user-error "Invalid target location")))))
  10712. (declare-function org-string-nw-p "org-macs" (s))
  10713. (defun org-refile-check-position (refile-pointer)
  10714. "Check if the refile pointer matches the headline to which it points."
  10715. (let* ((file (nth 1 refile-pointer))
  10716. (re (nth 2 refile-pointer))
  10717. (pos (nth 3 refile-pointer))
  10718. buffer)
  10719. (if (and (not (markerp pos)) (not file))
  10720. (user-error "Please indicate a target file in the refile path")
  10721. (when (org-string-nw-p re)
  10722. (setq buffer (if (markerp pos)
  10723. (marker-buffer pos)
  10724. (or (find-buffer-visiting file)
  10725. (find-file-noselect file))))
  10726. (with-current-buffer buffer
  10727. (org-with-wide-buffer
  10728. (goto-char pos)
  10729. (beginning-of-line 1)
  10730. (unless (looking-at-p re)
  10731. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10732. (defun org-refile-new-child (parent-target child)
  10733. "Use refile target PARENT-TARGET to add new CHILD below it."
  10734. (unless parent-target
  10735. (error "Cannot find parent for new node"))
  10736. (let ((file (nth 1 parent-target))
  10737. (pos (nth 3 parent-target))
  10738. level)
  10739. (with-current-buffer (or (find-buffer-visiting file)
  10740. (find-file-noselect file))
  10741. (org-with-wide-buffer
  10742. (if pos
  10743. (goto-char pos)
  10744. (goto-char (point-max))
  10745. (unless (bolp) (newline)))
  10746. (when (looking-at org-outline-regexp)
  10747. (setq level (funcall outline-level))
  10748. (org-end-of-subtree t t))
  10749. (org-back-over-empty-lines)
  10750. (insert "\n" (make-string
  10751. (if pos (org-get-valid-level level 1) 1) ?*)
  10752. " " child "\n")
  10753. (beginning-of-line 0)
  10754. (list (concat (car parent-target) "/" child) file "" (point))))))
  10755. (defun org-olpath-completing-read (prompt collection &rest args)
  10756. "Read an outline path like a file name."
  10757. (let ((thetable collection))
  10758. (apply #'completing-read
  10759. prompt
  10760. (lambda (string predicate &optional flag)
  10761. (cond
  10762. ((eq flag nil) (try-completion string thetable))
  10763. ((eq flag t)
  10764. (let ((l (length string)))
  10765. (mapcar (lambda (x)
  10766. (let ((r (substring x l))
  10767. (f (if (string-match " ([^)]*)$" x)
  10768. (match-string 0 x)
  10769. "")))
  10770. (if (string-match "/" r)
  10771. (concat string (substring r 0 (match-end 0)) f)
  10772. x)))
  10773. (all-completions string thetable predicate))))
  10774. ;; Exact match?
  10775. ((eq flag 'lambda) (assoc string thetable))))
  10776. args)))
  10777. ;;;; Dynamic blocks
  10778. (defun org-find-dblock (name)
  10779. "Find the first dynamic block with name NAME in the buffer.
  10780. If not found, stay at current position and return nil."
  10781. (let ((case-fold-search t) pos)
  10782. (save-excursion
  10783. (goto-char (point-min))
  10784. (setq pos (and (re-search-forward
  10785. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10786. (match-beginning 0))))
  10787. (when pos (goto-char pos))
  10788. pos))
  10789. (defun org-create-dblock (plist)
  10790. "Create a dynamic block section, with parameters taken from PLIST.
  10791. PLIST must contain a :name entry which is used as the name of the block."
  10792. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10793. (end-of-line 1)
  10794. (newline))
  10795. (let ((col (current-column))
  10796. (name (plist-get plist :name)))
  10797. (insert "#+BEGIN: " name)
  10798. (while plist
  10799. (if (eq (car plist) :name)
  10800. (setq plist (cddr plist))
  10801. (insert " " (prin1-to-string (pop plist)))))
  10802. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10803. (beginning-of-line -2)))
  10804. (defun org-prepare-dblock ()
  10805. "Prepare dynamic block for refresh.
  10806. This empties the block, puts the cursor at the insert position and returns
  10807. the property list including an extra property :name with the block name."
  10808. (unless (looking-at org-dblock-start-re)
  10809. (user-error "Not at a dynamic block"))
  10810. (let* ((begdel (1+ (match-end 0)))
  10811. (name (org-no-properties (match-string 1)))
  10812. (params (append (list :name name)
  10813. (read (concat "(" (match-string 3) ")")))))
  10814. (save-excursion
  10815. (beginning-of-line 1)
  10816. (skip-chars-forward " \t")
  10817. (setq params (plist-put params :indentation-column (current-column))))
  10818. (unless (re-search-forward org-dblock-end-re nil t)
  10819. (error "Dynamic block not terminated"))
  10820. (setq params
  10821. (append params
  10822. (list :content (buffer-substring
  10823. begdel (match-beginning 0)))))
  10824. (delete-region begdel (match-beginning 0))
  10825. (goto-char begdel)
  10826. (open-line 1)
  10827. params))
  10828. (defun org-map-dblocks (&optional command)
  10829. "Apply COMMAND to all dynamic blocks in the current buffer.
  10830. If COMMAND is not given, use `org-update-dblock'."
  10831. (let ((cmd (or command 'org-update-dblock)))
  10832. (save-excursion
  10833. (goto-char (point-min))
  10834. (while (re-search-forward org-dblock-start-re nil t)
  10835. (goto-char (match-beginning 0))
  10836. (save-excursion
  10837. (condition-case nil
  10838. (funcall cmd)
  10839. (error (message "Error during update of dynamic block"))))
  10840. (unless (re-search-forward org-dblock-end-re nil t)
  10841. (error "Dynamic block not terminated"))))))
  10842. (defun org-dblock-update (&optional arg)
  10843. "User command for updating dynamic blocks.
  10844. Update the dynamic block at point. With prefix ARG, update all dynamic
  10845. blocks in the buffer."
  10846. (interactive "P")
  10847. (if arg
  10848. (org-update-all-dblocks)
  10849. (or (looking-at org-dblock-start-re)
  10850. (org-beginning-of-dblock))
  10851. (org-update-dblock)))
  10852. (defun org-update-dblock ()
  10853. "Update the dynamic block at point.
  10854. This means to empty the block, parse for parameters and then call
  10855. the correct writing function."
  10856. (interactive)
  10857. (save-excursion
  10858. (let* ((win (selected-window))
  10859. (pos (point))
  10860. (line (org-current-line))
  10861. (params (org-prepare-dblock))
  10862. (name (plist-get params :name))
  10863. (indent (plist-get params :indentation-column))
  10864. (cmd (intern (concat "org-dblock-write:" name))))
  10865. (message "Updating dynamic block `%s' at line %d..." name line)
  10866. (funcall cmd params)
  10867. (message "Updating dynamic block `%s' at line %d...done" name line)
  10868. (goto-char pos)
  10869. (when (and indent (> indent 0))
  10870. (setq indent (make-string indent ?\ ))
  10871. (save-excursion
  10872. (select-window win)
  10873. (org-beginning-of-dblock)
  10874. (forward-line 1)
  10875. (while (not (looking-at org-dblock-end-re))
  10876. (insert indent)
  10877. (beginning-of-line 2))
  10878. (when (looking-at org-dblock-end-re)
  10879. (and (looking-at "[ \t]+")
  10880. (replace-match ""))
  10881. (insert indent)))))))
  10882. (defun org-beginning-of-dblock ()
  10883. "Find the beginning of the dynamic block at point.
  10884. Error if there is no such block at point."
  10885. (let ((pos (point))
  10886. beg)
  10887. (end-of-line 1)
  10888. (if (and (re-search-backward org-dblock-start-re nil t)
  10889. (setq beg (match-beginning 0))
  10890. (re-search-forward org-dblock-end-re nil t)
  10891. (> (match-end 0) pos))
  10892. (goto-char beg)
  10893. (goto-char pos)
  10894. (error "Not in a dynamic block"))))
  10895. (defun org-update-all-dblocks ()
  10896. "Update all dynamic blocks in the buffer.
  10897. This function can be used in a hook."
  10898. (interactive)
  10899. (when (derived-mode-p 'org-mode)
  10900. (org-map-dblocks 'org-update-dblock)))
  10901. ;;;; Completion
  10902. (declare-function org-export-backend-options "ox" (cl-x) t)
  10903. (defun org-get-export-keywords ()
  10904. "Return a list of all currently understood export keywords.
  10905. Export keywords include options, block names, attributes and
  10906. keywords relative to each registered export back-end."
  10907. (let (keywords)
  10908. (dolist (backend
  10909. (bound-and-true-p org-export-registered-backends)
  10910. (delq nil keywords))
  10911. ;; Back-end name (for keywords, like #+LATEX:)
  10912. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10913. (dolist (option-entry (org-export-backend-options backend))
  10914. ;; Back-end options.
  10915. (push (nth 1 option-entry) keywords)))))
  10916. (defconst org-options-keywords
  10917. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10918. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10919. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10920. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10921. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10922. (defcustom org-structure-template-alist
  10923. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10924. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10925. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10926. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10927. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10928. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10929. ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
  10930. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10931. ("L" "#+LaTeX: ")
  10932. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10933. ("H" "#+HTML: ")
  10934. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10935. ("A" "#+ASCII: ")
  10936. ("i" "#+INDEX: ?")
  10937. ("I" "#+INCLUDE: %file ?"))
  10938. "Structure completion elements.
  10939. This is a list of abbreviation keys and values. The value gets inserted
  10940. if you type `<' followed by the key and then press the completion key,
  10941. usually `TAB'. %file will be replaced by a file name after prompting
  10942. for the file using completion. The cursor will be placed at the position
  10943. of the `?' in the template.
  10944. There are two templates for each key, the first uses the original Org syntax,
  10945. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10946. the default when the /org-mtags.el/ module has been loaded. See also the
  10947. variable `org-mtags-prefer-muse-templates'."
  10948. :group 'org-completion
  10949. :type '(repeat
  10950. (list
  10951. (string :tag "Key")
  10952. (string :tag "Template")))
  10953. :version "26.1"
  10954. :package-version '(Org . "8.3"))
  10955. (defun org-try-structure-completion ()
  10956. "Try to complete a structure template before point.
  10957. This looks for strings like \"<e\" on an otherwise empty line and
  10958. expands them."
  10959. (let ((l (buffer-substring (point-at-bol) (point)))
  10960. a)
  10961. (when (and (looking-at "[ \t]*$")
  10962. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  10963. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  10964. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  10965. (match-beginning 1)) a)
  10966. t)))
  10967. (defun org-complete-expand-structure-template (start cell)
  10968. "Expand a structure template."
  10969. (let ((rpl (nth 1 cell))
  10970. (ind ""))
  10971. (delete-region start (point))
  10972. (when (string-match "\\`[ \t]*#\\+" rpl)
  10973. (cond
  10974. ((bolp))
  10975. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  10976. (setq ind (buffer-substring (point-at-bol) (point))))
  10977. (t (newline))))
  10978. (setq start (point))
  10979. (when (string-match "%file" rpl)
  10980. (setq rpl (replace-match
  10981. (concat
  10982. "\""
  10983. (save-match-data
  10984. (abbreviate-file-name (read-file-name "Include file: ")))
  10985. "\"")
  10986. t t rpl)))
  10987. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  10988. (concat "\n" ind)))
  10989. (insert rpl)
  10990. (when (re-search-backward "\\?" start t) (delete-char 1))))
  10991. ;;;; TODO, DEADLINE, Comments
  10992. (defun org-toggle-comment ()
  10993. "Change the COMMENT state of an entry."
  10994. (interactive)
  10995. (save-excursion
  10996. (org-back-to-heading)
  10997. (let ((case-fold-search nil))
  10998. (looking-at org-complex-heading-regexp))
  10999. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11000. (skip-chars-forward " \t")
  11001. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11002. (if (org-in-commented-heading-p t)
  11003. (delete-region (point)
  11004. (progn (search-forward " " (line-end-position) 'move)
  11005. (skip-chars-forward " \t")
  11006. (point)))
  11007. (insert org-comment-string)
  11008. (unless (eolp) (insert " ")))))
  11009. (defvar org-last-todo-state-is-todo nil
  11010. "This is non-nil when the last TODO state change led to a TODO state.
  11011. If the last change removed the TODO tag or switched to DONE, then
  11012. this is nil.")
  11013. (defvar org-setting-tags nil) ; dynamically skipped
  11014. (defvar org-todo-setup-filter-hook nil
  11015. "Hook for functions that pre-filter todo specs.
  11016. Each function takes a todo spec and returns either nil or the spec
  11017. transformed into canonical form." )
  11018. (defvar org-todo-get-default-hook nil
  11019. "Hook for functions that get a default item for todo.
  11020. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11021. nil or a string to be used for the todo mark." )
  11022. (defvar org-agenda-headline-snapshot-before-repeat)
  11023. (defun org-current-effective-time ()
  11024. "Return current time adjusted for `org-extend-today-until' variable."
  11025. (let* ((ct (org-current-time))
  11026. (dct (decode-time ct))
  11027. (ct1
  11028. (cond
  11029. (org-use-last-clock-out-time-as-effective-time
  11030. (or (org-clock-get-last-clock-out-time) ct))
  11031. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11032. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11033. (t ct))))
  11034. ct1))
  11035. (defun org-todo-yesterday (&optional arg)
  11036. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11037. (interactive "P")
  11038. (if (eq major-mode 'org-agenda-mode)
  11039. (apply 'org-agenda-todo-yesterday arg)
  11040. (let* ((org-use-effective-time t)
  11041. (hour (nth 2 (decode-time (org-current-time))))
  11042. (org-extend-today-until (1+ hour)))
  11043. (org-todo arg))))
  11044. (defvar org-block-entry-blocking ""
  11045. "First entry preventing the TODO state change.")
  11046. (defun org-cancel-repeater ()
  11047. "Cancel a repeater by setting its numeric value to zero."
  11048. (interactive)
  11049. (save-excursion
  11050. (org-back-to-heading t)
  11051. (let ((bound1 (point))
  11052. (bound0 (save-excursion (outline-next-heading) (point))))
  11053. (when (and (re-search-forward
  11054. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11055. org-deadline-time-regexp "\\)\\|\\("
  11056. org-ts-regexp "\\)")
  11057. bound0 t)
  11058. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11059. bound1 t))
  11060. (replace-match "0" t nil nil 1)))))
  11061. (defvar org-state)
  11062. (defvar org-blocked-by-checkboxes)
  11063. (defun org-todo (&optional arg)
  11064. "Change the TODO state of an item.
  11065. The state of an item is given by a keyword at the start of the heading,
  11066. like
  11067. *** TODO Write paper
  11068. *** DONE Call mom
  11069. The different keywords are specified in the variable `org-todo-keywords'.
  11070. By default the available states are \"TODO\" and \"DONE\". So, for this
  11071. example: when the item starts with TODO, it is changed to DONE.
  11072. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11073. DONE are present, add TODO at the beginning of the heading.
  11074. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11075. state.
  11076. With numeric prefix ARG, switch to that state.
  11077. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11078. next set of TODO \
  11079. keywords (nextset).
  11080. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11081. prefix, circumvent any state blocking.
  11082. With a numeric prefix arg of 0, inhibit note taking for the change.
  11083. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11084. When called through ELisp, arg is also interpreted in the following way:
  11085. `none' -> empty state
  11086. \"\" -> switch to empty state
  11087. `done' -> switch to DONE
  11088. `nextset' -> switch to the next set of keywords
  11089. `previousset' -> switch to the previous set of keywords
  11090. \"WAITING\" -> switch to the specified keyword, but only if it
  11091. really is a member of `org-todo-keywords'."
  11092. (interactive "P")
  11093. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11094. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11095. 'region-start-level 'region))
  11096. org-loop-over-headlines-in-active-region)
  11097. (org-map-entries
  11098. `(org-todo ,arg)
  11099. org-loop-over-headlines-in-active-region
  11100. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  11101. (when (equal arg '(16)) (setq arg 'nextset))
  11102. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11103. (let ((org-blocker-hook org-blocker-hook)
  11104. commentp
  11105. case-fold-search)
  11106. (when (equal arg '(64))
  11107. (setq arg nil org-blocker-hook nil))
  11108. (when (and org-blocker-hook
  11109. (or org-inhibit-blocking
  11110. (org-entry-get nil "NOBLOCKING")))
  11111. (setq org-blocker-hook nil))
  11112. (save-excursion
  11113. (catch 'exit
  11114. (org-back-to-heading t)
  11115. (when (org-in-commented-heading-p t)
  11116. (org-toggle-comment)
  11117. (setq commentp t))
  11118. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11119. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11120. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11121. (let* ((match-data (match-data))
  11122. (startpos (point-at-bol))
  11123. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11124. (org-log-done org-log-done)
  11125. (org-log-repeat org-log-repeat)
  11126. (org-todo-log-states org-todo-log-states)
  11127. (org-inhibit-logging
  11128. (if (equal arg 0)
  11129. (progn (setq arg nil) 'note) org-inhibit-logging))
  11130. (this (match-string 1))
  11131. (hl-pos (match-beginning 0))
  11132. (head (org-get-todo-sequence-head this))
  11133. (ass (assoc head org-todo-kwd-alist))
  11134. (interpret (nth 1 ass))
  11135. (done-word (nth 3 ass))
  11136. (final-done-word (nth 4 ass))
  11137. (org-last-state (or this ""))
  11138. (completion-ignore-case t)
  11139. (member (member this org-todo-keywords-1))
  11140. (tail (cdr member))
  11141. (org-state (cond
  11142. ((and org-todo-key-trigger
  11143. (or (and (equal arg '(4))
  11144. (eq org-use-fast-todo-selection 'prefix))
  11145. (and (not arg) org-use-fast-todo-selection
  11146. (not (eq org-use-fast-todo-selection
  11147. 'prefix)))))
  11148. ;; Use fast selection.
  11149. (org-fast-todo-selection))
  11150. ((and (equal arg '(4))
  11151. (or (not org-use-fast-todo-selection)
  11152. (not org-todo-key-trigger)))
  11153. ;; Read a state with completion.
  11154. (completing-read
  11155. "State: " (mapcar #'list org-todo-keywords-1)
  11156. nil t))
  11157. ((eq arg 'right)
  11158. (if this
  11159. (if tail (car tail) nil)
  11160. (car org-todo-keywords-1)))
  11161. ((eq arg 'left)
  11162. (unless (equal member org-todo-keywords-1)
  11163. (if this
  11164. (nth (- (length org-todo-keywords-1)
  11165. (length tail) 2)
  11166. org-todo-keywords-1)
  11167. (org-last org-todo-keywords-1))))
  11168. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11169. (setq arg nil))) ;hack to fall back to cycling
  11170. (arg
  11171. ;; User or caller requests a specific state.
  11172. (cond
  11173. ((equal arg "") nil)
  11174. ((eq arg 'none) nil)
  11175. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11176. ((eq arg 'nextset)
  11177. (or (car (cdr (member head org-todo-heads)))
  11178. (car org-todo-heads)))
  11179. ((eq arg 'previousset)
  11180. (let ((org-todo-heads (reverse org-todo-heads)))
  11181. (or (car (cdr (member head org-todo-heads)))
  11182. (car org-todo-heads))))
  11183. ((car (member arg org-todo-keywords-1)))
  11184. ((stringp arg)
  11185. (user-error "State `%s' not valid in this file" arg))
  11186. ((nth (1- (prefix-numeric-value arg))
  11187. org-todo-keywords-1))))
  11188. ((null member) (or head (car org-todo-keywords-1)))
  11189. ((equal this final-done-word) nil) ;-> make empty
  11190. ((null tail) nil) ;-> first entry
  11191. ((memq interpret '(type priority))
  11192. (if (eq this-command last-command)
  11193. (car tail)
  11194. (if (> (length tail) 0)
  11195. (or done-word (car org-done-keywords))
  11196. nil)))
  11197. (t
  11198. (car tail))))
  11199. (org-state (or
  11200. (run-hook-with-args-until-success
  11201. 'org-todo-get-default-hook org-state org-last-state)
  11202. org-state))
  11203. (next (if org-state (concat " " org-state " ") " "))
  11204. (change-plist (list :type 'todo-state-change :from this :to org-state
  11205. :position startpos))
  11206. dolog now-done-p)
  11207. (when org-blocker-hook
  11208. (let (org-blocked-by-checkboxes block-reason)
  11209. (setq org-last-todo-state-is-todo
  11210. (not (member this org-done-keywords)))
  11211. (unless (save-excursion
  11212. (save-match-data
  11213. (org-with-wide-buffer
  11214. (run-hook-with-args-until-failure
  11215. 'org-blocker-hook change-plist))))
  11216. (setq block-reason (if org-blocked-by-checkboxes
  11217. "contained checkboxes"
  11218. (format "\"%s\"" org-block-entry-blocking)))
  11219. (if (called-interactively-p 'interactive)
  11220. (user-error "TODO state change from %s to %s blocked (by %s)"
  11221. this org-state block-reason)
  11222. ;; Fail silently.
  11223. (message "TODO state change from %s to %s blocked (by %s)"
  11224. this org-state block-reason)
  11225. (throw 'exit nil)))))
  11226. (store-match-data match-data)
  11227. (replace-match next t t)
  11228. (cond ((equal this org-state)
  11229. (message "TODO state was already %s" (org-trim next)))
  11230. ((not (pos-visible-in-window-p hl-pos))
  11231. (message "TODO state changed to %s" (org-trim next))))
  11232. (unless head
  11233. (setq head (org-get-todo-sequence-head org-state)
  11234. ass (assoc head org-todo-kwd-alist)
  11235. interpret (nth 1 ass)
  11236. done-word (nth 3 ass)
  11237. final-done-word (nth 4 ass)))
  11238. (when (memq arg '(nextset previousset))
  11239. (message "Keyword-Set %d/%d: %s"
  11240. (- (length org-todo-sets) -1
  11241. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11242. (length org-todo-sets)
  11243. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11244. (setq org-last-todo-state-is-todo
  11245. (not (member org-state org-done-keywords)))
  11246. (setq now-done-p (and (member org-state org-done-keywords)
  11247. (not (member this org-done-keywords))))
  11248. (and logging (org-local-logging logging))
  11249. (when (and (or org-todo-log-states org-log-done)
  11250. (not (eq org-inhibit-logging t))
  11251. (not (memq arg '(nextset previousset))))
  11252. ;; We need to look at recording a time and note.
  11253. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11254. (nth 2 (assoc this org-todo-log-states))))
  11255. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11256. (setq dolog 'time))
  11257. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11258. (and org-state
  11259. (member org-state org-not-done-keywords)
  11260. (not (member this org-not-done-keywords))))
  11261. ;; This is now a todo state and was not one before
  11262. ;; If there was a CLOSED time stamp, get rid of it.
  11263. (org-add-planning-info nil nil 'closed))
  11264. (when (and now-done-p org-log-done)
  11265. ;; It is now done, and it was not done before.
  11266. (org-add-planning-info 'closed (org-current-effective-time))
  11267. (when (and (not dolog) (eq 'note org-log-done))
  11268. (org-add-log-setup 'done org-state this 'note)))
  11269. (when (and org-state dolog)
  11270. ;; This is a non-nil state, and we need to log it.
  11271. (org-add-log-setup 'state org-state this dolog)))
  11272. ;; Fixup tag positioning.
  11273. (org-todo-trigger-tag-changes org-state)
  11274. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11275. (when org-provide-todo-statistics
  11276. (org-update-parent-todo-statistics))
  11277. (run-hooks 'org-after-todo-state-change-hook)
  11278. (when (and arg (not (member org-state org-done-keywords)))
  11279. (setq head (org-get-todo-sequence-head org-state)))
  11280. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11281. ;; Do we need to trigger a repeat?
  11282. (when now-done-p
  11283. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11284. ;; This is for the agenda, take a snapshot of the headline.
  11285. (save-match-data
  11286. (setq org-agenda-headline-snapshot-before-repeat
  11287. (org-get-heading))))
  11288. (org-auto-repeat-maybe org-state))
  11289. ;; Fixup cursor location if close to the keyword.
  11290. (when (and (outline-on-heading-p)
  11291. (not (bolp))
  11292. (save-excursion (beginning-of-line 1)
  11293. (looking-at org-todo-line-regexp))
  11294. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11295. (goto-char (or (match-end 2) (match-end 1)))
  11296. (and (looking-at " ") (just-one-space)))
  11297. (when org-trigger-hook
  11298. (save-excursion
  11299. (run-hook-with-args 'org-trigger-hook change-plist)))
  11300. (when commentp (org-toggle-comment))))))))
  11301. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11302. "Block turning an entry into a TODO, using the hierarchy.
  11303. This checks whether the current task should be blocked from state
  11304. changes. Such blocking occurs when:
  11305. 1. The task has children which are not all in a completed state.
  11306. 2. A task has a parent with the property :ORDERED:, and there
  11307. are siblings prior to the current task with incomplete
  11308. status.
  11309. 3. The parent of the task is blocked because it has siblings that should
  11310. be done first, or is child of a block grandparent TODO entry."
  11311. (if (not org-enforce-todo-dependencies)
  11312. t ; if locally turned off don't block
  11313. (catch 'dont-block
  11314. ;; If this is not a todo state change, or if this entry is already DONE,
  11315. ;; do not block
  11316. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11317. (member (plist-get change-plist :from)
  11318. (cons 'done org-done-keywords))
  11319. (member (plist-get change-plist :to)
  11320. (cons 'todo org-not-done-keywords))
  11321. (not (plist-get change-plist :to)))
  11322. (throw 'dont-block t))
  11323. ;; If this task has children, and any are undone, it's blocked
  11324. (save-excursion
  11325. (org-back-to-heading t)
  11326. (let ((this-level (funcall outline-level)))
  11327. (outline-next-heading)
  11328. (let ((child-level (funcall outline-level)))
  11329. (while (and (not (eobp))
  11330. (> child-level this-level))
  11331. ;; this todo has children, check whether they are all
  11332. ;; completed
  11333. (when (and (not (org-entry-is-done-p))
  11334. (org-entry-is-todo-p))
  11335. (setq org-block-entry-blocking (org-get-heading))
  11336. (throw 'dont-block nil))
  11337. (outline-next-heading)
  11338. (setq child-level (funcall outline-level))))))
  11339. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11340. ;; any previous siblings are undone, it's blocked
  11341. (save-excursion
  11342. (org-back-to-heading t)
  11343. (let* ((pos (point))
  11344. (parent-pos (and (org-up-heading-safe) (point)))
  11345. (case-fold-search nil))
  11346. (unless parent-pos (throw 'dont-block t)) ; no parent
  11347. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11348. (forward-line 1)
  11349. (re-search-forward org-not-done-heading-regexp pos t))
  11350. (setq org-block-entry-blocking (match-string 0))
  11351. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11352. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11353. (while t
  11354. (goto-char parent-pos)
  11355. (unless (looking-at org-not-done-heading-regexp)
  11356. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11357. (setq pos (point))
  11358. (setq parent-pos (and (org-up-heading-safe) (point)))
  11359. (unless parent-pos (throw 'dont-block t)) ; no parent
  11360. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11361. (forward-line 1)
  11362. (re-search-forward org-not-done-heading-regexp pos t)
  11363. (setq org-block-entry-blocking (org-get-heading)))
  11364. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11365. (defcustom org-track-ordered-property-with-tag nil
  11366. "Should the ORDERED property also be shown as a tag?
  11367. The ORDERED property decides if an entry should require subtasks to be
  11368. completed in sequence. Since a property is not very visible, setting
  11369. this option means that toggling the ORDERED property with the command
  11370. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11371. not relevant for the behavior, but it makes things more visible.
  11372. Note that toggling the tag with tags commands will not change the property
  11373. and therefore not influence behavior!
  11374. This can be t, meaning the tag ORDERED should be used, It can also be a
  11375. string to select a different tag for this task."
  11376. :group 'org-todo
  11377. :type '(choice
  11378. (const :tag "No tracking" nil)
  11379. (const :tag "Track with ORDERED tag" t)
  11380. (string :tag "Use other tag")))
  11381. (defun org-toggle-ordered-property ()
  11382. "Toggle the ORDERED property of the current entry.
  11383. For better visibility, you can track the value of this property with a tag.
  11384. See variable `org-track-ordered-property-with-tag'."
  11385. (interactive)
  11386. (let* ((t1 org-track-ordered-property-with-tag)
  11387. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11388. (save-excursion
  11389. (org-back-to-heading)
  11390. (if (org-entry-get nil "ORDERED")
  11391. (progn
  11392. (org-delete-property "ORDERED")
  11393. (and tag (org-toggle-tag tag 'off))
  11394. (message "Subtasks can be completed in arbitrary order"))
  11395. (org-entry-put nil "ORDERED" "t")
  11396. (and tag (org-toggle-tag tag 'on))
  11397. (message "Subtasks must be completed in sequence")))))
  11398. (defun org-block-todo-from-checkboxes (change-plist)
  11399. "Block turning an entry into a TODO, using checkboxes.
  11400. This checks whether the current task should be blocked from state
  11401. changes because there are unchecked boxes in this entry."
  11402. (if (not org-enforce-todo-checkbox-dependencies)
  11403. t ; if locally turned off don't block
  11404. (catch 'dont-block
  11405. ;; If this is not a todo state change, or if this entry is already DONE,
  11406. ;; do not block
  11407. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11408. (member (plist-get change-plist :from)
  11409. (cons 'done org-done-keywords))
  11410. (member (plist-get change-plist :to)
  11411. (cons 'todo org-not-done-keywords))
  11412. (not (plist-get change-plist :to)))
  11413. (throw 'dont-block t))
  11414. ;; If this task has checkboxes that are not checked, it's blocked
  11415. (save-excursion
  11416. (org-back-to-heading t)
  11417. (let ((beg (point)) end)
  11418. (outline-next-heading)
  11419. (setq end (point))
  11420. (goto-char beg)
  11421. (when (org-list-search-forward
  11422. (concat (org-item-beginning-re)
  11423. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11424. "\\[[- ]\\]")
  11425. end t)
  11426. (when (boundp 'org-blocked-by-checkboxes)
  11427. (setq org-blocked-by-checkboxes t))
  11428. (throw 'dont-block nil))))
  11429. t))) ; do not block
  11430. (defun org-entry-blocked-p ()
  11431. "Non-nil if entry at point is blocked."
  11432. (and (not (org-entry-get nil "NOBLOCKING"))
  11433. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11434. (not (run-hook-with-args-until-failure
  11435. 'org-blocker-hook
  11436. (list :type 'todo-state-change
  11437. :position (point)
  11438. :from 'todo
  11439. :to 'done)))))
  11440. (defun org-update-statistics-cookies (all)
  11441. "Update the statistics cookie, either from TODO or from checkboxes.
  11442. This should be called with the cursor in a line with a statistics
  11443. cookie. When called with a \\[universal-argument] prefix, update
  11444. all statistics cookies in the buffer."
  11445. (interactive "P")
  11446. (if all
  11447. (progn
  11448. (org-update-checkbox-count 'all)
  11449. (org-map-entries 'org-update-parent-todo-statistics))
  11450. (if (not (org-at-heading-p))
  11451. (org-update-checkbox-count)
  11452. (let ((pos (point-marker))
  11453. end l1 l2)
  11454. (ignore-errors (org-back-to-heading t))
  11455. (if (not (org-at-heading-p))
  11456. (org-update-checkbox-count)
  11457. (setq l1 (org-outline-level))
  11458. (setq end (save-excursion
  11459. (outline-next-heading)
  11460. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11461. (point)))
  11462. (if (and (save-excursion
  11463. (re-search-forward
  11464. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11465. (not (save-excursion (re-search-forward
  11466. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11467. (org-update-checkbox-count)
  11468. (if (and l2 (> l2 l1))
  11469. (progn
  11470. (goto-char end)
  11471. (org-update-parent-todo-statistics))
  11472. (goto-char pos)
  11473. (beginning-of-line 1)
  11474. (while (re-search-forward
  11475. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11476. (point-at-eol) t)
  11477. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11478. (goto-char pos)
  11479. (move-marker pos nil)))))
  11480. (defvar org-entry-property-inherited-from) ;; defined below
  11481. (defun org-update-parent-todo-statistics ()
  11482. "Update any statistics cookie in the parent of the current headline.
  11483. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11484. the entire subtree and this will travel up the hierarchy and update
  11485. statistics everywhere."
  11486. (let* ((prop (save-excursion (org-up-heading-safe)
  11487. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11488. (recursive (or (not org-hierarchical-todo-statistics)
  11489. (and prop (string-match "\\<recursive\\>" prop))))
  11490. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11491. 0))
  11492. (first t)
  11493. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11494. level ltoggle l1 new ndel
  11495. (cnt-all 0) (cnt-done 0) is-percent kwd
  11496. checkbox-beg cookie-present)
  11497. (catch 'exit
  11498. (save-excursion
  11499. (beginning-of-line 1)
  11500. (setq ltoggle (funcall outline-level))
  11501. ;; Three situations are to consider:
  11502. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11503. ;; to the top-level ancestor on the headline;
  11504. ;; 2. If parent has "recursive" property, repeat up to the
  11505. ;; headline setting that property, taking inheritance into
  11506. ;; account;
  11507. ;; 3. Else, move up to direct parent and proceed only once.
  11508. (while (and (setq level (org-up-heading-safe))
  11509. (or recursive first)
  11510. (>= (point) lim))
  11511. (setq first nil cookie-present nil)
  11512. (unless (and level
  11513. (not (string-match
  11514. "\\<checkbox\\>"
  11515. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11516. "")))))
  11517. (throw 'exit nil))
  11518. (while (re-search-forward box-re (point-at-eol) t)
  11519. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11520. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11521. (save-match-data
  11522. (unless (outline-next-heading) (throw 'exit nil))
  11523. (while (and (looking-at org-complex-heading-regexp)
  11524. (> (setq l1 (length (match-string 1))) level))
  11525. (setq kwd (and (or recursive (= l1 ltoggle))
  11526. (match-string 2)))
  11527. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11528. (and (eq org-provide-todo-statistics t)
  11529. (or (member kwd org-done-keywords)))
  11530. (and (listp org-provide-todo-statistics)
  11531. (stringp (car org-provide-todo-statistics))
  11532. (or (member kwd org-provide-todo-statistics)
  11533. (member kwd org-done-keywords)))
  11534. (and (listp org-provide-todo-statistics)
  11535. (listp (car org-provide-todo-statistics))
  11536. (or (member kwd (car org-provide-todo-statistics))
  11537. (and (member kwd org-done-keywords)
  11538. (member kwd (cadr org-provide-todo-statistics))))))
  11539. (setq cnt-all (1+ cnt-all))
  11540. (and (eq org-provide-todo-statistics t)
  11541. kwd
  11542. (setq cnt-all (1+ cnt-all))))
  11543. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11544. (member kwd org-done-keywords))
  11545. (and (listp org-provide-todo-statistics)
  11546. (listp (car org-provide-todo-statistics))
  11547. (member kwd org-done-keywords)
  11548. (member kwd (cadr org-provide-todo-statistics)))
  11549. (and (listp org-provide-todo-statistics)
  11550. (stringp (car org-provide-todo-statistics))
  11551. (member kwd org-done-keywords)))
  11552. (setq cnt-done (1+ cnt-done)))
  11553. (outline-next-heading)))
  11554. (setq new
  11555. (if is-percent
  11556. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11557. (max 1 cnt-all)))
  11558. (format "[%d/%d]" cnt-done cnt-all))
  11559. ndel (- (match-end 0) checkbox-beg))
  11560. (goto-char checkbox-beg)
  11561. (insert new)
  11562. (delete-region (point) (+ (point) ndel))
  11563. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11564. (when cookie-present
  11565. (run-hook-with-args 'org-after-todo-statistics-hook
  11566. cnt-done (- cnt-all cnt-done))))))
  11567. (run-hooks 'org-todo-statistics-hook)))
  11568. (defvar org-after-todo-statistics-hook nil
  11569. "Hook that is called after a TODO statistics cookie has been updated.
  11570. Each function is called with two arguments: the number of not-done entries
  11571. and the number of done entries.
  11572. For example, the following function, when added to this hook, will switch
  11573. an entry to DONE when all children are done, and back to TODO when new
  11574. entries are set to a TODO status. Note that this hook is only called
  11575. when there is a statistics cookie in the headline!
  11576. (defun org-summary-todo (n-done n-not-done)
  11577. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11578. (let (org-log-done org-log-states) ; turn off logging
  11579. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11580. ")
  11581. (defvar org-todo-statistics-hook nil
  11582. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11583. This hook runs even if there is no statistics cookie present, in which case
  11584. `org-after-todo-statistics-hook' would not run.")
  11585. (defun org-todo-trigger-tag-changes (state)
  11586. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11587. (let ((l org-todo-state-tags-triggers)
  11588. changes)
  11589. (when (or (not state) (equal state ""))
  11590. (setq changes (append changes (cdr (assoc "" l)))))
  11591. (when (and (stringp state) (> (length state) 0))
  11592. (setq changes (append changes (cdr (assoc state l)))))
  11593. (when (member state org-not-done-keywords)
  11594. (setq changes (append changes (cdr (assq 'todo l)))))
  11595. (when (member state org-done-keywords)
  11596. (setq changes (append changes (cdr (assq 'done l)))))
  11597. (dolist (c changes)
  11598. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11599. (defun org-local-logging (value)
  11600. "Get logging settings from a property VALUE."
  11601. ;; Directly set the variables, they are already local.
  11602. (setq org-log-done nil
  11603. org-log-repeat nil
  11604. org-todo-log-states nil)
  11605. (dolist (w (split-string value))
  11606. (let (a)
  11607. (cond
  11608. ((setq a (assoc w org-startup-options))
  11609. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11610. (set (nth 1 a) (nth 2 a))))
  11611. ((setq a (org-extract-log-state-settings w))
  11612. (and (member (car a) org-todo-keywords-1)
  11613. (push a org-todo-log-states)))))))
  11614. (defun org-get-todo-sequence-head (kwd)
  11615. "Return the head of the TODO sequence to which KWD belongs.
  11616. If KWD is not set, check if there is a text property remembering the
  11617. right sequence."
  11618. (let (p)
  11619. (cond
  11620. ((not kwd)
  11621. (or (get-text-property (point-at-bol) 'org-todo-head)
  11622. (progn
  11623. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11624. nil (point-at-eol)))
  11625. (get-text-property p 'org-todo-head))))
  11626. ((not (member kwd org-todo-keywords-1))
  11627. (car org-todo-keywords-1))
  11628. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11629. (defun org-fast-todo-selection ()
  11630. "Fast TODO keyword selection with single keys.
  11631. Returns the new TODO keyword, or nil if no state change should occur."
  11632. (let* ((fulltable org-todo-key-alist)
  11633. (done-keywords org-done-keywords) ;; needed for the faces.
  11634. (maxlen (apply 'max (mapcar
  11635. (lambda (x)
  11636. (if (stringp (car x)) (string-width (car x)) 0))
  11637. fulltable)))
  11638. (expert nil)
  11639. (fwidth (+ maxlen 3 1 3))
  11640. (ncol (/ (- (window-width) 4) fwidth))
  11641. tg cnt e c tbl
  11642. groups ingroup)
  11643. (save-excursion
  11644. (save-window-excursion
  11645. (if expert
  11646. (set-buffer (get-buffer-create " *Org todo*"))
  11647. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11648. (erase-buffer)
  11649. (setq-local org-done-keywords done-keywords)
  11650. (setq tbl fulltable cnt 0)
  11651. (while (setq e (pop tbl))
  11652. (cond
  11653. ((equal e '(:startgroup))
  11654. (push '() groups) (setq ingroup t)
  11655. (unless (= cnt 0)
  11656. (setq cnt 0)
  11657. (insert "\n"))
  11658. (insert "{ "))
  11659. ((equal e '(:endgroup))
  11660. (setq ingroup nil cnt 0)
  11661. (insert "}\n"))
  11662. ((equal e '(:newline))
  11663. (unless (= cnt 0)
  11664. (setq cnt 0)
  11665. (insert "\n")
  11666. (setq e (car tbl))
  11667. (while (equal (car tbl) '(:newline))
  11668. (insert "\n")
  11669. (setq tbl (cdr tbl)))))
  11670. (t
  11671. (setq tg (car e) c (cdr e))
  11672. (when ingroup (push tg (car groups)))
  11673. (setq tg (org-add-props tg nil 'face
  11674. (org-get-todo-face tg)))
  11675. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11676. (insert "[" c "] " tg (make-string
  11677. (- fwidth 4 (length tg)) ?\ ))
  11678. (when (= (setq cnt (1+ cnt)) ncol)
  11679. (insert "\n")
  11680. (when ingroup (insert " "))
  11681. (setq cnt 0)))))
  11682. (insert "\n")
  11683. (goto-char (point-min))
  11684. (unless expert (org-fit-window-to-buffer))
  11685. (message "[a-z..]:Set [SPC]:clear")
  11686. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11687. (cond
  11688. ((or (= c ?\C-g)
  11689. (and (= c ?q) (not (rassoc c fulltable))))
  11690. (setq quit-flag t))
  11691. ((= c ?\ ) nil)
  11692. ((setq e (rassoc c fulltable) tg (car e))
  11693. tg)
  11694. (t (setq quit-flag t)))))))
  11695. (defun org-entry-is-todo-p ()
  11696. (member (org-get-todo-state) org-not-done-keywords))
  11697. (defun org-entry-is-done-p ()
  11698. (member (org-get-todo-state) org-done-keywords))
  11699. (defun org-get-todo-state ()
  11700. "Return the TODO keyword of the current subtree."
  11701. (save-excursion
  11702. (org-back-to-heading t)
  11703. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11704. (match-end 2)
  11705. (match-string 2))))
  11706. (defun org-at-date-range-p (&optional inactive-ok)
  11707. "Non-nil if point is inside a date range.
  11708. When optional argument INACTIVE-OK is non-nil, also consider
  11709. inactive time ranges.
  11710. When this function returns a non-nil value, match data is set
  11711. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11712. on INACTIVE-OK."
  11713. (interactive)
  11714. (save-excursion
  11715. (catch 'exit
  11716. (let ((pos (point)))
  11717. (skip-chars-backward "^[<\r\n")
  11718. (skip-chars-backward "<[")
  11719. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11720. (>= (match-end 0) pos)
  11721. (throw 'exit t))
  11722. (skip-chars-backward "^<[\r\n")
  11723. (skip-chars-backward "<[")
  11724. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11725. (>= (match-end 0) pos)
  11726. (throw 'exit t)))
  11727. nil)))
  11728. (defun org-get-repeat (&optional timestamp)
  11729. "Check if there is a time-stamp with repeater in this entry.
  11730. Return the repeater, as a string, or nil. Also return nil when
  11731. this function is called before first heading.
  11732. When optional argument TIMESTAMP is a string, extract the
  11733. repeater from there instead."
  11734. (save-match-data
  11735. (cond (timestamp
  11736. (and (string-match org-repeat-re timestamp)
  11737. (match-string-no-properties 1 timestamp)))
  11738. ((org-before-first-heading-p) nil)
  11739. (t
  11740. (save-excursion
  11741. (org-back-to-heading t)
  11742. (let ((end (org-entry-end-position)))
  11743. (catch :repeat
  11744. (while (re-search-forward org-repeat-re end t)
  11745. (when (save-match-data (org-at-timestamp-p 'agenda))
  11746. (throw :repeat (match-string-no-properties 1)))))))))))
  11747. (defvar org-last-changed-timestamp)
  11748. (defvar org-last-inserted-timestamp)
  11749. (defvar org-log-post-message)
  11750. (defvar org-log-note-purpose)
  11751. (defvar org-log-note-how nil)
  11752. (defvar org-log-note-extra)
  11753. (defun org-auto-repeat-maybe (done-word)
  11754. "Check if the current headline contains a repeated time-stamp.
  11755. If yes, set TODO state back to what it was and change the base date
  11756. of repeating deadline/scheduled time stamps to new date.
  11757. This function is run automatically after each state change to a DONE state."
  11758. (let* ((repeat (org-get-repeat))
  11759. (aa (assoc org-last-state org-todo-kwd-alist))
  11760. (interpret (nth 1 aa))
  11761. (head (nth 2 aa))
  11762. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11763. (msg "Entry repeats: ")
  11764. (org-log-done nil)
  11765. (org-todo-log-states nil)
  11766. (end (copy-marker (org-entry-end-position))))
  11767. (unwind-protect
  11768. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11769. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11770. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11771. org-todo-repeat-to-state)))
  11772. (org-todo (cond
  11773. ((and to-state (member to-state org-todo-keywords-1))
  11774. to-state)
  11775. ((eq interpret 'type) org-last-state)
  11776. (head)
  11777. (t 'none))))
  11778. (org-back-to-heading t)
  11779. (org-add-planning-info nil nil 'closed)
  11780. ;; When `org-log-repeat' is non-nil or entry contains
  11781. ;; a clock, set LAST_REPEAT property.
  11782. (when (or org-log-repeat
  11783. (catch :clock
  11784. (save-excursion
  11785. (while (re-search-forward org-clock-line-re end t)
  11786. (when (org-at-clock-log-p) (throw :clock t))))))
  11787. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11788. (org-time-stamp-format t t)
  11789. (current-time))))
  11790. (when org-log-repeat
  11791. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11792. (memq 'org-add-log-note post-command-hook))
  11793. ;; We are already setup for some record.
  11794. (when (eq org-log-repeat 'note)
  11795. ;; Make sure we take a note, not only a time stamp.
  11796. (setq org-log-note-how 'note))
  11797. ;; Set up for taking a record.
  11798. (org-add-log-setup 'state
  11799. (or done-word (car org-done-keywords))
  11800. org-last-state
  11801. org-log-repeat)))
  11802. (let ((planning-re (regexp-opt
  11803. (list org-scheduled-string org-deadline-string))))
  11804. (while (re-search-forward org-ts-regexp end t)
  11805. (let* ((ts (match-string 0))
  11806. (planning? (org-at-planning-p))
  11807. (type (if (not planning?) "Plain:"
  11808. (save-excursion
  11809. (re-search-backward
  11810. planning-re (line-beginning-position) t)
  11811. (match-string 0)))))
  11812. (cond
  11813. ;; Ignore fake time-stamps (e.g., within comments).
  11814. ((not (org-at-timestamp-p 'agenda)))
  11815. ;; Time-stamps without a repeater are usually
  11816. ;; skipped. However, a SCHEDULED time-stamp without
  11817. ;; one is removed, as they are no longer relevant.
  11818. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11819. ts))
  11820. (when (equal type org-scheduled-string)
  11821. (org-remove-timestamp-with-keyword type)))
  11822. (t
  11823. (let ((n (string-to-number (match-string 2 ts)))
  11824. (what (match-string 3 ts)))
  11825. (when (equal what "w") (setq n (* n 7) what "d"))
  11826. (when (and (equal what "h")
  11827. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11828. ts)))
  11829. (user-error
  11830. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11831. has been set"
  11832. n))
  11833. ;; Preparation, see if we need to modify the start
  11834. ;; date for the change.
  11835. (when (match-end 1)
  11836. (let ((time (save-match-data
  11837. (org-time-string-to-time ts))))
  11838. (cond
  11839. ((equal (match-string 1 ts) ".")
  11840. ;; Shift starting date to today
  11841. (org-timestamp-change
  11842. (- (org-today) (time-to-days time))
  11843. 'day))
  11844. ((equal (match-string 1 ts) "+")
  11845. (let ((nshiftmax 10)
  11846. (nshift 0))
  11847. (while (or (= nshift 0)
  11848. (not (time-less-p (current-time) time)))
  11849. (when (= (cl-incf nshift) nshiftmax)
  11850. (or (y-or-n-p
  11851. (format "%d repeater intervals were not \
  11852. enough to shift date past today. Continue? "
  11853. nshift))
  11854. (user-error "Abort")))
  11855. (org-timestamp-change n (cdr (assoc what whata)))
  11856. (org-in-regexp org-ts-regexp3)
  11857. (setq ts (match-string 1))
  11858. (setq time
  11859. (save-match-data
  11860. (org-time-string-to-time ts)))))
  11861. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11862. ;; Rematch, so that we have everything in place
  11863. ;; for the real shift.
  11864. (org-in-regexp org-ts-regexp3)
  11865. (setq ts (match-string 1))
  11866. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11867. ts)))))
  11868. (save-excursion
  11869. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11870. (setq msg
  11871. (concat
  11872. msg type " " org-last-changed-timestamp " "))))))))
  11873. (setq org-log-post-message msg)
  11874. (message "%s" msg))
  11875. (set-marker end nil))))
  11876. (defun org-show-todo-tree (arg)
  11877. "Make a compact tree which shows all headlines marked with TODO.
  11878. The tree will show the lines where the regexp matches, and all higher
  11879. headlines above the match.
  11880. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11881. With a numeric prefix N, construct a sparse tree for the Nth element
  11882. of `org-todo-keywords-1'."
  11883. (interactive "P")
  11884. (let ((case-fold-search nil)
  11885. (kwd-re
  11886. (cond ((null arg) org-not-done-regexp)
  11887. ((equal arg '(4))
  11888. (let ((kwd
  11889. (completing-read "Keyword (or KWD1|KWD2|...): "
  11890. (mapcar #'list org-todo-keywords-1))))
  11891. (concat "\\("
  11892. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11893. "\\)\\>")))
  11894. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11895. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11896. org-todo-keywords-1)))
  11897. (t (user-error "Invalid prefix argument: %s" arg)))))
  11898. (message "%d TODO entries found"
  11899. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11900. (defun org--deadline-or-schedule (arg type time)
  11901. "Insert DEADLINE or SCHEDULE information in current entry.
  11902. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11903. `org-schedule' for information about ARG and TIME arguments."
  11904. (let* ((deadline? (eq type 'deadline))
  11905. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11906. (log (if deadline? org-log-redeadline org-log-reschedule))
  11907. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11908. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11909. ;; Save repeater cookie from either TIME or current scheduled
  11910. ;; time stamp. We are going to insert it back at the end of
  11911. ;; the process.
  11912. (repeater (or (and (org-string-nw-p time)
  11913. ;; We use `org-repeat-re' because we need
  11914. ;; to tell the difference between a real
  11915. ;; repeater and a time delta, e.g. "+2d".
  11916. (string-match org-repeat-re time)
  11917. (match-string 1 time))
  11918. (and (org-string-nw-p old-date)
  11919. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11920. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11921. old-date)
  11922. (match-string 1 old-date)))))
  11923. (pcase arg
  11924. (`(4)
  11925. (when (and old-date log)
  11926. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11927. nil old-date log))
  11928. (org-remove-timestamp-with-keyword keyword)
  11929. (message (if deadline? "Item no longer has a deadline."
  11930. "Item is no longer scheduled.")))
  11931. (`(16)
  11932. (save-excursion
  11933. (org-back-to-heading t)
  11934. (let ((regexp (if deadline? org-deadline-time-regexp
  11935. org-scheduled-time-regexp)))
  11936. (if (not (re-search-forward regexp (line-end-position 2) t))
  11937. (user-error (if deadline? "No deadline information to update"
  11938. "No scheduled information to update"))
  11939. (let* ((rpl0 (match-string 1))
  11940. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11941. (msg (if deadline? "Warn starting from" "Delay until")))
  11942. (replace-match
  11943. (concat keyword
  11944. " <" rpl
  11945. (format " -%dd"
  11946. (abs (- (time-to-days
  11947. (save-match-data
  11948. (org-read-date
  11949. nil t nil msg old-date-time)))
  11950. (time-to-days old-date-time))))
  11951. ">") t t))))))
  11952. (_
  11953. (org-add-planning-info type time 'closed)
  11954. (when (and old-date
  11955. log
  11956. (not (equal old-date org-last-inserted-timestamp)))
  11957. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11958. org-last-inserted-timestamp
  11959. old-date
  11960. log))
  11961. (when repeater
  11962. (save-excursion
  11963. (org-back-to-heading t)
  11964. (when (re-search-forward
  11965. (concat keyword " " org-last-inserted-timestamp)
  11966. (line-end-position 2)
  11967. t)
  11968. (goto-char (1- (match-end 0)))
  11969. (insert " " repeater)
  11970. (setq org-last-inserted-timestamp
  11971. (concat (substring org-last-inserted-timestamp 0 -1)
  11972. " " repeater
  11973. (substring org-last-inserted-timestamp -1))))))
  11974. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11975. org-last-inserted-timestamp)))))
  11976. (defun org-deadline (arg &optional time)
  11977. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11978. With one universal prefix argument, remove any deadline from the item.
  11979. With two universal prefix arguments, prompt for a warning delay.
  11980. With argument TIME, set the deadline at the corresponding date. TIME
  11981. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11982. (interactive "P")
  11983. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11984. (org-map-entries
  11985. (lambda () (org--deadline-or-schedule arg 'deadline time))
  11986. nil
  11987. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11988. 'region-start-level
  11989. 'region)
  11990. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  11991. (org--deadline-or-schedule arg 'deadline time)))
  11992. (defun org-schedule (arg &optional time)
  11993. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  11994. With one universal prefix argument, remove any scheduling date from the item.
  11995. With two universal prefix arguments, prompt for a delay cookie.
  11996. With argument TIME, scheduled at the corresponding date. TIME can
  11997. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11998. (interactive "P")
  11999. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12000. (org-map-entries
  12001. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12002. nil
  12003. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12004. 'region-start-level
  12005. 'region)
  12006. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12007. (org--deadline-or-schedule arg 'scheduled time)))
  12008. (defun org-get-scheduled-time (pom &optional inherit)
  12009. "Get the scheduled time as a time tuple, of a format suitable
  12010. for calling org-schedule with, or if there is no scheduling,
  12011. returns nil."
  12012. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12013. (when time
  12014. (apply 'encode-time (org-parse-time-string time)))))
  12015. (defun org-get-deadline-time (pom &optional inherit)
  12016. "Get the deadline as a time tuple, of a format suitable for
  12017. calling org-deadline with, or if there is no scheduling, returns
  12018. nil."
  12019. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12020. (when time
  12021. (apply 'encode-time (org-parse-time-string time)))))
  12022. (defun org-remove-timestamp-with-keyword (keyword)
  12023. "Remove all time stamps with KEYWORD in the current entry."
  12024. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12025. beg)
  12026. (save-excursion
  12027. (org-back-to-heading t)
  12028. (setq beg (point))
  12029. (outline-next-heading)
  12030. (while (re-search-backward re beg t)
  12031. (replace-match "")
  12032. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12033. (equal (char-before) ?\ ))
  12034. (backward-delete-char 1)
  12035. (when (string-match "^[ \t]*$" (buffer-substring
  12036. (point-at-bol) (point-at-eol)))
  12037. (delete-region (point-at-bol)
  12038. (min (point-max) (1+ (point-at-eol))))))))))
  12039. (defvar org-time-was-given) ; dynamically scoped parameter
  12040. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12041. (defun org-at-planning-p ()
  12042. "Non-nil when point is on a planning info line."
  12043. ;; This is as accurate and faster than `org-element-at-point' since
  12044. ;; planning info location is fixed in the section.
  12045. (org-with-wide-buffer
  12046. (beginning-of-line)
  12047. (and (looking-at-p org-planning-line-re)
  12048. (eq (point)
  12049. (ignore-errors
  12050. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12051. (org-back-to-heading t)
  12052. (org-with-limited-levels (org-back-to-heading t)))
  12053. (line-beginning-position 2))))))
  12054. (defun org-add-planning-info (what &optional time &rest remove)
  12055. "Insert new timestamp with keyword in the planning line.
  12056. WHAT indicates what kind of time stamp to add. It is a symbol
  12057. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12058. the time to use. If none is given, the user is prompted for
  12059. a date. REMOVE indicates what kind of entries to remove. An old
  12060. WHAT entry will also be removed."
  12061. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12062. (catch 'exit
  12063. (when (and (memq what '(scheduled deadline))
  12064. (or (not time)
  12065. (and (stringp time)
  12066. (string-match "^[-+]+[0-9]" time))))
  12067. ;; Try to get a default date/time from existing timestamp
  12068. (save-excursion
  12069. (org-back-to-heading t)
  12070. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12071. (when (re-search-forward (if (eq what 'scheduled)
  12072. org-scheduled-time-regexp
  12073. org-deadline-time-regexp)
  12074. end t)
  12075. (setq ts (match-string 1)
  12076. default-time (apply 'encode-time (org-parse-time-string ts))
  12077. default-input (and ts (org-get-compact-tod ts)))))))
  12078. (when what
  12079. (setq time
  12080. (if (stringp time)
  12081. ;; This is a string (relative or absolute), set
  12082. ;; proper date.
  12083. (apply #'encode-time
  12084. (org-read-date-analyze
  12085. time default-time (decode-time default-time)))
  12086. ;; If necessary, get the time from the user
  12087. (or time (org-read-date nil 'to-time nil nil
  12088. default-time default-input)))))
  12089. (org-with-wide-buffer
  12090. (org-back-to-heading t)
  12091. (forward-line)
  12092. (unless (bolp) (insert "\n"))
  12093. (cond ((looking-at-p org-planning-line-re)
  12094. ;; Move to current indentation.
  12095. (skip-chars-forward " \t")
  12096. ;; Check if we have to remove something.
  12097. (dolist (type (if what (cons what remove) remove))
  12098. (save-excursion
  12099. (when (re-search-forward
  12100. (cl-case type
  12101. (closed org-closed-time-regexp)
  12102. (deadline org-deadline-time-regexp)
  12103. (scheduled org-scheduled-time-regexp)
  12104. (otherwise
  12105. (error "Invalid planning type: %s" type)))
  12106. (line-end-position) t)
  12107. ;; Delete until next keyword or end of line.
  12108. (delete-region
  12109. (match-beginning 0)
  12110. (if (re-search-forward org-keyword-time-not-clock-regexp
  12111. (line-end-position)
  12112. t)
  12113. (match-beginning 0)
  12114. (line-end-position))))))
  12115. ;; If there is nothing more to add and no more keyword
  12116. ;; is left, remove the line completely.
  12117. (if (and (looking-at-p "[ \t]*$") (not what))
  12118. (delete-region (line-beginning-position)
  12119. (line-beginning-position 2))
  12120. ;; If we removed last keyword, do not leave trailing
  12121. ;; white space at the end of line.
  12122. (let ((p (point)))
  12123. (save-excursion
  12124. (end-of-line)
  12125. (unless (= (skip-chars-backward " \t" p) 0)
  12126. (delete-region (point) (line-end-position)))))))
  12127. ((not what) (throw 'exit nil)) ; Nothing to do.
  12128. (t (insert-before-markers "\n")
  12129. (backward-char 1)
  12130. (when org-adapt-indentation
  12131. (indent-to-column (1+ (org-outline-level))))))
  12132. (when what
  12133. ;; Insert planning keyword.
  12134. (insert (cl-case what
  12135. (closed org-closed-string)
  12136. (deadline org-deadline-string)
  12137. (scheduled org-scheduled-string)
  12138. (otherwise (error "Invalid planning type: %s" what)))
  12139. " ")
  12140. ;; Insert associated timestamp.
  12141. (let ((ts (org-insert-time-stamp
  12142. time
  12143. (or org-time-was-given
  12144. (and (eq what 'closed) org-log-done-with-time))
  12145. (eq what 'closed)
  12146. nil nil (list org-end-time-was-given))))
  12147. (unless (eolp) (insert " "))
  12148. ts))))))
  12149. (defvar org-log-note-marker (make-marker)
  12150. "Marker pointing at the entry where the note is to be inserted.")
  12151. (defvar org-log-note-purpose nil)
  12152. (defvar org-log-note-state nil)
  12153. (defvar org-log-note-previous-state nil)
  12154. (defvar org-log-note-extra nil)
  12155. (defvar org-log-note-window-configuration nil)
  12156. (defvar org-log-note-return-to (make-marker))
  12157. (defvar org-log-note-effective-time nil
  12158. "Remembered current time so that dynamically scoped
  12159. `org-extend-today-until' affects timestamps in state change log")
  12160. (defvar org-log-post-message nil
  12161. "Message to be displayed after a log note has been stored.
  12162. The auto-repeater uses this.")
  12163. (defun org-add-note ()
  12164. "Add a note to the current entry.
  12165. This is done in the same way as adding a state change note."
  12166. (interactive)
  12167. (org-add-log-setup 'note))
  12168. (defun org-log-beginning (&optional create)
  12169. "Return expected start of log notes in current entry.
  12170. When optional argument CREATE is non-nil, the function creates
  12171. a drawer to store notes, if necessary. Returned position ignores
  12172. narrowing."
  12173. (org-with-wide-buffer
  12174. (let ((drawer (org-log-into-drawer)))
  12175. (cond
  12176. (drawer
  12177. (org-end-of-meta-data)
  12178. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12179. (end (if (org-at-heading-p) (point)
  12180. (save-excursion (outline-next-heading) (point))))
  12181. (case-fold-search t))
  12182. (catch 'exit
  12183. ;; Try to find existing drawer.
  12184. (while (re-search-forward regexp end t)
  12185. (let ((element (org-element-at-point)))
  12186. (when (eq (org-element-type element) 'drawer)
  12187. (let ((cend (org-element-property :contents-end element)))
  12188. (when (and (not org-log-states-order-reversed) cend)
  12189. (goto-char cend)))
  12190. (throw 'exit nil))))
  12191. ;; No drawer found. Create one, if permitted.
  12192. (when create
  12193. (unless (bolp) (insert "\n"))
  12194. (let ((beg (point)))
  12195. (insert ":" drawer ":\n:END:\n")
  12196. (org-indent-region beg (point)))
  12197. (end-of-line -1)))))
  12198. (t
  12199. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12200. (skip-chars-forward " \t\n")
  12201. (beginning-of-line)
  12202. (unless org-log-states-order-reversed
  12203. (org-skip-over-state-notes)
  12204. (skip-chars-backward " \t\n")
  12205. (forward-line)))))
  12206. (if (bolp) (point) (line-beginning-position 2))))
  12207. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12208. "Set up the post command hook to take a note.
  12209. If this is about to TODO state change, the new state is expected in STATE.
  12210. HOW is an indicator what kind of note should be created.
  12211. EXTRA is additional text that will be inserted into the notes buffer."
  12212. (move-marker org-log-note-marker (point))
  12213. (setq org-log-note-purpose purpose
  12214. org-log-note-state state
  12215. org-log-note-previous-state prev-state
  12216. org-log-note-how how
  12217. org-log-note-extra extra
  12218. org-log-note-effective-time (org-current-effective-time))
  12219. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12220. (defun org-skip-over-state-notes ()
  12221. "Skip past the list of State notes in an entry."
  12222. (when (ignore-errors (goto-char (org-in-item-p)))
  12223. (let* ((struct (org-list-struct))
  12224. (prevs (org-list-prevs-alist struct))
  12225. (regexp
  12226. (concat "[ \t]*- +"
  12227. (replace-regexp-in-string
  12228. " +" " +"
  12229. (org-replace-escapes
  12230. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12231. `(("%d" . ,org-ts-regexp-inactive)
  12232. ("%D" . ,org-ts-regexp)
  12233. ("%s" . "\"\\S-+\"")
  12234. ("%S" . "\"\\S-+\"")
  12235. ("%t" . ,org-ts-regexp-inactive)
  12236. ("%T" . ,org-ts-regexp)
  12237. ("%u" . ".*?")
  12238. ("%U" . ".*?")))))))
  12239. (while (looking-at-p regexp)
  12240. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12241. (org-list-get-item-end (point) struct)))))))
  12242. (defun org-add-log-note (&optional _purpose)
  12243. "Pop up a window for taking a note, and add this note later."
  12244. (remove-hook 'post-command-hook 'org-add-log-note)
  12245. (setq org-log-note-window-configuration (current-window-configuration))
  12246. (delete-other-windows)
  12247. (move-marker org-log-note-return-to (point))
  12248. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12249. (goto-char org-log-note-marker)
  12250. (org-switch-to-buffer-other-window "*Org Note*")
  12251. (erase-buffer)
  12252. (if (memq org-log-note-how '(time state))
  12253. (org-store-log-note)
  12254. (let ((org-inhibit-startup t)) (org-mode))
  12255. (insert (format "# Insert note for %s.
  12256. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12257. (cond
  12258. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12259. ((eq org-log-note-purpose 'done) "closed todo item")
  12260. ((eq org-log-note-purpose 'state)
  12261. (format "state change from \"%s\" to \"%s\""
  12262. (or org-log-note-previous-state "")
  12263. (or org-log-note-state "")))
  12264. ((eq org-log-note-purpose 'reschedule)
  12265. "rescheduling")
  12266. ((eq org-log-note-purpose 'delschedule)
  12267. "no longer scheduled")
  12268. ((eq org-log-note-purpose 'redeadline)
  12269. "changing deadline")
  12270. ((eq org-log-note-purpose 'deldeadline)
  12271. "removing deadline")
  12272. ((eq org-log-note-purpose 'refile)
  12273. "refiling")
  12274. ((eq org-log-note-purpose 'note)
  12275. "this entry")
  12276. (t (error "This should not happen")))))
  12277. (when org-log-note-extra (insert org-log-note-extra))
  12278. (setq-local org-finish-function 'org-store-log-note)
  12279. (run-hooks 'org-log-buffer-setup-hook)))
  12280. (defvar org-note-abort nil) ; dynamically scoped
  12281. (defun org-store-log-note ()
  12282. "Finish taking a log note, and insert it to where it belongs."
  12283. (let ((txt (prog1 (buffer-string)
  12284. (kill-buffer)))
  12285. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12286. lines)
  12287. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12288. (setq txt (replace-match "" t t txt)))
  12289. (when (string-match "\\s-+\\'" txt)
  12290. (setq txt (replace-match "" t t txt)))
  12291. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  12292. (when (org-string-nw-p note)
  12293. (setq note
  12294. (org-replace-escapes
  12295. note
  12296. (list (cons "%u" (user-login-name))
  12297. (cons "%U" user-full-name)
  12298. (cons "%t" (format-time-string
  12299. (org-time-stamp-format 'long 'inactive)
  12300. org-log-note-effective-time))
  12301. (cons "%T" (format-time-string
  12302. (org-time-stamp-format 'long nil)
  12303. org-log-note-effective-time))
  12304. (cons "%d" (format-time-string
  12305. (org-time-stamp-format nil 'inactive)
  12306. org-log-note-effective-time))
  12307. (cons "%D" (format-time-string
  12308. (org-time-stamp-format nil nil)
  12309. org-log-note-effective-time))
  12310. (cons "%s" (cond
  12311. ((not org-log-note-state) "")
  12312. ((string-match-p org-ts-regexp
  12313. org-log-note-state)
  12314. (format "\"[%s]\""
  12315. (substring org-log-note-state 1 -1)))
  12316. (t (format "\"%s\"" org-log-note-state))))
  12317. (cons "%S"
  12318. (cond
  12319. ((not org-log-note-previous-state) "")
  12320. ((string-match-p org-ts-regexp
  12321. org-log-note-previous-state)
  12322. (format "\"[%s]\""
  12323. (substring
  12324. org-log-note-previous-state 1 -1)))
  12325. (t (format "\"%s\""
  12326. org-log-note-previous-state)))))))
  12327. (when lines (setq note (concat note " \\\\")))
  12328. (push note lines))
  12329. (when (and lines (not org-note-abort))
  12330. (with-current-buffer (marker-buffer org-log-note-marker)
  12331. (org-with-wide-buffer
  12332. ;; Find location for the new note.
  12333. (goto-char org-log-note-marker)
  12334. (set-marker org-log-note-marker nil)
  12335. ;; Note associated to a clock is to be located right after
  12336. ;; the clock. Do not move point.
  12337. (unless (eq org-log-note-purpose 'clock-out)
  12338. (goto-char (org-log-beginning t)))
  12339. ;; Make sure point is at the beginning of an empty line.
  12340. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12341. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12342. ;; In an existing list, add a new item at the top level.
  12343. ;; Otherwise, indent line like a regular one.
  12344. (let ((itemp (org-in-item-p)))
  12345. (if itemp
  12346. (indent-line-to
  12347. (let ((struct (save-excursion
  12348. (goto-char itemp) (org-list-struct))))
  12349. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12350. (org-indent-line)))
  12351. (insert (org-list-bullet-string "-") (pop lines))
  12352. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12353. (dolist (line lines)
  12354. (insert "\n")
  12355. (indent-line-to ind)
  12356. (insert line)))
  12357. (message "Note stored")
  12358. (org-back-to-heading t)
  12359. (org-cycle-hide-drawers 'children))
  12360. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12361. ;; from within `org-add-log-note' because `buffer-undo-list'
  12362. ;; is then modified outside of `org-with-remote-undo'.
  12363. (when (eq this-command 'org-agenda-todo)
  12364. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12365. ;; Don't add undo information when called from `org-agenda-todo'.
  12366. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12367. (set-window-configuration org-log-note-window-configuration)
  12368. (with-current-buffer (marker-buffer org-log-note-return-to)
  12369. (goto-char org-log-note-return-to))
  12370. (move-marker org-log-note-return-to nil)
  12371. (when org-log-post-message (message "%s" org-log-post-message))))
  12372. (defun org-remove-empty-drawer-at (pos)
  12373. "Remove an empty drawer at position POS.
  12374. POS may also be a marker."
  12375. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12376. (org-with-wide-buffer
  12377. (goto-char pos)
  12378. (let ((drawer (org-element-at-point)))
  12379. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12380. (not (org-element-property :contents-begin drawer)))
  12381. (delete-region (org-element-property :begin drawer)
  12382. (progn (goto-char (org-element-property :end drawer))
  12383. (skip-chars-backward " \r\t\n")
  12384. (forward-line)
  12385. (point))))))))
  12386. (defvar org-ts-type nil)
  12387. (defun org-sparse-tree (&optional arg type)
  12388. "Create a sparse tree, prompt for the details.
  12389. This command can create sparse trees. You first need to select the type
  12390. of match used to create the tree:
  12391. t Show all TODO entries.
  12392. T Show entries with a specific TODO keyword.
  12393. m Show entries selected by a tags/property match.
  12394. p Enter a property name and its value (both with completion on existing
  12395. names/values) and show entries with that property.
  12396. r Show entries matching a regular expression (`/' can be used as well).
  12397. b Show deadlines and scheduled items before a date.
  12398. a Show deadlines and scheduled items after a date.
  12399. d Show deadlines due within `org-deadline-warning-days'.
  12400. D Show deadlines and scheduled items between a date range."
  12401. (interactive "P")
  12402. (setq type (or type org-sparse-tree-default-date-type))
  12403. (setq org-ts-type type)
  12404. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12405. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12406. \[c]ycle through date types: %s"
  12407. (cl-case type
  12408. (all "all timestamps")
  12409. (scheduled "only scheduled")
  12410. (deadline "only deadline")
  12411. (active "only active timestamps")
  12412. (inactive "only inactive timestamps")
  12413. (closed "with a closed time-stamp")
  12414. (otherwise "scheduled/deadline")))
  12415. (let ((answer (read-char-exclusive)))
  12416. (cl-case answer
  12417. (?c
  12418. (org-sparse-tree
  12419. arg
  12420. (cadr
  12421. (memq type '(nil all scheduled deadline active inactive closed)))))
  12422. (?d (call-interactively 'org-check-deadlines))
  12423. (?b (call-interactively 'org-check-before-date))
  12424. (?a (call-interactively 'org-check-after-date))
  12425. (?D (call-interactively 'org-check-dates-range))
  12426. (?t (call-interactively 'org-show-todo-tree))
  12427. (?T (org-show-todo-tree '(4)))
  12428. (?m (call-interactively 'org-match-sparse-tree))
  12429. ((?p ?P)
  12430. (let* ((kwd (completing-read
  12431. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12432. (value (completing-read
  12433. "Value: " (mapcar #'list (org-property-values kwd)))))
  12434. (unless (string-match "\\`{.*}\\'" value)
  12435. (setq value (concat "\"" value "\"")))
  12436. (org-match-sparse-tree arg (concat kwd "=" value))))
  12437. ((?r ?R ?/) (call-interactively 'org-occur))
  12438. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12439. (defvar-local org-occur-highlights nil
  12440. "List of overlays used for occur matches.")
  12441. (defvar-local org-occur-parameters nil
  12442. "Parameters of the active org-occur calls.
  12443. This is a list, each call to org-occur pushes as cons cell,
  12444. containing the regular expression and the callback, onto the list.
  12445. The list can contain several entries if `org-occur' has been called
  12446. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12447. will only contain one set of parameters. When the highlights are
  12448. removed (for example with `C-c C-c', or with the next edit (depending
  12449. on `org-remove-highlights-with-change'), this variable is emptied
  12450. as well.")
  12451. (defun org-occur (regexp &optional keep-previous callback)
  12452. "Make a compact tree which shows all matches of REGEXP.
  12453. The tree will show the lines where the regexp matches, and any other context
  12454. defined in `org-show-context-detail', which see.
  12455. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12456. done by a previous call to `org-occur' will be kept, to allow stacking of
  12457. calls to this command.
  12458. Optional argument CALLBACK can be a function of no argument. In this case,
  12459. it is called with point at the end of the match, match data being set
  12460. accordingly. Current match is shown only if the return value is non-nil.
  12461. The function must neither move point nor alter narrowing."
  12462. (interactive "sRegexp: \nP")
  12463. (when (equal regexp "")
  12464. (user-error "Regexp cannot be empty"))
  12465. (unless keep-previous
  12466. (org-remove-occur-highlights nil nil t))
  12467. (push (cons regexp callback) org-occur-parameters)
  12468. (let ((cnt 0))
  12469. (save-excursion
  12470. (goto-char (point-min))
  12471. (when (or (not keep-previous) ; do not want to keep
  12472. (not org-occur-highlights)) ; no previous matches
  12473. ;; hide everything
  12474. (org-overview))
  12475. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12476. (isearch-no-upper-case-p regexp t)
  12477. org-occur-case-fold-search)))
  12478. (while (re-search-forward regexp nil t)
  12479. (when (or (not callback)
  12480. (save-match-data (funcall callback)))
  12481. (setq cnt (1+ cnt))
  12482. (when org-highlight-sparse-tree-matches
  12483. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12484. (org-show-context 'occur-tree)))))
  12485. (when org-remove-highlights-with-change
  12486. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12487. nil 'local))
  12488. (unless org-sparse-tree-open-archived-trees
  12489. (org-hide-archived-subtrees (point-min) (point-max)))
  12490. (run-hooks 'org-occur-hook)
  12491. (when (called-interactively-p 'interactive)
  12492. (message "%d match(es) for regexp %s" cnt regexp))
  12493. cnt))
  12494. (defun org-occur-next-match (&optional n _reset)
  12495. "Function for `next-error-function' to find sparse tree matches.
  12496. N is the number of matches to move, when negative move backwards.
  12497. This function always goes back to the starting point when no
  12498. match is found."
  12499. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12500. (search-func (if (< n 0)
  12501. 'previous-single-char-property-change
  12502. 'next-single-char-property-change))
  12503. (n (abs n))
  12504. (pos (point))
  12505. p1)
  12506. (catch 'exit
  12507. (while (setq p1 (funcall search-func (point) 'org-type))
  12508. (when (equal p1 limit)
  12509. (goto-char pos)
  12510. (user-error "No more matches"))
  12511. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12512. (setq n (1- n))
  12513. (when (= n 0)
  12514. (goto-char p1)
  12515. (throw 'exit (point))))
  12516. (goto-char p1))
  12517. (goto-char p1)
  12518. (user-error "No more matches"))))
  12519. (defun org-show-context (&optional key)
  12520. "Make sure point and context are visible.
  12521. Optional argument KEY, when non-nil, is a symbol. See
  12522. `org-show-context-detail' for allowed values and how much is to
  12523. be shown."
  12524. (org-show-set-visibility
  12525. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12526. ((cdr (assq key org-show-context-detail)))
  12527. (t (cdr (assq 'default org-show-context-detail))))))
  12528. (defun org-show-set-visibility (detail)
  12529. "Set visibility around point according to DETAIL.
  12530. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12531. `tree', `canonical' or t. See `org-show-context-detail' for more
  12532. information."
  12533. ;; Show current heading and possibly its entry, following headline
  12534. ;; or all children.
  12535. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12536. (org-flag-heading nil)
  12537. (org-show-entry)
  12538. ;; If point is hidden within a drawer or a block, make sure to
  12539. ;; expose it.
  12540. (dolist (o (overlays-at (point)))
  12541. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12542. (delete-overlay o)))
  12543. (unless (org-before-first-heading-p)
  12544. (org-with-limited-levels
  12545. (cl-case detail
  12546. ((tree canonical t) (org-show-children))
  12547. ((nil minimal ancestors))
  12548. (t (save-excursion
  12549. (outline-next-heading)
  12550. (org-flag-heading nil)))))))
  12551. ;; Show all siblings.
  12552. (when (eq detail 'lineage) (org-show-siblings))
  12553. ;; Show ancestors, possibly with their children.
  12554. (when (memq detail '(ancestors lineage tree canonical t))
  12555. (save-excursion
  12556. (while (org-up-heading-safe)
  12557. (org-flag-heading nil)
  12558. (when (memq detail '(canonical t)) (org-show-entry))
  12559. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12560. (defvar org-reveal-start-hook nil
  12561. "Hook run before revealing a location.")
  12562. (defun org-reveal (&optional siblings)
  12563. "Show current entry, hierarchy above it, and the following headline.
  12564. This can be used to show a consistent set of context around
  12565. locations exposed with `org-show-context'.
  12566. With optional argument SIBLINGS, on each level of the hierarchy all
  12567. siblings are shown. This repairs the tree structure to what it would
  12568. look like when opened with hierarchical calls to `org-cycle'.
  12569. With a \\[universal-argument] \\[universal-argument] prefix, \
  12570. go to the parent and show the entire tree."
  12571. (interactive "P")
  12572. (run-hooks 'org-reveal-start-hook)
  12573. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12574. ((equal siblings '(16))
  12575. (save-excursion
  12576. (when (org-up-heading-safe)
  12577. (org-show-subtree)
  12578. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12579. (t (org-show-set-visibility 'lineage))))
  12580. (defun org-highlight-new-match (beg end)
  12581. "Highlight from BEG to END and mark the highlight is an occur headline."
  12582. (let ((ov (make-overlay beg end)))
  12583. (overlay-put ov 'face 'secondary-selection)
  12584. (overlay-put ov 'org-type 'org-occur)
  12585. (push ov org-occur-highlights)))
  12586. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12587. "Remove the occur highlights from the buffer.
  12588. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12589. from the `before-change-functions' in the current buffer."
  12590. (interactive)
  12591. (unless org-inhibit-highlight-removal
  12592. (mapc #'delete-overlay org-occur-highlights)
  12593. (setq org-occur-highlights nil)
  12594. (setq org-occur-parameters nil)
  12595. (unless noremove
  12596. (remove-hook 'before-change-functions
  12597. 'org-remove-occur-highlights 'local))))
  12598. ;;;; Priorities
  12599. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12600. "Regular expression matching the priority indicator.")
  12601. (defvar org-remove-priority-next-time nil)
  12602. (defun org-priority-up ()
  12603. "Increase the priority of the current item."
  12604. (interactive)
  12605. (org-priority 'up))
  12606. (defun org-priority-down ()
  12607. "Decrease the priority of the current item."
  12608. (interactive)
  12609. (org-priority 'down))
  12610. (defun org-priority (&optional action _show)
  12611. "Change the priority of an item.
  12612. ACTION can be `set', `up', `down', or a character."
  12613. (interactive "P")
  12614. (if (equal action '(4))
  12615. (org-show-priority)
  12616. (unless org-enable-priority-commands
  12617. (user-error "Priority commands are disabled"))
  12618. (setq action (or action 'set))
  12619. (let (current new news have remove)
  12620. (save-excursion
  12621. (org-back-to-heading t)
  12622. (when (looking-at org-priority-regexp)
  12623. (setq current (string-to-char (match-string 2))
  12624. have t))
  12625. (cond
  12626. ((eq action 'remove)
  12627. (setq remove t new ?\ ))
  12628. ((or (eq action 'set)
  12629. (integerp action))
  12630. (if (not (eq action 'set))
  12631. (setq new action)
  12632. (message "Priority %c-%c, SPC to remove: "
  12633. org-highest-priority org-lowest-priority)
  12634. (save-match-data
  12635. (setq new (read-char-exclusive))))
  12636. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12637. (= (upcase org-lowest-priority) org-lowest-priority))
  12638. (setq new (upcase new)))
  12639. (cond ((equal new ?\ ) (setq remove t))
  12640. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12641. (user-error "Priority must be between `%c' and `%c'"
  12642. org-highest-priority org-lowest-priority))))
  12643. ((eq action 'up)
  12644. (setq new (if have
  12645. (1- current) ; normal cycling
  12646. ;; last priority was empty
  12647. (if (eq last-command this-command)
  12648. org-lowest-priority ; wrap around empty to lowest
  12649. ;; default
  12650. (if org-priority-start-cycle-with-default
  12651. org-default-priority
  12652. (1- org-default-priority))))))
  12653. ((eq action 'down)
  12654. (setq new (if have
  12655. (1+ current) ; normal cycling
  12656. ;; last priority was empty
  12657. (if (eq last-command this-command)
  12658. org-highest-priority ; wrap around empty to highest
  12659. ;; default
  12660. (if org-priority-start-cycle-with-default
  12661. org-default-priority
  12662. (1+ org-default-priority))))))
  12663. (t (user-error "Invalid action")))
  12664. (when (or (< (upcase new) org-highest-priority)
  12665. (> (upcase new) org-lowest-priority))
  12666. (if (and (memq action '(up down))
  12667. (not have) (not (eq last-command this-command)))
  12668. ;; `new' is from default priority
  12669. (error
  12670. "The default can not be set, see `org-default-priority' why")
  12671. ;; normal cycling: `new' is beyond highest/lowest priority
  12672. ;; and is wrapped around to the empty priority
  12673. (setq remove t)))
  12674. (setq news (format "%c" new))
  12675. (if have
  12676. (if remove
  12677. (replace-match "" t t nil 1)
  12678. (replace-match news t t nil 2))
  12679. (if remove
  12680. (user-error "No priority cookie found in line")
  12681. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12682. (if (match-end 2)
  12683. (progn
  12684. (goto-char (match-end 2))
  12685. (insert " [#" news "]"))
  12686. (goto-char (match-beginning 3))
  12687. (insert "[#" news "] "))))
  12688. (org-set-tags nil 'align))
  12689. (if remove
  12690. (message "Priority removed")
  12691. (message "Priority of current item set to %s" news)))))
  12692. (defun org-show-priority ()
  12693. "Show the priority of the current item.
  12694. This priority is composed of the main priority given with the [#A] cookies,
  12695. and by additional input from the age of a schedules or deadline entry."
  12696. (interactive)
  12697. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12698. (org-get-at-bol 'priority)
  12699. (save-excursion
  12700. (save-match-data
  12701. (beginning-of-line)
  12702. (and (looking-at org-heading-regexp)
  12703. (org-get-priority (match-string 0))))))))
  12704. (message "Priority is %d" (if pri pri -1000))))
  12705. (defun org-get-priority (s)
  12706. "Find priority cookie and return priority."
  12707. (save-match-data
  12708. (if (functionp org-get-priority-function)
  12709. (funcall org-get-priority-function)
  12710. (if (not (string-match org-priority-regexp s))
  12711. (* 1000 (- org-lowest-priority org-default-priority))
  12712. (* 1000 (- org-lowest-priority
  12713. (string-to-char (match-string 2 s))))))))
  12714. ;;;; Tags
  12715. (defvar org-agenda-archives-mode)
  12716. (defvar org-map-continue-from nil
  12717. "Position from where mapping should continue.
  12718. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12719. (defvar org-scanner-tags nil
  12720. "The current tag list while the tags scanner is running.")
  12721. (defvar org-trust-scanner-tags nil
  12722. "Should `org-get-tags-at' use the tags for the scanner.
  12723. This is for internal dynamical scoping only.
  12724. When this is non-nil, the function `org-get-tags-at' will return the value
  12725. of `org-scanner-tags' instead of building the list by itself. This
  12726. can lead to large speed-ups when the tags scanner is used in a file with
  12727. many entries, and when the list of tags is retrieved, for example to
  12728. obtain a list of properties. Building the tags list for each entry in such
  12729. a file becomes an N^2 operation - but with this variable set, it scales
  12730. as N.")
  12731. (defvar org--matcher-tags-todo-only nil)
  12732. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12733. "Scan headline tags with inheritance and produce output ACTION.
  12734. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12735. or `agenda' to produce an entry list for an agenda view. It can also be
  12736. a Lisp form or a function that should be called at each matched headline, in
  12737. this case the return value is a list of all return values from these calls.
  12738. MATCHER is a function accepting three arguments, returning
  12739. a non-nil value whenever a given set of tags qualifies a headline
  12740. for inclusion. See `org-make-tags-matcher' for more information.
  12741. As a special case, it can also be set to t (respectively nil) in
  12742. order to match all (respectively none) headline.
  12743. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  12744. included in the output.
  12745. START-LEVEL can be a string with asterisks, reducing the scope to
  12746. headlines matching this string."
  12747. (require 'org-agenda)
  12748. (let* ((re (concat "^"
  12749. (if start-level
  12750. ;; Get the correct level to match
  12751. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12752. org-outline-regexp)
  12753. " *\\(\\<\\("
  12754. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12755. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12756. (props (list 'face 'default
  12757. 'done-face 'org-agenda-done
  12758. 'undone-face 'default
  12759. 'mouse-face 'highlight
  12760. 'org-not-done-regexp org-not-done-regexp
  12761. 'org-todo-regexp org-todo-regexp
  12762. 'org-complex-heading-regexp org-complex-heading-regexp
  12763. 'help-echo
  12764. (format "mouse-2 or RET jump to org file %s"
  12765. (abbreviate-file-name
  12766. (or (buffer-file-name (buffer-base-buffer))
  12767. (buffer-name (buffer-base-buffer)))))))
  12768. (org-map-continue-from nil)
  12769. lspos tags tags-list
  12770. (tags-alist (list (cons 0 org-file-tags)))
  12771. (llast 0) rtn rtn1 level category i txt
  12772. todo marker entry priority
  12773. ts-date ts-date-type ts-date-pair)
  12774. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12775. (setq action (list 'lambda nil action)))
  12776. (save-excursion
  12777. (goto-char (point-min))
  12778. (when (eq action 'sparse-tree)
  12779. (org-overview)
  12780. (org-remove-occur-highlights))
  12781. (while (let (case-fold-search)
  12782. (re-search-forward re nil t))
  12783. (setq org-map-continue-from nil)
  12784. (catch :skip
  12785. (setq todo
  12786. ;; TODO: is the 1-2 difference a bug?
  12787. (when (match-end 1) (match-string-no-properties 2))
  12788. tags (when (match-end 4) (match-string-no-properties 4)))
  12789. (goto-char (setq lspos (match-beginning 0)))
  12790. (setq level (org-reduced-level (org-outline-level))
  12791. category (org-get-category))
  12792. (when (eq action 'agenda)
  12793. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12794. ts-date (car ts-date-pair)
  12795. ts-date-type (cdr ts-date-pair)))
  12796. (setq i llast llast level)
  12797. ;; remove tag lists from same and sublevels
  12798. (while (>= i level)
  12799. (when (setq entry (assoc i tags-alist))
  12800. (setq tags-alist (delete entry tags-alist)))
  12801. (setq i (1- i)))
  12802. ;; add the next tags
  12803. (when tags
  12804. (setq tags (org-split-string tags ":")
  12805. tags-alist
  12806. (cons (cons level tags) tags-alist)))
  12807. ;; compile tags for current headline
  12808. (setq tags-list
  12809. (if org-use-tag-inheritance
  12810. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12811. tags)
  12812. org-scanner-tags tags-list)
  12813. (when org-use-tag-inheritance
  12814. (setcdr (car tags-alist)
  12815. (mapcar (lambda (x)
  12816. (setq x (copy-sequence x))
  12817. (org-add-prop-inherited x))
  12818. (cdar tags-alist))))
  12819. (when (and tags org-use-tag-inheritance
  12820. (or (not (eq t org-use-tag-inheritance))
  12821. org-tags-exclude-from-inheritance))
  12822. ;; Selective inheritance, remove uninherited ones.
  12823. (setcdr (car tags-alist)
  12824. (org-remove-uninherited-tags (cdar tags-alist))))
  12825. (when (and
  12826. ;; eval matcher only when the todo condition is OK
  12827. (and (or (not todo-only) (member todo org-todo-keywords-1))
  12828. (if (functionp matcher)
  12829. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12830. (funcall matcher todo tags-list level))
  12831. matcher))
  12832. ;; Call the skipper, but return t if it does not
  12833. ;; skip, so that the `and' form continues evaluating.
  12834. (progn
  12835. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12836. t)
  12837. ;; Check if timestamps are deselecting this entry
  12838. (or (not todo-only)
  12839. (and (member todo org-todo-keywords-1)
  12840. (or (not org-agenda-tags-todo-honor-ignore-options)
  12841. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12842. ;; select this headline
  12843. (cond
  12844. ((eq action 'sparse-tree)
  12845. (and org-highlight-sparse-tree-matches
  12846. (org-get-heading) (match-end 0)
  12847. (org-highlight-new-match
  12848. (match-beginning 1) (match-end 1)))
  12849. (org-show-context 'tags-tree))
  12850. ((eq action 'agenda)
  12851. (setq txt (org-agenda-format-item
  12852. ""
  12853. (concat
  12854. (if (eq org-tags-match-list-sublevels 'indented)
  12855. (make-string (1- level) ?.) "")
  12856. (org-get-heading))
  12857. (make-string level ?\s)
  12858. category
  12859. tags-list)
  12860. priority (org-get-priority txt))
  12861. (goto-char lspos)
  12862. (setq marker (org-agenda-new-marker))
  12863. (org-add-props txt props
  12864. 'org-marker marker 'org-hd-marker marker 'org-category category
  12865. 'todo-state todo
  12866. 'ts-date ts-date
  12867. 'priority priority
  12868. 'type (concat "tagsmatch" ts-date-type))
  12869. (push txt rtn))
  12870. ((functionp action)
  12871. (setq org-map-continue-from nil)
  12872. (save-excursion
  12873. (setq rtn1 (funcall action))
  12874. (push rtn1 rtn)))
  12875. (t (user-error "Invalid action")))
  12876. ;; if we are to skip sublevels, jump to end of subtree
  12877. (unless org-tags-match-list-sublevels
  12878. (org-end-of-subtree t)
  12879. (backward-char 1))))
  12880. ;; Get the correct position from where to continue
  12881. (if org-map-continue-from
  12882. (goto-char org-map-continue-from)
  12883. (and (= (point) lspos) (end-of-line 1)))))
  12884. (when (and (eq action 'sparse-tree)
  12885. (not org-sparse-tree-open-archived-trees))
  12886. (org-hide-archived-subtrees (point-min) (point-max)))
  12887. (nreverse rtn)))
  12888. (defun org-remove-uninherited-tags (tags)
  12889. "Remove all tags that are not inherited from the list TAGS."
  12890. (cond
  12891. ((eq org-use-tag-inheritance t)
  12892. (if org-tags-exclude-from-inheritance
  12893. (org-delete-all org-tags-exclude-from-inheritance tags)
  12894. tags))
  12895. ((not org-use-tag-inheritance) nil)
  12896. ((stringp org-use-tag-inheritance)
  12897. (delq nil (mapcar
  12898. (lambda (x)
  12899. (if (and (string-match org-use-tag-inheritance x)
  12900. (not (member x org-tags-exclude-from-inheritance)))
  12901. x nil))
  12902. tags)))
  12903. ((listp org-use-tag-inheritance)
  12904. (delq nil (mapcar
  12905. (lambda (x)
  12906. (if (member x org-use-tag-inheritance) x nil))
  12907. tags)))))
  12908. (defun org-match-sparse-tree (&optional todo-only match)
  12909. "Create a sparse tree according to tags string MATCH.
  12910. MATCH is a string with match syntax. It can contain a selection
  12911. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12912. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12913. those. See the manual for details.
  12914. If optional argument TODO-ONLY is non-nil, only select lines that
  12915. are also TODO tasks."
  12916. (interactive "P")
  12917. (org-agenda-prepare-buffers (list (current-buffer)))
  12918. (let ((org--matcher-tags-todo-only todo-only))
  12919. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12920. org--matcher-tags-todo-only)))
  12921. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12922. (defvar org-cached-props nil)
  12923. (defun org-cached-entry-get (pom property)
  12924. (if (or (eq t org-use-property-inheritance)
  12925. (and (stringp org-use-property-inheritance)
  12926. (let ((case-fold-search t))
  12927. (string-match-p org-use-property-inheritance property)))
  12928. (and (listp org-use-property-inheritance)
  12929. (member-ignore-case property org-use-property-inheritance)))
  12930. ;; Caching is not possible, check it directly.
  12931. (org-entry-get pom property 'inherit)
  12932. ;; Get all properties, so we can do complicated checks easily.
  12933. (cdr (assoc-string property
  12934. (or org-cached-props
  12935. (setq org-cached-props (org-entry-properties pom)))
  12936. t))))
  12937. (defun org-global-tags-completion-table (&optional files)
  12938. "Return the list of all tags in all agenda buffer/files.
  12939. Optional FILES argument is a list of files which can be used
  12940. instead of the agenda files."
  12941. (save-excursion
  12942. (org-uniquify
  12943. (delq nil
  12944. (apply #'append
  12945. (mapcar
  12946. (lambda (file)
  12947. (set-buffer (find-file-noselect file))
  12948. (mapcar (lambda (x)
  12949. (and (stringp (car-safe x))
  12950. (list (car-safe x))))
  12951. (or org-current-tag-alist (org-get-buffer-tags))))
  12952. (if (car-safe files) files
  12953. (org-agenda-files))))))))
  12954. (defun org-make-tags-matcher (match)
  12955. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12956. Returns a cons of the selection string MATCH and a function
  12957. implementing the matcher.
  12958. The matcher is to be called at an Org entry, with point on the
  12959. headline, and returns non-nil if the entry matches the selection
  12960. string MATCH. It must be called with three arguments: the TODO
  12961. keyword at the entry (or nil if none), the list of all tags at
  12962. the entry including inherited ones and the reduced level of the
  12963. headline. Additionally, the category of the entry, if any, must
  12964. be specified as the text property `org-category' on the headline.
  12965. This function sets the variable `org--matcher-tags-todo-only' to
  12966. a non-nil value if the matcher restricts matching to TODO
  12967. entries, otherwise it is not touched.
  12968. See also `org-scan-tags'."
  12969. (unless match
  12970. ;; Get a new match request, with completion against the global
  12971. ;; tags table and the local tags in current buffer.
  12972. (let ((org-last-tags-completion-table
  12973. (org-uniquify
  12974. (delq nil (append (org-get-buffer-tags)
  12975. (org-global-tags-completion-table))))))
  12976. (setq match
  12977. (completing-read
  12978. "Match: "
  12979. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12980. (let ((match0 match)
  12981. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12982. (start 0)
  12983. tagsmatch todomatch tagsmatcher todomatcher)
  12984. ;; Expand group tags.
  12985. (setq match (org-tags-expand match))
  12986. ;; Check if there is a TODO part of this match, which would be the
  12987. ;; part after a "/". To make sure that this slash is not part of
  12988. ;; a property value to be matched against, we also check that
  12989. ;; there is no / after that slash. First, find the last slash.
  12990. (let ((s 0))
  12991. (while (string-match "/+" match s)
  12992. (setq start (match-beginning 0))
  12993. (setq s (match-end 0))))
  12994. (if (and (string-match "/+" match start)
  12995. (not (string-match-p "\"" match start)))
  12996. ;; Match contains also a TODO-matching request.
  12997. (progn
  12998. (setq tagsmatch (substring match 0 (match-beginning 0)))
  12999. (setq todomatch (substring match (match-end 0)))
  13000. (when (string-prefix-p "!" todomatch)
  13001. (setq org--matcher-tags-todo-only t)
  13002. (setq todomatch (substring todomatch 1)))
  13003. (when (string-match "\\`\\s-*\\'" todomatch)
  13004. (setq todomatch nil)))
  13005. ;; Only matching tags.
  13006. (setq tagsmatch match)
  13007. (setq todomatch nil))
  13008. ;; Make the tags matcher.
  13009. (when (org-string-nw-p tagsmatch)
  13010. (let ((orlist nil)
  13011. (orterms (org-split-string tagsmatch "|"))
  13012. term)
  13013. (while (setq term (pop orterms))
  13014. (while (and (equal (substring term -1) "\\") orterms)
  13015. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13016. (while (string-match re term)
  13017. (let* ((rest (substring term (match-end 0)))
  13018. (minus (and (match-end 1)
  13019. (equal (match-string 1 term) "-")))
  13020. (tag (save-match-data
  13021. (replace-regexp-in-string
  13022. "\\\\-" "-" (match-string 2 term))))
  13023. (regexp (eq (string-to-char tag) ?{))
  13024. (levelp (match-end 4))
  13025. (propp (match-end 5))
  13026. (mm
  13027. (cond
  13028. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13029. (levelp
  13030. `(,(org-op-to-function (match-string 3 term))
  13031. level
  13032. ,(string-to-number (match-string 4 term))))
  13033. (propp
  13034. (let* ((gv (pcase (upcase (match-string 5 term))
  13035. ("CATEGORY"
  13036. '(get-text-property (point) 'org-category))
  13037. ("TODO" 'todo)
  13038. (p `(org-cached-entry-get nil ,p))))
  13039. (pv (match-string 7 term))
  13040. (regexp (eq (string-to-char pv) ?{))
  13041. (strp (eq (string-to-char pv) ?\"))
  13042. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13043. (po (org-op-to-function (match-string 6 term)
  13044. (if timep 'time strp))))
  13045. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13046. (when timep (setq pv (org-matcher-time pv)))
  13047. (cond ((and regexp (eq po 'org<>))
  13048. `(not (string-match ,pv (or ,gv ""))))
  13049. (regexp `(string-match ,pv (or ,gv "")))
  13050. (strp `(,po (or ,gv "") ,pv))
  13051. (t
  13052. `(,po
  13053. (string-to-number (or ,gv ""))
  13054. ,(string-to-number pv))))))
  13055. (t `(member ,tag tags-list)))))
  13056. (push (if minus `(not ,mm) mm) tagsmatcher)
  13057. (setq term rest)))
  13058. (push `(and ,@tagsmatcher) orlist)
  13059. (setq tagsmatcher nil))
  13060. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13061. ;; Make the TODO matcher.
  13062. (when (org-string-nw-p todomatch)
  13063. (let ((orlist nil))
  13064. (dolist (term (org-split-string todomatch "|"))
  13065. (while (string-match re term)
  13066. (let* ((minus (and (match-end 1)
  13067. (equal (match-string 1 term) "-")))
  13068. (kwd (match-string 2 term))
  13069. (regexp (eq (string-to-char kwd) ?{))
  13070. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13071. `(equal todo ,kwd))))
  13072. (push (if minus `(not ,mm) mm) todomatcher))
  13073. (setq term (substring term (match-end 0))))
  13074. (push (if (> (length todomatcher) 1)
  13075. (cons 'and todomatcher)
  13076. (car todomatcher))
  13077. orlist)
  13078. (setq todomatcher nil))
  13079. (setq todomatcher (cons 'or orlist))))
  13080. ;; Return the string and function of the matcher. If no
  13081. ;; tags-specific or todo-specific matcher exists, match
  13082. ;; everything.
  13083. (let ((matcher (if (and tagsmatcher todomatcher)
  13084. `(and ,tagsmatcher ,todomatcher)
  13085. (or tagsmatcher todomatcher t))))
  13086. (when org--matcher-tags-todo-only
  13087. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13088. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13089. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13090. "Expand group tags in MATCH.
  13091. This replaces every group tag in MATCH with a regexp tag search.
  13092. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13093. will be replaced like this:
  13094. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13095. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13096. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13097. Replacing by a regexp preserves the structure of the match.
  13098. E.g., this expansion
  13099. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13100. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13101. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13102. A group tag in MATCH can contain regular expressions of its own.
  13103. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13104. will be replaced like this:
  13105. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13106. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13107. assumed to be a single group tag, and the function will return
  13108. the list of tags in this group.
  13109. When DOWNCASE is non-nil, expand downcased TAGS."
  13110. (if org-group-tags
  13111. (let* ((case-fold-search t)
  13112. (stable org-mode-syntax-table)
  13113. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13114. (taggroups (if downcased
  13115. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13116. taggroups)
  13117. taggroups))
  13118. (taggroups-keys (mapcar #'car taggroups))
  13119. (return-match (if downcased (downcase match) match))
  13120. (count 0)
  13121. (work-already-expanded tags-already-expanded)
  13122. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13123. ;; @ and _ are allowed as word-components in tags.
  13124. (modify-syntax-entry ?@ "w" stable)
  13125. (modify-syntax-entry ?_ "w" stable)
  13126. ;; Temporarily replace regexp-expressions in the match-expression.
  13127. (while (string-match "{.+?}" return-match)
  13128. (cl-incf count)
  13129. (push (match-string 0 return-match) regexps-in-match)
  13130. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13131. (while (and taggroups-keys
  13132. (with-syntax-table stable
  13133. (string-match
  13134. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13135. (regexp-opt taggroups-keys) "\\>\\)")
  13136. return-match)))
  13137. (let* ((dir (match-string 1 return-match))
  13138. (tag (match-string 2 return-match))
  13139. (tag (if downcased (downcase tag) tag)))
  13140. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13141. (member tag work-already-expanded))
  13142. (setq tags-in-group (assoc tag taggroups))
  13143. (push tag work-already-expanded)
  13144. ;; Recursively expand each tag in the group, if the tag hasn't
  13145. ;; already been expanded. Restore the match-data after all recursive calls.
  13146. (save-match-data
  13147. (let (tags-expanded)
  13148. (dolist (x (cdr tags-in-group))
  13149. (if (and (member x taggroups-keys)
  13150. (not (member x work-already-expanded)))
  13151. (setq tags-expanded
  13152. (delete-dups
  13153. (append
  13154. (org-tags-expand x t downcased
  13155. work-already-expanded)
  13156. tags-expanded)))
  13157. (setq tags-expanded
  13158. (append (list x) tags-expanded)))
  13159. (setq work-already-expanded
  13160. (delete-dups
  13161. (append tags-expanded
  13162. work-already-expanded))))
  13163. (setq tags-in-group
  13164. (delete-dups (cons (car tags-in-group)
  13165. tags-expanded)))))
  13166. ;; Filter tag-regexps from tags.
  13167. (setq regexp-in-group-escaped
  13168. (delq nil (mapcar (lambda (x)
  13169. (if (stringp x)
  13170. (and (equal "{" (substring x 0 1))
  13171. (equal "}" (substring x -1))
  13172. x)
  13173. x))
  13174. tags-in-group))
  13175. regexp-in-group
  13176. (mapcar (lambda (x)
  13177. (substring x 1 -1))
  13178. regexp-in-group-escaped)
  13179. tags-in-group
  13180. (delq nil (mapcar (lambda (x)
  13181. (if (stringp x)
  13182. (and (not (equal "{" (substring x 0 1)))
  13183. (not (equal "}" (substring x -1)))
  13184. x)
  13185. x))
  13186. tags-in-group)))
  13187. ;; If single-as-list, do no more in the while-loop.
  13188. (if (not single-as-list)
  13189. (progn
  13190. (when regexp-in-group
  13191. (setq regexp-in-group
  13192. (concat "\\|"
  13193. (mapconcat 'identity regexp-in-group
  13194. "\\|"))))
  13195. (setq tags-in-group
  13196. (concat dir
  13197. "{\\<"
  13198. (regexp-opt tags-in-group)
  13199. "\\>"
  13200. regexp-in-group
  13201. "}"))
  13202. (when (stringp tags-in-group)
  13203. (org-add-props tags-in-group '(grouptag t)))
  13204. (setq return-match
  13205. (replace-match tags-in-group t t return-match)))
  13206. (setq tags-in-group
  13207. (append regexp-in-group-escaped tags-in-group))))
  13208. (setq taggroups-keys (delete tag taggroups-keys))))
  13209. ;; Add the regular expressions back into the match-expression again.
  13210. (while regexps-in-match
  13211. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13212. (pop regexps-in-match)
  13213. return-match t t))
  13214. (cl-decf count))
  13215. (if single-as-list
  13216. (if tags-in-group tags-in-group (list return-match))
  13217. return-match))
  13218. (if single-as-list
  13219. (list (if downcased (downcase match) match))
  13220. match)))
  13221. (defun org-op-to-function (op &optional stringp)
  13222. "Turn an operator into the appropriate function."
  13223. (setq op
  13224. (cond
  13225. ((equal op "<" ) '(< string< org-time<))
  13226. ((equal op ">" ) '(> org-string> org-time>))
  13227. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13228. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13229. ((member op '("=" "==")) '(= string= org-time=))
  13230. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13231. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13232. (defun org<> (a b) (not (= a b)))
  13233. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13234. (defun org-string>= (a b) (not (string< a b)))
  13235. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13236. (defun org-string<> (a b) (not (string= a b)))
  13237. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13238. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13239. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13240. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13241. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13242. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13243. (defun org-2ft (s)
  13244. "Convert S to a floating point time.
  13245. If S is already a number, just return it. If it is a string, parse
  13246. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13247. (cond
  13248. ((numberp s) s)
  13249. ((stringp s)
  13250. (condition-case nil
  13251. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13252. (error 0.)))
  13253. (t 0.)))
  13254. (defun org-time-today ()
  13255. "Time in seconds today at 0:00.
  13256. Returns the float number of seconds since the beginning of the
  13257. epoch to the beginning of today (00:00)."
  13258. (float-time (apply 'encode-time
  13259. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13260. (defun org-matcher-time (s)
  13261. "Interpret a time comparison value."
  13262. (save-match-data
  13263. (cond
  13264. ((string= s "<now>") (float-time))
  13265. ((string= s "<today>") (org-time-today))
  13266. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13267. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13268. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13269. (+ (org-time-today)
  13270. (* (string-to-number (match-string 1 s))
  13271. (cdr (assoc (match-string 2 s)
  13272. '(("d" . 86400.0) ("w" . 604800.0)
  13273. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13274. (t (org-2ft s)))))
  13275. (defun org-match-any-p (re list)
  13276. "Does re match any element of list?"
  13277. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13278. (delq nil list))
  13279. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13280. (defvar org-tags-overlay (make-overlay 1 1))
  13281. (delete-overlay org-tags-overlay)
  13282. (defun org-get-local-tags-at (&optional pos)
  13283. "Get a list of tags defined in the current headline."
  13284. (org-get-tags-at pos 'local))
  13285. (defun org-get-local-tags ()
  13286. "Get a list of tags defined in the current headline."
  13287. (org-get-tags-at nil 'local))
  13288. (defun org-get-tags-at (&optional pos local)
  13289. "Get a list of all headline tags applicable at POS.
  13290. POS defaults to point. If tags are inherited, the list contains
  13291. the targets in the same sequence as the headlines appear, i.e.
  13292. the tags of the current headline come last.
  13293. When LOCAL is non-nil, only return tags from the current headline,
  13294. ignore inherited ones."
  13295. (interactive)
  13296. (if (and org-trust-scanner-tags
  13297. (or (not pos) (equal pos (point)))
  13298. (not local))
  13299. org-scanner-tags
  13300. (let (tags ltags lastpos parent)
  13301. (save-excursion
  13302. (save-restriction
  13303. (widen)
  13304. (goto-char (or pos (point)))
  13305. (save-match-data
  13306. (catch 'done
  13307. (condition-case nil
  13308. (progn
  13309. (org-back-to-heading t)
  13310. (while (not (equal lastpos (point)))
  13311. (setq lastpos (point))
  13312. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13313. (setq ltags (org-split-string
  13314. (match-string-no-properties 1) ":"))
  13315. (when parent
  13316. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13317. (setq tags (append
  13318. (if parent
  13319. (org-remove-uninherited-tags ltags)
  13320. ltags)
  13321. tags)))
  13322. (or org-use-tag-inheritance (throw 'done t))
  13323. (when local (throw 'done t))
  13324. (or (org-up-heading-safe) (error nil))
  13325. (setq parent t)))
  13326. (error nil)))))
  13327. (if local
  13328. tags
  13329. (reverse (delete-dups
  13330. (reverse (append
  13331. (org-remove-uninherited-tags
  13332. org-file-tags)
  13333. tags)))))))))
  13334. (defun org-add-prop-inherited (s)
  13335. (add-text-properties 0 (length s) '(inherited t) s)
  13336. s)
  13337. (defun org-toggle-tag (tag &optional onoff)
  13338. "Toggle the tag TAG for the current line.
  13339. If ONOFF is `on' or `off', don't toggle but set to this state."
  13340. (save-excursion
  13341. (org-back-to-heading t)
  13342. (let ((current
  13343. (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13344. (line-end-position) t)
  13345. (let ((tags (match-string 1)))
  13346. ;; Clear current tags.
  13347. (replace-match "")
  13348. ;; Reverse the tags list so any new tag is appended to
  13349. ;; the current list of tags.
  13350. (nreverse (org-split-string tags ":")))))
  13351. res)
  13352. (pcase onoff
  13353. (`off (setq current (delete tag current)))
  13354. ((or `on (guard (not (member tag current))))
  13355. (setq res t)
  13356. (cl-pushnew tag current :test #'equal))
  13357. (_ (setq current (delete tag current))))
  13358. (end-of-line)
  13359. (if current
  13360. (progn
  13361. (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
  13362. (org-set-tags nil t))
  13363. (delete-horizontal-space))
  13364. (run-hooks 'org-after-tags-change-hook)
  13365. res)))
  13366. (defun org--align-tags-here (to-col)
  13367. "Align tags on the current headline to TO-COL.
  13368. Assume point is on a headline."
  13369. (let ((pos (point)))
  13370. (beginning-of-line)
  13371. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13372. (>= pos (match-beginning 2)))
  13373. ;; No tags or point within tags: do not align.
  13374. (goto-char pos)
  13375. (goto-char (match-beginning 1))
  13376. (let ((shift (max (- (if (>= to-col 0) to-col
  13377. (- (abs to-col) (string-width (match-string 2))))
  13378. (current-column))
  13379. 1)))
  13380. (replace-match (make-string shift ?\s) nil nil nil 1)
  13381. ;; Preserve initial position, if possible. In any case, stop
  13382. ;; before tags.
  13383. (when (< pos (point)) (goto-char pos))))))
  13384. (defun org-set-tags-command (&optional arg just-align)
  13385. "Call the set-tags command for the current entry."
  13386. (interactive "P")
  13387. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13388. (org-set-tags arg just-align)
  13389. (save-excursion
  13390. (unless (and (org-region-active-p)
  13391. org-loop-over-headlines-in-active-region)
  13392. (org-back-to-heading t))
  13393. (org-set-tags arg just-align))))
  13394. (defun org-set-tags-to (data)
  13395. "Set the tags of the current entry to DATA, replacing the current tags.
  13396. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13397. If DATA is nil or the empty string, any tags will be removed."
  13398. (interactive "sTags: ")
  13399. (setq data
  13400. (cond
  13401. ((eq data nil) "")
  13402. ((equal data "") "")
  13403. ((stringp data)
  13404. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13405. ":"))
  13406. ((listp data)
  13407. (concat ":" (mapconcat 'identity data ":") ":"))))
  13408. (when data
  13409. (save-excursion
  13410. (org-back-to-heading t)
  13411. (when (let ((case-fold-search nil))
  13412. (looking-at org-complex-heading-regexp))
  13413. (if (match-end 5)
  13414. (progn
  13415. (goto-char (match-beginning 5))
  13416. (insert data)
  13417. (delete-region (point) (point-at-eol))
  13418. (org-set-tags nil 'align))
  13419. (goto-char (point-at-eol))
  13420. (insert " " data)
  13421. (org-set-tags nil 'align)))
  13422. (beginning-of-line 1)
  13423. (when (looking-at ".*?\\([ \t]+\\)$")
  13424. (delete-region (match-beginning 1) (match-end 1))))))
  13425. (defun org-align-all-tags ()
  13426. "Align the tags in all headings."
  13427. (interactive)
  13428. (save-excursion
  13429. (or (ignore-errors (org-back-to-heading t))
  13430. (outline-next-heading))
  13431. (if (org-at-heading-p)
  13432. (org-set-tags t)
  13433. (message "No headings"))))
  13434. (defvar org-indent-indentation-per-level)
  13435. (defun org-set-tags (&optional arg just-align)
  13436. "Set the tags for the current headline.
  13437. With prefix ARG, realign all tags in headings in the current buffer.
  13438. When JUST-ALIGN is non-nil, only align tags."
  13439. (interactive "P")
  13440. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13441. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13442. 'region-start-level
  13443. 'region))
  13444. org-loop-over-headlines-in-active-region)
  13445. (org-map-entries
  13446. ;; We don't use ARG and JUST-ALIGN here because these args
  13447. ;; are not useful when looping over headlines.
  13448. #'org-set-tags
  13449. org-loop-over-headlines-in-active-region
  13450. cl
  13451. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13452. (let ((org-setting-tags t))
  13453. (if arg
  13454. (save-excursion
  13455. (goto-char (point-min))
  13456. (while (re-search-forward org-outline-regexp-bol nil t)
  13457. (org-set-tags nil t)
  13458. (end-of-line))
  13459. (message "All tags realigned to column %d" org-tags-column))
  13460. (let* ((current (org-get-tags-string))
  13461. (tags
  13462. (if just-align current
  13463. ;; Get a new set of tags from the user.
  13464. (save-excursion
  13465. (let* ((seen)
  13466. (table
  13467. (setq
  13468. org-last-tags-completion-table
  13469. ;; Uniquify tags in alists, yet preserve
  13470. ;; structure (i.e., keywords).
  13471. (delq nil
  13472. (mapcar
  13473. (lambda (pair)
  13474. (let ((head (car pair)))
  13475. (cond ((symbolp head) pair)
  13476. ((member head seen) nil)
  13477. (t (push head seen)
  13478. pair))))
  13479. (append
  13480. (or org-current-tag-alist
  13481. (org-get-buffer-tags))
  13482. (and
  13483. org-complete-tags-always-offer-all-agenda-tags
  13484. (org-global-tags-completion-table
  13485. (org-agenda-files))))))))
  13486. (current-tags (org-split-string current ":"))
  13487. (inherited-tags
  13488. (nreverse (nthcdr (length current-tags)
  13489. (nreverse (org-get-tags-at))))))
  13490. (replace-regexp-in-string
  13491. "\\([-+&]+\\|,\\)"
  13492. ":"
  13493. (if (or (eq t org-use-fast-tag-selection)
  13494. (and org-use-fast-tag-selection
  13495. (delq nil (mapcar #'cdr table))))
  13496. (org-fast-tag-selection
  13497. current-tags inherited-tags table
  13498. (and org-fast-tag-selection-include-todo
  13499. org-todo-key-alist))
  13500. (let ((org-add-colon-after-tag-completion
  13501. (< 1 (length table))))
  13502. (org-trim
  13503. (completing-read
  13504. "Tags: "
  13505. #'org-tags-completion-function
  13506. nil nil current 'org-tags-history))))))))))
  13507. (when org-tags-sort-function
  13508. (setq tags
  13509. (mapconcat
  13510. #'identity
  13511. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13512. org-tags-sort-function)
  13513. ":")))
  13514. (if (or (string= ":" tags)
  13515. (string= "::" tags))
  13516. (setq tags ""))
  13517. (if (not (org-string-nw-p tags)) (setq tags "")
  13518. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13519. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13520. ;; Insert new tags at the correct column.
  13521. (unless (equal current tags)
  13522. (save-excursion
  13523. (beginning-of-line)
  13524. (let ((case-fold-search nil))
  13525. (looking-at org-complex-heading-regexp))
  13526. ;; Remove current tags, if any.
  13527. (when (match-end 5) (replace-match "" nil nil nil 5))
  13528. ;; Insert new tags, if any. Otherwise, remove trailing
  13529. ;; white spaces.
  13530. (end-of-line)
  13531. (if (not (equal tags ""))
  13532. ;; When text is being inserted on an invisible
  13533. ;; region boundary, it can be inadvertently sucked
  13534. ;; into invisibility.
  13535. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13536. (skip-chars-backward " \t")
  13537. (delete-region (point) (line-end-position)))))
  13538. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13539. ;; is on.
  13540. (unless (equal tags "")
  13541. (let* ((level (save-excursion
  13542. (beginning-of-line)
  13543. (skip-chars-forward "\\*")))
  13544. (offset (if (bound-and-true-p org-indent-mode)
  13545. (* (1- org-indent-indentation-per-level)
  13546. (1- level))
  13547. 0))
  13548. (tags-column
  13549. (+ org-tags-column
  13550. (if (> org-tags-column 0) (- offset) offset))))
  13551. (org--align-tags-here tags-column))))
  13552. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13553. (defun org-change-tag-in-region (beg end tag off)
  13554. "Add or remove TAG for each entry in the region.
  13555. This works in the agenda, and also in an Org buffer."
  13556. (interactive
  13557. (list (region-beginning) (region-end)
  13558. (let ((org-last-tags-completion-table
  13559. (if (derived-mode-p 'org-mode)
  13560. (org-uniquify
  13561. (delq nil (append (org-get-buffer-tags)
  13562. (org-global-tags-completion-table))))
  13563. (org-global-tags-completion-table))))
  13564. (completing-read
  13565. "Tag: " 'org-tags-completion-function nil nil nil
  13566. 'org-tags-history))
  13567. (progn
  13568. (message "[s]et or [r]emove? ")
  13569. (equal (read-char-exclusive) ?r))))
  13570. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13571. (let ((agendap (equal major-mode 'org-agenda-mode))
  13572. l1 l2 m buf pos newhead (cnt 0))
  13573. (goto-char end)
  13574. (setq l2 (1- (org-current-line)))
  13575. (goto-char beg)
  13576. (setq l1 (org-current-line))
  13577. (cl-loop for l from l1 to l2 do
  13578. (org-goto-line l)
  13579. (setq m (get-text-property (point) 'org-hd-marker))
  13580. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13581. (and agendap m))
  13582. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13583. pos (if agendap m (point)))
  13584. (with-current-buffer buf
  13585. (save-excursion
  13586. (save-restriction
  13587. (goto-char pos)
  13588. (setq cnt (1+ cnt))
  13589. (org-toggle-tag tag (if off 'off 'on))
  13590. (setq newhead (org-get-heading)))))
  13591. (and agendap (org-agenda-change-all-lines newhead m))))
  13592. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13593. (defun org-tags-completion-function (string _predicate &optional flag)
  13594. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13595. (confirm (lambda (x) (stringp (car x)))))
  13596. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13597. (setq s1 (match-string 1 string)
  13598. s2 (match-string 2 string))
  13599. (setq s1 "" s2 string))
  13600. (cond
  13601. ((eq flag nil)
  13602. ;; try completion
  13603. (setq rtn (try-completion s2 ctable confirm))
  13604. (when (stringp rtn)
  13605. (setq rtn
  13606. (concat s1 s2 (substring rtn (length s2))
  13607. (if (and org-add-colon-after-tag-completion
  13608. (assoc rtn ctable))
  13609. ":" ""))))
  13610. rtn)
  13611. ((eq flag t)
  13612. ;; all-completions
  13613. (all-completions s2 ctable confirm))
  13614. ((eq flag 'lambda)
  13615. ;; exact match?
  13616. (assoc s2 ctable)))))
  13617. (defun org-fast-tag-insert (kwd tags face &optional end)
  13618. "Insert KDW, and the TAGS, the latter with face FACE.
  13619. Also insert END."
  13620. (insert (format "%-12s" (concat kwd ":"))
  13621. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13622. (or end "")))
  13623. (defun org-fast-tag-show-exit (flag)
  13624. (save-excursion
  13625. (org-goto-line 3)
  13626. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13627. (replace-match ""))
  13628. (when flag
  13629. (end-of-line 1)
  13630. (org-move-to-column (- (window-width) 19) t)
  13631. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13632. (defun org-set-current-tags-overlay (current prefix)
  13633. "Add an overlay to CURRENT tag with PREFIX."
  13634. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13635. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13636. (org-overlay-display org-tags-overlay (concat prefix s))))
  13637. (defvar org-last-tag-selection-key nil)
  13638. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13639. "Fast tag selection with single keys.
  13640. CURRENT is the current list of tags in the headline, INHERITED is the
  13641. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13642. possibly with grouping information. TODO-TABLE is a similar table with
  13643. TODO keywords, should these have keys assigned to them.
  13644. If the keys are nil, a-z are automatically assigned.
  13645. Returns the new tags string, or nil to not change the current settings."
  13646. (let* ((fulltable (append table todo-table))
  13647. (maxlen (apply 'max (mapcar
  13648. (lambda (x)
  13649. (if (stringp (car x)) (string-width (car x)) 0))
  13650. fulltable)))
  13651. (buf (current-buffer))
  13652. (expert (eq org-fast-tag-selection-single-key 'expert))
  13653. (buffer-tags nil)
  13654. (fwidth (+ maxlen 3 1 3))
  13655. (ncol (/ (- (window-width) 4) fwidth))
  13656. (i-face 'org-done)
  13657. (c-face 'org-todo)
  13658. tg cnt e c char c1 c2 ntable tbl rtn
  13659. ov-start ov-end ov-prefix
  13660. (exit-after-next org-fast-tag-selection-single-key)
  13661. (done-keywords org-done-keywords)
  13662. groups ingroup intaggroup)
  13663. (save-excursion
  13664. (beginning-of-line 1)
  13665. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13666. (setq ov-start (match-beginning 1)
  13667. ov-end (match-end 1)
  13668. ov-prefix "")
  13669. (setq ov-start (1- (point-at-eol))
  13670. ov-end (1+ ov-start))
  13671. (skip-chars-forward "^\n\r")
  13672. (setq ov-prefix
  13673. (concat
  13674. (buffer-substring (1- (point)) (point))
  13675. (if (> (current-column) org-tags-column)
  13676. " "
  13677. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13678. (move-overlay org-tags-overlay ov-start ov-end)
  13679. (save-window-excursion
  13680. (if expert
  13681. (set-buffer (get-buffer-create " *Org tags*"))
  13682. (delete-other-windows)
  13683. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13684. (org-switch-to-buffer-other-window " *Org tags*"))
  13685. (erase-buffer)
  13686. (setq-local org-done-keywords done-keywords)
  13687. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13688. (org-fast-tag-insert "Current" current c-face "\n\n")
  13689. (org-fast-tag-show-exit exit-after-next)
  13690. (org-set-current-tags-overlay current ov-prefix)
  13691. (setq tbl fulltable char ?a cnt 0)
  13692. (while (setq e (pop tbl))
  13693. (cond
  13694. ((eq (car e) :startgroup)
  13695. (push '() groups) (setq ingroup t)
  13696. (unless (zerop cnt)
  13697. (setq cnt 0)
  13698. (insert "\n"))
  13699. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13700. ((eq (car e) :endgroup)
  13701. (setq ingroup nil cnt 0)
  13702. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13703. ((eq (car e) :startgrouptag)
  13704. (setq intaggroup t)
  13705. (unless (zerop cnt)
  13706. (setq cnt 0)
  13707. (insert "\n"))
  13708. (insert "[ "))
  13709. ((eq (car e) :endgrouptag)
  13710. (setq intaggroup nil cnt 0)
  13711. (insert "]\n"))
  13712. ((equal e '(:newline))
  13713. (unless (zerop cnt)
  13714. (setq cnt 0)
  13715. (insert "\n")
  13716. (setq e (car tbl))
  13717. (while (equal (car tbl) '(:newline))
  13718. (insert "\n")
  13719. (setq tbl (cdr tbl)))))
  13720. ((equal e '(:grouptags)) (insert " : "))
  13721. (t
  13722. (setq tg (copy-sequence (car e)) c2 nil)
  13723. (if (cdr e)
  13724. (setq c (cdr e))
  13725. ;; automatically assign a character.
  13726. (setq c1 (string-to-char
  13727. (downcase (substring
  13728. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13729. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13730. (while (or (rassoc char ntable) (rassoc char table))
  13731. (setq char (1+ char)))
  13732. (setq c2 c1))
  13733. (setq c (or c2 char)))
  13734. (when ingroup (push tg (car groups)))
  13735. (setq tg (org-add-props tg nil 'face
  13736. (cond
  13737. ((not (assoc tg table))
  13738. (org-get-todo-face tg))
  13739. ((member tg current) c-face)
  13740. ((member tg inherited) i-face))))
  13741. (when (equal (caar tbl) :grouptags)
  13742. (org-add-props tg nil 'face 'org-tag-group))
  13743. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13744. (insert "[" c "] " tg (make-string
  13745. (- fwidth 4 (length tg)) ?\ ))
  13746. (push (cons tg c) ntable)
  13747. (when (= (cl-incf cnt) ncol)
  13748. (insert "\n")
  13749. (when (or ingroup intaggroup) (insert " "))
  13750. (setq cnt 0)))))
  13751. (setq ntable (nreverse ntable))
  13752. (insert "\n")
  13753. (goto-char (point-min))
  13754. (unless expert (org-fit-window-to-buffer))
  13755. (setq rtn
  13756. (catch 'exit
  13757. (while t
  13758. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  13759. (if (not groups) "no " "")
  13760. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13761. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13762. (setq org-last-tag-selection-key c)
  13763. (cond
  13764. ((= c ?\r) (throw 'exit t))
  13765. ((= c ?!)
  13766. (setq groups (not groups))
  13767. (goto-char (point-min))
  13768. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13769. ((= c ?\C-c)
  13770. (if (not expert)
  13771. (org-fast-tag-show-exit
  13772. (setq exit-after-next (not exit-after-next)))
  13773. (setq expert nil)
  13774. (delete-other-windows)
  13775. (set-window-buffer (split-window-vertically) " *Org tags*")
  13776. (org-switch-to-buffer-other-window " *Org tags*")
  13777. (org-fit-window-to-buffer)))
  13778. ((or (= c ?\C-g)
  13779. (and (= c ?q) (not (rassoc c ntable))))
  13780. (delete-overlay org-tags-overlay)
  13781. (setq quit-flag t))
  13782. ((= c ?\ )
  13783. (setq current nil)
  13784. (when exit-after-next (setq exit-after-next 'now)))
  13785. ((= c ?\t)
  13786. (condition-case nil
  13787. (setq tg (completing-read
  13788. "Tag: "
  13789. (or buffer-tags
  13790. (with-current-buffer buf
  13791. (setq buffer-tags
  13792. (org-get-buffer-tags))))))
  13793. (quit (setq tg "")))
  13794. (when (string-match "\\S-" tg)
  13795. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13796. (if (member tg current)
  13797. (setq current (delete tg current))
  13798. (push tg current)))
  13799. (when exit-after-next (setq exit-after-next 'now)))
  13800. ((setq e (rassoc c todo-table) tg (car e))
  13801. (with-current-buffer buf
  13802. (save-excursion (org-todo tg)))
  13803. (when exit-after-next (setq exit-after-next 'now)))
  13804. ((setq e (rassoc c ntable) tg (car e))
  13805. (if (member tg current)
  13806. (setq current (delete tg current))
  13807. (cl-loop for g in groups do
  13808. (when (member tg g)
  13809. (dolist (x g) (setq current (delete x current)))))
  13810. (push tg current))
  13811. (when exit-after-next (setq exit-after-next 'now))))
  13812. ;; Create a sorted list
  13813. (setq current
  13814. (sort current
  13815. (lambda (a b)
  13816. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13817. (when (eq exit-after-next 'now) (throw 'exit t))
  13818. (goto-char (point-min))
  13819. (beginning-of-line 2)
  13820. (delete-region (point) (point-at-eol))
  13821. (org-fast-tag-insert "Current" current c-face)
  13822. (org-set-current-tags-overlay current ov-prefix)
  13823. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13824. (setq tg (match-string 1))
  13825. (add-text-properties
  13826. (match-beginning 1) (match-end 1)
  13827. (list 'face
  13828. (cond
  13829. ((member tg current) c-face)
  13830. ((member tg inherited) i-face)
  13831. (t (get-text-property (match-beginning 1) 'face))))))
  13832. (goto-char (point-min)))))
  13833. (delete-overlay org-tags-overlay)
  13834. (if rtn
  13835. (mapconcat 'identity current ":")
  13836. nil))))
  13837. (defun org-get-tags-string ()
  13838. "Get the TAGS string in the current headline."
  13839. (unless (org-at-heading-p t)
  13840. (user-error "Not on a heading"))
  13841. (save-excursion
  13842. (beginning-of-line 1)
  13843. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13844. (match-string-no-properties 1)
  13845. "")))
  13846. (defun org-get-tags ()
  13847. "Get the list of tags specified in the current headline."
  13848. (org-split-string (org-get-tags-string) ":"))
  13849. (defun org-get-buffer-tags ()
  13850. "Get a table of all tags used in the buffer, for completion."
  13851. (org-with-wide-buffer
  13852. (goto-char (point-min))
  13853. (let ((tag-re (concat org-outline-regexp-bol
  13854. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13855. tags)
  13856. (while (re-search-forward tag-re nil t)
  13857. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13858. (push tag tags)))
  13859. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13860. ;;;; The mapping API
  13861. (defvar org-agenda-skip-comment-trees)
  13862. (defvar org-agenda-skip-function)
  13863. (defun org-map-entries (func &optional match scope &rest skip)
  13864. "Call FUNC at each headline selected by MATCH in SCOPE.
  13865. FUNC is a function or a lisp form. The function will be called without
  13866. arguments, with the cursor positioned at the beginning of the headline.
  13867. The return values of all calls to the function will be collected and
  13868. returned as a list.
  13869. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13870. does not need to preserve point. After evaluation, the cursor will be
  13871. moved to the end of the line (presumably of the headline of the
  13872. processed entry) and search continues from there. Under some
  13873. circumstances, this may not produce the wanted results. For example,
  13874. if you have removed (e.g. archived) the current (sub)tree it could
  13875. mean that the next entry will be skipped entirely. In such cases, you
  13876. can specify the position from where search should continue by making
  13877. FUNC set the variable `org-map-continue-from' to the desired buffer
  13878. position.
  13879. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13880. Only headlines that are matched by this query will be considered during
  13881. the iteration. When MATCH is nil or t, all headlines will be
  13882. visited by the iteration.
  13883. SCOPE determines the scope of this command. It can be any of:
  13884. nil The current buffer, respecting the restriction if any
  13885. tree The subtree started with the entry at point
  13886. region The entries within the active region, if any
  13887. region-start-level
  13888. The entries within the active region, but only those at
  13889. the same level than the first one.
  13890. file The current buffer, without restriction
  13891. file-with-archives
  13892. The current buffer, and any archives associated with it
  13893. agenda All agenda files
  13894. agenda-with-archives
  13895. All agenda files with any archive files associated with them
  13896. \(file1 file2 ...)
  13897. If this is a list, all files in the list will be scanned
  13898. The remaining args are treated as settings for the skipping facilities of
  13899. the scanner. The following items can be given here:
  13900. archive skip trees with the archive tag
  13901. comment skip trees with the COMMENT keyword
  13902. function or Emacs Lisp form:
  13903. will be used as value for `org-agenda-skip-function', so
  13904. whenever the function returns a position, FUNC will not be
  13905. called for that entry and search will continue from the
  13906. position returned
  13907. If your function needs to retrieve the tags including inherited tags
  13908. at the *current* entry, you can use the value of the variable
  13909. `org-scanner-tags' which will be much faster than getting the value
  13910. with `org-get-tags-at'. If your function gets properties with
  13911. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13912. to t around the call to `org-entry-properties' to get the same speedup.
  13913. Note that if your function moves around to retrieve tags and properties at
  13914. a *different* entry, you cannot use these techniques."
  13915. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13916. (not (org-region-active-p)))
  13917. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13918. (org-agenda-skip-archived-trees (memq 'archive skip))
  13919. (org-agenda-skip-comment-trees (memq 'comment skip))
  13920. (org-agenda-skip-function
  13921. (car (org-delete-all '(comment archive) skip)))
  13922. (org-tags-match-list-sublevels t)
  13923. (start-level (eq scope 'region-start-level))
  13924. matcher res
  13925. org-todo-keywords-for-agenda
  13926. org-done-keywords-for-agenda
  13927. org-todo-keyword-alist-for-agenda
  13928. org-tag-alist-for-agenda
  13929. org--matcher-tags-todo-only)
  13930. (cond
  13931. ((eq match t) (setq matcher t))
  13932. ((eq match nil) (setq matcher t))
  13933. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13934. (save-excursion
  13935. (save-restriction
  13936. (cond ((eq scope 'tree)
  13937. (org-back-to-heading t)
  13938. (org-narrow-to-subtree)
  13939. (setq scope nil))
  13940. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13941. (org-region-active-p))
  13942. ;; If needed, set start-level to a string like "2"
  13943. (when start-level
  13944. (save-excursion
  13945. (goto-char (region-beginning))
  13946. (unless (org-at-heading-p) (outline-next-heading))
  13947. (setq start-level (org-current-level))))
  13948. (narrow-to-region (region-beginning)
  13949. (save-excursion
  13950. (goto-char (region-end))
  13951. (unless (and (bolp) (org-at-heading-p))
  13952. (outline-next-heading))
  13953. (point)))
  13954. (setq scope nil)))
  13955. (if (not scope)
  13956. (progn
  13957. (org-agenda-prepare-buffers
  13958. (and buffer-file-name (list buffer-file-name)))
  13959. (setq res
  13960. (org-scan-tags
  13961. func matcher org--matcher-tags-todo-only start-level)))
  13962. ;; Get the right scope
  13963. (cond
  13964. ((and scope (listp scope) (symbolp (car scope)))
  13965. (setq scope (eval scope)))
  13966. ((eq scope 'agenda)
  13967. (setq scope (org-agenda-files t)))
  13968. ((eq scope 'agenda-with-archives)
  13969. (setq scope (org-agenda-files t))
  13970. (setq scope (org-add-archive-files scope)))
  13971. ((eq scope 'file)
  13972. (setq scope (and buffer-file-name (list buffer-file-name))))
  13973. ((eq scope 'file-with-archives)
  13974. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13975. (org-agenda-prepare-buffers scope)
  13976. (dolist (file scope)
  13977. (with-current-buffer (org-find-base-buffer-visiting file)
  13978. (org-with-wide-buffer
  13979. (goto-char (point-min))
  13980. (setq res
  13981. (append
  13982. res
  13983. (org-scan-tags
  13984. func matcher org--matcher-tags-todo-only)))))))))
  13985. res)))
  13986. ;;; Properties API
  13987. (defconst org-special-properties
  13988. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  13989. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  13990. "The special properties valid in Org mode.
  13991. These are properties that are not defined in the property drawer,
  13992. but in some other way.")
  13993. (defconst org-default-properties
  13994. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  13995. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  13996. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  13997. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  13998. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  13999. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14000. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14001. "Some properties that are used by Org mode for various purposes.
  14002. Being in this list makes sure that they are offered for completion.")
  14003. (defun org--valid-property-p (property)
  14004. "Non nil when string PROPERTY is a valid property name."
  14005. (not
  14006. (or (equal property "")
  14007. (string-match-p "\\s-" property))))
  14008. (defun org--update-property-plist (key val props)
  14009. "Associate KEY to VAL in alist PROPS.
  14010. Modifications are made by side-effect. Return new alist."
  14011. (let* ((appending (string= (substring key -1) "+"))
  14012. (key (if appending (substring key 0 -1) key))
  14013. (old (assoc-string key props t)))
  14014. (if (not old) (cons (cons key val) props)
  14015. (setcdr old (if appending (concat (cdr old) " " val) val))
  14016. props)))
  14017. (defun org-get-property-block (&optional beg force)
  14018. "Return the (beg . end) range of the body of the property drawer.
  14019. BEG is the beginning of the current subtree, or of the part
  14020. before the first headline. If it is not given, it will be found.
  14021. If the drawer does not exist, create it if FORCE is non-nil, or
  14022. return nil."
  14023. (org-with-wide-buffer
  14024. (when beg (goto-char beg))
  14025. (unless (org-before-first-heading-p)
  14026. (let ((beg (cond (beg)
  14027. ((or (not (featurep 'org-inlinetask))
  14028. (org-inlinetask-in-task-p))
  14029. (org-back-to-heading t))
  14030. (t (org-with-limited-levels (org-back-to-heading t))))))
  14031. (forward-line)
  14032. (when (looking-at-p org-planning-line-re) (forward-line))
  14033. (cond ((looking-at org-property-drawer-re)
  14034. (forward-line)
  14035. (cons (point) (progn (goto-char (match-end 0))
  14036. (line-beginning-position))))
  14037. (force
  14038. (goto-char beg)
  14039. (org-insert-property-drawer)
  14040. (let ((pos (save-excursion (search-forward ":END:")
  14041. (line-beginning-position))))
  14042. (cons pos pos))))))))
  14043. (defun org-at-property-p ()
  14044. "Non-nil when point is inside a property drawer.
  14045. See `org-property-re' for match data, if applicable."
  14046. (save-excursion
  14047. (beginning-of-line)
  14048. (and (looking-at org-property-re)
  14049. (let ((property-drawer (save-match-data (org-get-property-block))))
  14050. (and property-drawer
  14051. (>= (point) (car property-drawer))
  14052. (< (point) (cdr property-drawer)))))))
  14053. (defun org-property-action ()
  14054. "Do an action on properties."
  14055. (interactive)
  14056. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14057. (let ((c (read-char-exclusive)))
  14058. (cl-case c
  14059. (?s (call-interactively #'org-set-property))
  14060. (?d (call-interactively #'org-delete-property))
  14061. (?D (call-interactively #'org-delete-property-globally))
  14062. (?c (call-interactively #'org-compute-property-at-point))
  14063. (otherwise (user-error "No such property action %c" c)))))
  14064. (defun org-inc-effort ()
  14065. "Increment the value of the effort property in the current entry."
  14066. (interactive)
  14067. (org-set-effort nil t))
  14068. (defvar org-clock-effort) ; Defined in org-clock.el.
  14069. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14070. (defun org-set-effort (&optional value increment)
  14071. "Set the effort property of the current entry.
  14072. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14073. 10th allowed value.
  14074. When INCREMENT is non-nil, set the property to the next allowed value."
  14075. (interactive "P")
  14076. (when (equal value 0) (setq value 10))
  14077. (let* ((completion-ignore-case t)
  14078. (prop org-effort-property)
  14079. (cur (org-entry-get nil prop))
  14080. (allowed (org-property-get-allowed-values nil prop 'table))
  14081. (existing (mapcar 'list (org-property-values prop)))
  14082. (heading (nth 4 (org-heading-components)))
  14083. rpl
  14084. (val (cond
  14085. ((stringp value) value)
  14086. ((and allowed (integerp value))
  14087. (or (car (nth (1- value) allowed))
  14088. (car (org-last allowed))))
  14089. ((and allowed increment)
  14090. (or (cl-caadr (member (list cur) allowed))
  14091. (user-error "Allowed effort values are not set")))
  14092. (allowed
  14093. (message "Select 1-9,0, [RET%s]: %s"
  14094. (if cur (concat "=" cur) "")
  14095. (mapconcat 'car allowed " "))
  14096. (setq rpl (read-char-exclusive))
  14097. (if (equal rpl ?\r)
  14098. cur
  14099. (setq rpl (- rpl ?0))
  14100. (when (equal rpl 0) (setq rpl 10))
  14101. (if (and (> rpl 0) (<= rpl (length allowed)))
  14102. (car (nth (1- rpl) allowed))
  14103. (org-completing-read "Effort: " allowed nil))))
  14104. (t
  14105. (org-completing-read
  14106. (concat "Effort" (and cur (string-match "\\S-" cur)
  14107. (concat " [" cur "]"))
  14108. ": ")
  14109. existing nil nil "" nil cur)))))
  14110. (unless (equal (org-entry-get nil prop) val)
  14111. (org-entry-put nil prop val))
  14112. (org-refresh-property
  14113. '((effort . identity)
  14114. (effort-minutes . org-duration-to-minutes))
  14115. val)
  14116. (when (equal heading (bound-and-true-p org-clock-current-task))
  14117. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14118. (org-clock-update-mode-line))
  14119. (message "%s is now %s" prop val)))
  14120. (defun org-entry-properties (&optional pom which)
  14121. "Get all properties of the current entry.
  14122. When POM is a buffer position, get all properties from the entry
  14123. there instead.
  14124. This includes the TODO keyword, the tags, time strings for
  14125. deadline, scheduled, and clocking, and any additional properties
  14126. defined in the entry.
  14127. If WHICH is nil or `all', get all properties. If WHICH is
  14128. `special' or `standard', only get that subclass. If WHICH is
  14129. a string, only get that property.
  14130. Return value is an alist. Keys are properties, as upcased
  14131. strings."
  14132. (org-with-point-at pom
  14133. (when (and (derived-mode-p 'org-mode)
  14134. (ignore-errors (org-back-to-heading t)))
  14135. (catch 'exit
  14136. (let* ((beg (point))
  14137. (specific (and (stringp which) (upcase which)))
  14138. (which (cond ((not specific) which)
  14139. ((member specific org-special-properties) 'special)
  14140. (t 'standard)))
  14141. props)
  14142. ;; Get the special properties, like TODO and TAGS.
  14143. (when (memq which '(nil all special))
  14144. (when (or (not specific) (string= specific "CLOCKSUM"))
  14145. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14146. (when clocksum
  14147. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14148. props)))
  14149. (when specific (throw 'exit props)))
  14150. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14151. (let ((clocksumt (get-text-property (point)
  14152. :org-clock-minutes-today)))
  14153. (when clocksumt
  14154. (push (cons "CLOCKSUM_T"
  14155. (org-duration-from-minutes clocksumt))
  14156. props)))
  14157. (when specific (throw 'exit props)))
  14158. (when (or (not specific) (string= specific "ITEM"))
  14159. (let ((case-fold-search nil))
  14160. (when (looking-at org-complex-heading-regexp)
  14161. (push (cons "ITEM"
  14162. (let ((title (match-string-no-properties 4)))
  14163. (if (org-string-nw-p title)
  14164. (org-remove-tabs title)
  14165. "")))
  14166. props)))
  14167. (when specific (throw 'exit props)))
  14168. (when (or (not specific) (string= specific "TODO"))
  14169. (let ((case-fold-search nil))
  14170. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14171. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14172. (when specific (throw 'exit props)))
  14173. (when (or (not specific) (string= specific "PRIORITY"))
  14174. (push (cons "PRIORITY"
  14175. (if (looking-at org-priority-regexp)
  14176. (match-string-no-properties 2)
  14177. (char-to-string org-default-priority)))
  14178. props)
  14179. (when specific (throw 'exit props)))
  14180. (when (or (not specific) (string= specific "FILE"))
  14181. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14182. props)
  14183. (when specific (throw 'exit props)))
  14184. (when (or (not specific) (string= specific "TAGS"))
  14185. (let ((value (org-string-nw-p (org-get-tags-string))))
  14186. (when value (push (cons "TAGS" value) props)))
  14187. (when specific (throw 'exit props)))
  14188. (when (or (not specific) (string= specific "ALLTAGS"))
  14189. (let ((value (org-get-tags-at)))
  14190. (when value
  14191. (push (cons "ALLTAGS"
  14192. (format ":%s:" (mapconcat #'identity value ":")))
  14193. props)))
  14194. (when specific (throw 'exit props)))
  14195. (when (or (not specific) (string= specific "BLOCKED"))
  14196. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14197. (when specific (throw 'exit props)))
  14198. (when (or (not specific)
  14199. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14200. (forward-line)
  14201. (when (looking-at-p org-planning-line-re)
  14202. (end-of-line)
  14203. (let ((bol (line-beginning-position))
  14204. ;; Backward compatibility: time keywords used to
  14205. ;; be configurable (before 8.3). Make sure we
  14206. ;; get the correct keyword.
  14207. (key-assoc `(("CLOSED" . ,org-closed-string)
  14208. ("DEADLINE" . ,org-deadline-string)
  14209. ("SCHEDULED" . ,org-scheduled-string))))
  14210. (dolist (pair (if specific (list (assoc specific key-assoc))
  14211. key-assoc))
  14212. (save-excursion
  14213. (when (search-backward (cdr pair) bol t)
  14214. (goto-char (match-end 0))
  14215. (skip-chars-forward " \t")
  14216. (and (looking-at org-ts-regexp-both)
  14217. (push (cons (car pair)
  14218. (match-string-no-properties 0))
  14219. props)))))))
  14220. (when specific (throw 'exit props)))
  14221. (when (or (not specific)
  14222. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14223. (let ((find-ts
  14224. (lambda (end ts)
  14225. ;; Fix next time-stamp before END. TS is the
  14226. ;; list of time-stamps found so far.
  14227. (let ((ts ts)
  14228. (regexp (cond
  14229. ((string= specific "TIMESTAMP")
  14230. org-ts-regexp)
  14231. ((string= specific "TIMESTAMP_IA")
  14232. org-ts-regexp-inactive)
  14233. ((assoc "TIMESTAMP_IA" ts)
  14234. org-ts-regexp)
  14235. ((assoc "TIMESTAMP" ts)
  14236. org-ts-regexp-inactive)
  14237. (t org-ts-regexp-both))))
  14238. (catch 'next
  14239. (while (re-search-forward regexp end t)
  14240. (backward-char)
  14241. (let ((object (org-element-context)))
  14242. ;; Accept to match timestamps in node
  14243. ;; properties, too.
  14244. (when (memq (org-element-type object)
  14245. '(node-property timestamp))
  14246. (let ((type
  14247. (org-element-property :type object)))
  14248. (cond
  14249. ((and (memq type '(active active-range))
  14250. (not (equal specific "TIMESTAMP_IA")))
  14251. (unless (assoc "TIMESTAMP" ts)
  14252. (push (cons "TIMESTAMP"
  14253. (org-element-property
  14254. :raw-value object))
  14255. ts)
  14256. (when specific (throw 'exit ts))))
  14257. ((and (memq type '(inactive inactive-range))
  14258. (not (string= specific "TIMESTAMP")))
  14259. (unless (assoc "TIMESTAMP_IA" ts)
  14260. (push (cons "TIMESTAMP_IA"
  14261. (org-element-property
  14262. :raw-value object))
  14263. ts)
  14264. (when specific (throw 'exit ts))))))
  14265. ;; Both timestamp types are found,
  14266. ;; move to next part.
  14267. (when (= (length ts) 2) (throw 'next ts)))))
  14268. ts)))))
  14269. (goto-char beg)
  14270. ;; First look for timestamps within headline.
  14271. (let ((ts (funcall find-ts (line-end-position) nil)))
  14272. (if (= (length ts) 2) (setq props (nconc ts props))
  14273. ;; Then find timestamps in the section, skipping
  14274. ;; planning line.
  14275. (let ((end (save-excursion (outline-next-heading))))
  14276. (forward-line)
  14277. (when (looking-at-p org-planning-line-re) (forward-line))
  14278. (setq props (nconc (funcall find-ts end ts) props))))))))
  14279. ;; Get the standard properties, like :PROP:.
  14280. (when (memq which '(nil all standard))
  14281. ;; If we are looking after a specific property, delegate
  14282. ;; to `org-entry-get', which is faster. However, make an
  14283. ;; exception for "CATEGORY", since it can be also set
  14284. ;; through keywords (i.e. #+CATEGORY).
  14285. (if (and specific (not (equal specific "CATEGORY")))
  14286. (let ((value (org-entry-get beg specific nil t)))
  14287. (throw 'exit (and value (list (cons specific value)))))
  14288. (let ((range (org-get-property-block beg)))
  14289. (when range
  14290. (let ((end (cdr range)) seen-base)
  14291. (goto-char (car range))
  14292. ;; Unlike to `org--update-property-plist', we
  14293. ;; handle the case where base values is found
  14294. ;; after its extension. We also forbid standard
  14295. ;; properties to be named as special properties.
  14296. (while (re-search-forward org-property-re end t)
  14297. (let* ((key (upcase (match-string-no-properties 2)))
  14298. (extendp (string-match-p "\\+\\'" key))
  14299. (key-base (if extendp (substring key 0 -1) key))
  14300. (value (match-string-no-properties 3)))
  14301. (cond
  14302. ((member-ignore-case key-base org-special-properties))
  14303. (extendp
  14304. (setq props
  14305. (org--update-property-plist key value props)))
  14306. ((member key seen-base))
  14307. (t (push key seen-base)
  14308. (let ((p (assoc-string key props t)))
  14309. (if p (setcdr p (concat value " " (cdr p)))
  14310. (push (cons key value) props))))))))))))
  14311. (unless (assoc "CATEGORY" props)
  14312. (push (cons "CATEGORY" (org-get-category beg)) props)
  14313. (when (string= specific "CATEGORY") (throw 'exit props)))
  14314. ;; Return value.
  14315. props)))))
  14316. (defun org--property-local-values (property literal-nil)
  14317. "Return value for PROPERTY in current entry.
  14318. Value is a list whose car is the base value for PROPERTY and cdr
  14319. a list of accumulated values. Return nil if neither is found in
  14320. the entry. Also return nil when PROPERTY is set to \"nil\",
  14321. unless LITERAL-NIL is non-nil."
  14322. (let ((range (org-get-property-block)))
  14323. (when range
  14324. (goto-char (car range))
  14325. (let* ((case-fold-search t)
  14326. (end (cdr range))
  14327. (value
  14328. ;; Base value.
  14329. (save-excursion
  14330. (let ((v (and (re-search-forward
  14331. (org-re-property property nil t) end t)
  14332. (match-string-no-properties 3))))
  14333. (list (if literal-nil v (org-not-nil v)))))))
  14334. ;; Find additional values.
  14335. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14336. (while (re-search-forward property+ end t)
  14337. (push (match-string-no-properties 3) value)))
  14338. ;; Return final values.
  14339. (and (not (equal value '(nil))) (nreverse value))))))
  14340. (defun org--property-global-value (property literal-nil)
  14341. "Return value for PROPERTY in current buffer.
  14342. Return value is a string. Return nil if property is not set
  14343. globally. Also return nil when PROPERTY is set to \"nil\",
  14344. unless LITERAL-NIL is non-nil."
  14345. (let ((global
  14346. (cdr (or (assoc-string property org-file-properties t)
  14347. (assoc-string property org-global-properties t)
  14348. (assoc-string property org-global-properties-fixed t)))))
  14349. (if literal-nil global (org-not-nil global))))
  14350. (defun org-entry-get (pom property &optional inherit literal-nil)
  14351. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14352. If INHERIT is non-nil and the entry does not have the property,
  14353. then also check higher levels of the hierarchy. If INHERIT is
  14354. the symbol `selective', use inheritance only if the setting in
  14355. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14356. If the property is present but empty, the return value is the
  14357. empty string. If the property is not present at all, nil is
  14358. returned. In any other case, return the value as a string.
  14359. Search is case-insensitive.
  14360. If LITERAL-NIL is set, return the string value \"nil\" as
  14361. a string, do not interpret it as the list atom nil. This is used
  14362. for inheritance when a \"nil\" value can supersede a non-nil
  14363. value higher up the hierarchy."
  14364. (org-with-point-at pom
  14365. (cond
  14366. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14367. ;; We need a special property. Use `org-entry-properties' to
  14368. ;; retrieve it, but specify the wanted property.
  14369. (cdr (assoc-string property (org-entry-properties nil property))))
  14370. ((and inherit
  14371. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14372. (org-entry-get-with-inheritance property literal-nil))
  14373. (t
  14374. (let* ((local (org--property-local-values property literal-nil))
  14375. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14376. (if literal-nil value (org-not-nil value)))))))
  14377. (defun org-property-or-variable-value (var &optional inherit)
  14378. "Check if there is a property fixing the value of VAR.
  14379. If yes, return this value. If not, return the current value of the variable."
  14380. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14381. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14382. (read prop)
  14383. (symbol-value var))))
  14384. (defun org-entry-delete (pom property)
  14385. "Delete PROPERTY from entry at point-or-marker POM.
  14386. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14387. non-nil when a property was removed."
  14388. (org-with-point-at pom
  14389. (pcase (org-get-property-block)
  14390. (`(,begin . ,origin)
  14391. (let* ((end (copy-marker origin))
  14392. (re (org-re-property
  14393. (concat (regexp-quote property) "\\+?") t t)))
  14394. (goto-char begin)
  14395. (while (re-search-forward re end t)
  14396. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14397. ;; If drawer is empty, remove it altogether.
  14398. (when (= begin end)
  14399. (delete-region (line-beginning-position 0)
  14400. (line-beginning-position 2)))
  14401. ;; Return non-nil if some property was removed.
  14402. (prog1 (/= end origin) (set-marker end nil))))
  14403. (_ nil))))
  14404. ;; Multi-values properties are properties that contain multiple values
  14405. ;; These values are assumed to be single words, separated by whitespace.
  14406. (defun org-entry-add-to-multivalued-property (pom property value)
  14407. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14408. (let* ((old (org-entry-get pom property))
  14409. (values (and old (split-string old))))
  14410. (setq value (org-entry-protect-space value))
  14411. (unless (member value values)
  14412. (setq values (append values (list value)))
  14413. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14414. (defun org-entry-remove-from-multivalued-property (pom property value)
  14415. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14416. (let* ((old (org-entry-get pom property))
  14417. (values (and old (split-string old))))
  14418. (setq value (org-entry-protect-space value))
  14419. (when (member value values)
  14420. (setq values (delete value values))
  14421. (org-entry-put pom property (mapconcat #'identity values " ")))))
  14422. (defun org-entry-member-in-multivalued-property (pom property value)
  14423. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14424. (let* ((old (org-entry-get pom property))
  14425. (values (and old (split-string old))))
  14426. (setq value (org-entry-protect-space value))
  14427. (member value values)))
  14428. (defun org-entry-get-multivalued-property (pom property)
  14429. "Return a list of values in a multivalued property."
  14430. (let* ((value (org-entry-get pom property))
  14431. (values (and value (split-string value))))
  14432. (mapcar #'org-entry-restore-space values)))
  14433. (defun org-entry-put-multivalued-property (pom property &rest values)
  14434. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14435. VALUES should be a list of strings. Spaces will be protected."
  14436. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  14437. (let* ((value (org-entry-get pom property))
  14438. (values (and value (split-string value))))
  14439. (mapcar #'org-entry-restore-space values)))
  14440. (defun org-entry-protect-space (s)
  14441. "Protect spaces and newline in string S."
  14442. (while (string-match " " s)
  14443. (setq s (replace-match "%20" t t s)))
  14444. (while (string-match "\n" s)
  14445. (setq s (replace-match "%0A" t t s)))
  14446. s)
  14447. (defun org-entry-restore-space (s)
  14448. "Restore spaces and newline in string S."
  14449. (while (string-match "%20" s)
  14450. (setq s (replace-match " " t t s)))
  14451. (while (string-match "%0A" s)
  14452. (setq s (replace-match "\n" t t s)))
  14453. s)
  14454. (defvar org-entry-property-inherited-from (make-marker)
  14455. "Marker pointing to the entry from where a property was inherited.
  14456. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14457. location of the entry where the inheritance search matched. If there was
  14458. no match, the marker will point nowhere.
  14459. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14460. is set.")
  14461. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14462. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14463. The search will stop at the first ancestor which has the property defined.
  14464. If the value found is \"nil\", return nil to show that the property
  14465. should be considered as undefined (this is the meaning of nil here).
  14466. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14467. (move-marker org-entry-property-inherited-from nil)
  14468. (org-with-wide-buffer
  14469. (let (value)
  14470. (catch 'exit
  14471. (while t
  14472. (let ((v (org--property-local-values property literal-nil)))
  14473. (when v
  14474. (setq value
  14475. (concat (mapconcat #'identity (delq nil v) " ")
  14476. (and value " ")
  14477. value)))
  14478. (cond
  14479. ((car v)
  14480. (org-back-to-heading t)
  14481. (move-marker org-entry-property-inherited-from (point))
  14482. (throw 'exit nil))
  14483. ((org-up-heading-safe))
  14484. (t
  14485. (let ((global (org--property-global-value property literal-nil)))
  14486. (cond ((not global))
  14487. (value (setq value (concat global " " value)))
  14488. (t (setq value global))))
  14489. (throw 'exit nil))))))
  14490. (if literal-nil value (org-not-nil value)))))
  14491. (defvar org-property-changed-functions nil
  14492. "Hook called when the value of a property has changed.
  14493. Each hook function should accept two arguments, the name of the property
  14494. and the new value.")
  14495. (defun org-entry-put (pom property value)
  14496. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14497. If the value is nil, it is converted to the empty string. If it
  14498. is not a string, an error is raised. Also raise an error on
  14499. invalid property names.
  14500. PROPERTY can be any regular property (see
  14501. `org-special-properties'). It can also be \"TODO\",
  14502. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14503. For the last two properties, VALUE may have any of the special
  14504. values \"earlier\" and \"later\". The function then increases or
  14505. decreases scheduled or deadline date by one day."
  14506. (cond ((null value) (setq value ""))
  14507. ((not (stringp value)) (error "Properties values should be strings"))
  14508. ((not (org--valid-property-p property))
  14509. (user-error "Invalid property name: \"%s\"" property)))
  14510. (org-with-point-at pom
  14511. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14512. (org-back-to-heading t)
  14513. (org-with-limited-levels (org-back-to-heading t)))
  14514. (let ((beg (point)))
  14515. (cond
  14516. ((equal property "TODO")
  14517. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14518. ((not (member value org-todo-keywords-1))
  14519. (user-error "\"%s\" is not a valid TODO state" value)))
  14520. (org-todo value)
  14521. (org-set-tags nil 'align))
  14522. ((equal property "PRIORITY")
  14523. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14524. (org-set-tags nil 'align))
  14525. ((equal property "SCHEDULED")
  14526. (forward-line)
  14527. (if (and (looking-at-p org-planning-line-re)
  14528. (re-search-forward
  14529. org-scheduled-time-regexp (line-end-position) t))
  14530. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14531. ((string= value "later") (org-timestamp-change 1 'day))
  14532. ((string= value "") (org-schedule '(4)))
  14533. (t (org-schedule nil value)))
  14534. (if (member value '("earlier" "later" ""))
  14535. (call-interactively #'org-schedule)
  14536. (org-schedule nil value))))
  14537. ((equal property "DEADLINE")
  14538. (forward-line)
  14539. (if (and (looking-at-p org-planning-line-re)
  14540. (re-search-forward
  14541. org-deadline-time-regexp (line-end-position) t))
  14542. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14543. ((string= value "later") (org-timestamp-change 1 'day))
  14544. ((string= value "") (org-deadline '(4)))
  14545. (t (org-deadline nil value)))
  14546. (if (member value '("earlier" "later" ""))
  14547. (call-interactively #'org-deadline)
  14548. (org-deadline nil value))))
  14549. ((member property org-special-properties)
  14550. (error "The %s property cannot be set with `org-entry-put'" property))
  14551. (t
  14552. (let* ((range (org-get-property-block beg 'force))
  14553. (end (cdr range))
  14554. (case-fold-search t))
  14555. (goto-char (car range))
  14556. (if (re-search-forward (org-re-property property nil t) end t)
  14557. (progn (delete-region (match-beginning 0) (match-end 0))
  14558. (goto-char (match-beginning 0)))
  14559. (goto-char end)
  14560. (insert "\n")
  14561. (backward-char))
  14562. (insert ":" property ":")
  14563. (when value (insert " " value))
  14564. (org-indent-line)))))
  14565. (run-hook-with-args 'org-property-changed-functions property value)))
  14566. (defun org-buffer-property-keys (&optional specials defaults columns)
  14567. "Get all property keys in the current buffer.
  14568. When SPECIALS is non-nil, also list the special properties that
  14569. reflect things like tags and TODO state.
  14570. When DEFAULTS is non-nil, also include properties that has
  14571. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14572. DESCRIPTION, LOCATION, and LOGGING and others.
  14573. When COLUMNS in non-nil, also include property names given in
  14574. COLUMN formats in the current buffer."
  14575. (let ((case-fold-search t)
  14576. (props (append
  14577. (and specials org-special-properties)
  14578. (and defaults (cons org-effort-property org-default-properties))
  14579. nil)))
  14580. (org-with-wide-buffer
  14581. (goto-char (point-min))
  14582. (while (re-search-forward org-property-start-re nil t)
  14583. (catch :skip
  14584. (let ((range (org-get-property-block)))
  14585. (unless range (throw :skip nil))
  14586. (goto-char (car range))
  14587. (let ((begin (car range))
  14588. (end (cdr range)))
  14589. ;; Make sure that found property block is not located
  14590. ;; before current point, as it would generate an infloop.
  14591. ;; It can happen, for example, in the following
  14592. ;; situation:
  14593. ;;
  14594. ;; * Headline
  14595. ;; :PROPERTIES:
  14596. ;; ...
  14597. ;; :END:
  14598. ;; *************** Inlinetask
  14599. ;; #+BEGIN_EXAMPLE
  14600. ;; :PROPERTIES:
  14601. ;; #+END_EXAMPLE
  14602. ;;
  14603. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  14604. (while (< (point) end)
  14605. (let ((p (progn (looking-at org-property-re)
  14606. (match-string-no-properties 2))))
  14607. ;; Only add true property name, not extension symbol.
  14608. (push (if (not (string-match-p "\\+\\'" p)) p
  14609. (substring p 0 -1))
  14610. props))
  14611. (forward-line))))
  14612. (outline-next-heading)))
  14613. (when columns
  14614. (goto-char (point-min))
  14615. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14616. (let ((element (org-element-at-point)))
  14617. (when (memq (org-element-type element) '(keyword node-property))
  14618. (let ((value (org-element-property :value element))
  14619. (start 0))
  14620. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14621. (setq start (match-end 0))
  14622. (let ((p (match-string-no-properties 1 value)))
  14623. (unless (member-ignore-case p org-special-properties)
  14624. (push p props))))))))))
  14625. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14626. (defun org-property-values (key)
  14627. "List all non-nil values of property KEY in current buffer."
  14628. (org-with-wide-buffer
  14629. (goto-char (point-min))
  14630. (let ((case-fold-search t)
  14631. (re (org-re-property key))
  14632. values)
  14633. (while (re-search-forward re nil t)
  14634. (push (org-entry-get (point) key) values))
  14635. (delete-dups values))))
  14636. (defun org-insert-property-drawer ()
  14637. "Insert a property drawer into the current entry."
  14638. (org-with-wide-buffer
  14639. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14640. (org-back-to-heading t)
  14641. (org-with-limited-levels (org-back-to-heading t)))
  14642. (forward-line)
  14643. (when (looking-at-p org-planning-line-re) (forward-line))
  14644. (unless (looking-at-p org-property-drawer-re)
  14645. ;; Make sure we start editing a line from current entry, not from
  14646. ;; next one. It prevents extending text properties or overlays
  14647. ;; belonging to the latter.
  14648. (when (bolp) (backward-char))
  14649. (let ((begin (1+ (point)))
  14650. (inhibit-read-only t))
  14651. (insert "\n:PROPERTIES:\n:END:")
  14652. (when (eobp) (insert "\n"))
  14653. (org-indent-region begin (point))))))
  14654. (defun org-insert-drawer (&optional arg drawer)
  14655. "Insert a drawer at point.
  14656. When optional argument ARG is non-nil, insert a property drawer.
  14657. Optional argument DRAWER, when non-nil, is a string representing
  14658. drawer's name. Otherwise, the user is prompted for a name.
  14659. If a region is active, insert the drawer around that region
  14660. instead.
  14661. Point is left between drawer's boundaries."
  14662. (interactive "P")
  14663. (let* ((drawer (if arg "PROPERTIES"
  14664. (or drawer (read-from-minibuffer "Drawer: ")))))
  14665. (cond
  14666. ;; With C-u, fall back on `org-insert-property-drawer'
  14667. (arg (org-insert-property-drawer))
  14668. ;; Check validity of suggested drawer's name.
  14669. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14670. (user-error "Invalid drawer name"))
  14671. ;; With an active region, insert a drawer at point.
  14672. ((not (org-region-active-p))
  14673. (progn
  14674. (unless (bolp) (insert "\n"))
  14675. (insert (format ":%s:\n\n:END:\n" drawer))
  14676. (forward-line -2)))
  14677. ;; Otherwise, insert the drawer at point
  14678. (t
  14679. (let ((rbeg (region-beginning))
  14680. (rend (copy-marker (region-end))))
  14681. (unwind-protect
  14682. (progn
  14683. (goto-char rbeg)
  14684. (beginning-of-line)
  14685. (when (save-excursion
  14686. (re-search-forward org-outline-regexp-bol rend t))
  14687. (user-error "Drawers cannot contain headlines"))
  14688. ;; Position point at the beginning of the first
  14689. ;; non-blank line in region. Insert drawer's opening
  14690. ;; there, then indent it.
  14691. (org-skip-whitespace)
  14692. (beginning-of-line)
  14693. (insert ":" drawer ":\n")
  14694. (forward-line -1)
  14695. (indent-for-tab-command)
  14696. ;; Move point to the beginning of the first blank line
  14697. ;; after the last non-blank line in region. Insert
  14698. ;; drawer's closing, then indent it.
  14699. (goto-char rend)
  14700. (skip-chars-backward " \r\t\n")
  14701. (insert "\n:END:")
  14702. (deactivate-mark t)
  14703. (indent-for-tab-command)
  14704. (unless (eolp) (insert "\n")))
  14705. ;; Clear marker, whatever the outcome of insertion is.
  14706. (set-marker rend nil)))))))
  14707. (defvar org-property-set-functions-alist nil
  14708. "Property set function alist.
  14709. Each entry should have the following format:
  14710. (PROPERTY . READ-FUNCTION)
  14711. The read function will be called with the same argument as
  14712. `org-completing-read'.")
  14713. (defun org-set-property-function (property)
  14714. "Get the function that should be used to set PROPERTY.
  14715. This is computed according to `org-property-set-functions-alist'."
  14716. (or (cdr (assoc property org-property-set-functions-alist))
  14717. 'org-completing-read))
  14718. (defun org-read-property-value (property)
  14719. "Read PROPERTY value from user."
  14720. (let* ((completion-ignore-case t)
  14721. (allowed (org-property-get-allowed-values nil property 'table))
  14722. (cur (org-entry-get nil property))
  14723. (prompt (concat property " value"
  14724. (if (and cur (string-match "\\S-" cur))
  14725. (concat " [" cur "]") "") ": "))
  14726. (set-function (org-set-property-function property))
  14727. (val (if allowed
  14728. (funcall set-function prompt allowed nil
  14729. (not (get-text-property 0 'org-unrestricted
  14730. (caar allowed))))
  14731. (funcall set-function prompt
  14732. (mapcar 'list (org-property-values property))
  14733. nil nil "" nil cur))))
  14734. (org-trim val)))
  14735. (defvar org-last-set-property nil)
  14736. (defvar org-last-set-property-value nil)
  14737. (defun org-read-property-name ()
  14738. "Read a property name."
  14739. (let ((completion-ignore-case t)
  14740. (default-prop (or (and (org-at-property-p)
  14741. (match-string-no-properties 2))
  14742. org-last-set-property)))
  14743. (org-completing-read
  14744. (concat "Property"
  14745. (if default-prop (concat " [" default-prop "]") "")
  14746. ": ")
  14747. (mapcar #'list (org-buffer-property-keys nil t t))
  14748. nil nil nil nil default-prop)))
  14749. (defun org-set-property-and-value (use-last)
  14750. "Allow to set [PROPERTY]: [value] direction from prompt.
  14751. When use-default, don't even ask, just use the last
  14752. \"[PROPERTY]: [value]\" string from the history."
  14753. (interactive "P")
  14754. (let* ((completion-ignore-case t)
  14755. (pv (or (and use-last org-last-set-property-value)
  14756. (org-completing-read
  14757. "Enter a \"[Property]: [value]\" pair: "
  14758. nil nil nil nil nil
  14759. org-last-set-property-value)))
  14760. prop val)
  14761. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14762. (setq prop (match-string 1 pv)
  14763. val (match-string 2 pv))
  14764. (org-set-property prop val))))
  14765. (defun org-set-property (property value)
  14766. "In the current entry, set PROPERTY to VALUE.
  14767. When called interactively, this will prompt for a property name, offering
  14768. completion on existing and default properties. And then it will prompt
  14769. for a value, offering completion either on allowed values (via an inherited
  14770. xxx_ALL property) or on existing values in other instances of this property
  14771. in the current file.
  14772. Throw an error when trying to set a property with an invalid name."
  14773. (interactive (list nil nil))
  14774. (let ((property (or property (org-read-property-name))))
  14775. ;; `org-entry-put' also makes the following check, but this one
  14776. ;; avoids polluting `org-last-set-property' and
  14777. ;; `org-last-set-property-value' needlessly.
  14778. (unless (org--valid-property-p property)
  14779. (user-error "Invalid property name: \"%s\"" property))
  14780. (let ((value (or value (org-read-property-value property)))
  14781. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14782. (setq org-last-set-property property)
  14783. (setq org-last-set-property-value (concat property ": " value))
  14784. ;; Possibly postprocess the inserted value:
  14785. (when fn (setq value (funcall fn value)))
  14786. (unless (equal (org-entry-get nil property) value)
  14787. (org-entry-put nil property value)))))
  14788. (defun org-find-property (property &optional value)
  14789. "Find first entry in buffer that sets PROPERTY.
  14790. When optional argument VALUE is non-nil, only consider an entry
  14791. if it contains PROPERTY set to this value. If PROPERTY should be
  14792. explicitly set to nil, use string \"nil\" for VALUE.
  14793. Return position where the entry begins, or nil if there is no
  14794. such entry. If narrowing is in effect, only search the visible
  14795. part of the buffer."
  14796. (save-excursion
  14797. (goto-char (point-min))
  14798. (let ((case-fold-search t)
  14799. (re (org-re-property property nil (not value) value)))
  14800. (catch 'exit
  14801. (while (re-search-forward re nil t)
  14802. (when (if value (org-at-property-p)
  14803. (org-entry-get (point) property nil t))
  14804. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14805. (defun org-delete-property (property)
  14806. "In the current entry, delete PROPERTY."
  14807. (interactive
  14808. (let* ((completion-ignore-case t)
  14809. (cat (org-entry-get (point) "CATEGORY"))
  14810. (props0 (org-entry-properties nil 'standard))
  14811. (props (if cat props0
  14812. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14813. (prop (if (< 1 (length props))
  14814. (completing-read "Property: " props nil t)
  14815. (caar props))))
  14816. (list prop)))
  14817. (if (not property)
  14818. (message "No property to delete in this entry")
  14819. (org-entry-delete nil property)
  14820. (message "Property \"%s\" deleted" property)))
  14821. (defun org-delete-property-globally (property)
  14822. "Remove PROPERTY globally, from all entries.
  14823. This function ignores narrowing, if any."
  14824. (interactive
  14825. (let* ((completion-ignore-case t)
  14826. (prop (completing-read
  14827. "Globally remove property: "
  14828. (mapcar #'list (org-buffer-property-keys)))))
  14829. (list prop)))
  14830. (org-with-wide-buffer
  14831. (goto-char (point-min))
  14832. (let ((count 0)
  14833. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14834. (while (re-search-forward re nil t)
  14835. (when (org-entry-delete (point) property) (cl-incf count)))
  14836. (message "Property \"%s\" removed from %d entries" property count))))
  14837. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14838. (defun org-compute-property-at-point ()
  14839. "Compute the property at point.
  14840. This looks for an enclosing column format, extracts the operator and
  14841. then applies it to the property in the column format's scope."
  14842. (interactive)
  14843. (unless (org-at-property-p)
  14844. (user-error "Not at a property"))
  14845. (let ((prop (match-string-no-properties 2)))
  14846. (org-columns-get-format-and-top-level)
  14847. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14848. (user-error "No operator defined for property %s" prop))
  14849. (org-columns-compute prop)))
  14850. (defvar org-property-allowed-value-functions nil
  14851. "Hook for functions supplying allowed values for a specific property.
  14852. The functions must take a single argument, the name of the property, and
  14853. return a flat list of allowed values. If \":ETC\" is one of
  14854. the values, this means that these values are intended as defaults for
  14855. completion, but that other values should be allowed too.
  14856. The functions must return nil if they are not responsible for this
  14857. property.")
  14858. (defun org-property-get-allowed-values (pom property &optional table)
  14859. "Get allowed values for the property PROPERTY.
  14860. When TABLE is non-nil, return an alist that can directly be used for
  14861. completion."
  14862. (let (vals)
  14863. (cond
  14864. ((equal property "TODO")
  14865. (setq vals (org-with-point-at pom
  14866. (append org-todo-keywords-1 '("")))))
  14867. ((equal property "PRIORITY")
  14868. (let ((n org-lowest-priority))
  14869. (while (>= n org-highest-priority)
  14870. (push (char-to-string n) vals)
  14871. (setq n (1- n)))))
  14872. ((equal property "CATEGORY"))
  14873. ((member property org-special-properties))
  14874. ((setq vals (run-hook-with-args-until-success
  14875. 'org-property-allowed-value-functions property)))
  14876. (t
  14877. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14878. (when (and vals (string-match "\\S-" vals))
  14879. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14880. (setq vals (mapcar (lambda (x)
  14881. (cond ((stringp x) x)
  14882. ((numberp x) (number-to-string x))
  14883. ((symbolp x) (symbol-name x))
  14884. (t "???")))
  14885. vals)))))
  14886. (when (member ":ETC" vals)
  14887. (setq vals (remove ":ETC" vals))
  14888. (org-add-props (car vals) '(org-unrestricted t)))
  14889. (if table (mapcar 'list vals) vals)))
  14890. (defun org-property-previous-allowed-value (&optional _previous)
  14891. "Switch to the next allowed value for this property."
  14892. (interactive)
  14893. (org-property-next-allowed-value t))
  14894. (defun org-property-next-allowed-value (&optional previous)
  14895. "Switch to the next allowed value for this property."
  14896. (interactive)
  14897. (unless (org-at-property-p)
  14898. (user-error "Not at a property"))
  14899. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14900. (key (match-string 2))
  14901. (value (match-string 3))
  14902. (allowed (or (org-property-get-allowed-values (point) key)
  14903. (and (member value '("[ ]" "[-]" "[X]"))
  14904. '("[ ]" "[X]"))))
  14905. (heading (save-match-data (nth 4 (org-heading-components))))
  14906. nval)
  14907. (unless allowed
  14908. (user-error "Allowed values for this property have not been defined"))
  14909. (when previous (setq allowed (reverse allowed)))
  14910. (when (member value allowed)
  14911. (setq nval (car (cdr (member value allowed)))))
  14912. (setq nval (or nval (car allowed)))
  14913. (when (equal nval value)
  14914. (user-error "Only one allowed value for this property"))
  14915. (org-at-property-p)
  14916. (replace-match (concat " :" key ": " nval) t t)
  14917. (org-indent-line)
  14918. (beginning-of-line 1)
  14919. (skip-chars-forward " \t")
  14920. (when (equal prop org-effort-property)
  14921. (org-refresh-property
  14922. '((effort . identity)
  14923. (effort-minutes . org-duration-to-minutes))
  14924. nval)
  14925. (when (string= org-clock-current-task heading)
  14926. (setq org-clock-effort nval)
  14927. (org-clock-update-mode-line)))
  14928. (run-hook-with-args 'org-property-changed-functions key nval)))
  14929. (defun org-find-olp (path &optional this-buffer)
  14930. "Return a marker pointing to the entry at outline path OLP.
  14931. If anything goes wrong, throw an error.
  14932. You can wrap this call to catch the error like this:
  14933. (condition-case msg
  14934. (org-mobile-locate-entry (match-string 4))
  14935. (error (nth 1 msg)))
  14936. The return value will then be either a string with the error message,
  14937. or a marker if everything is OK.
  14938. If THIS-BUFFER is set, the outline path does not contain a file,
  14939. only headings."
  14940. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14941. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14942. (level 1)
  14943. (lmin 1)
  14944. (lmax 1)
  14945. end found flevel)
  14946. (unless buffer (error "File not found :%s" file))
  14947. (with-current-buffer buffer
  14948. (unless (derived-mode-p 'org-mode)
  14949. (error "Buffer %s needs to be in Org mode" buffer))
  14950. (org-with-wide-buffer
  14951. (goto-char (point-min))
  14952. (dolist (heading path)
  14953. (let ((re (format org-complex-heading-regexp-format
  14954. (regexp-quote heading)))
  14955. (cnt 0))
  14956. (while (re-search-forward re end t)
  14957. (setq level (- (match-end 1) (match-beginning 1)))
  14958. (when (and (>= level lmin) (<= level lmax))
  14959. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14960. (when (= cnt 0)
  14961. (error "Heading not found on level %d: %s" lmax heading))
  14962. (when (> cnt 1)
  14963. (error "Heading not unique on level %d: %s" lmax heading))
  14964. (goto-char found)
  14965. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14966. (setq end (save-excursion (org-end-of-subtree t t)))))
  14967. (when (org-at-heading-p)
  14968. (point-marker))))))
  14969. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  14970. "Find node HEADING in BUFFER.
  14971. Return a marker to the heading if it was found, or nil if not.
  14972. If POS-ONLY is set, return just the position instead of a marker.
  14973. The heading text must match exact, but it may have a TODO keyword,
  14974. a priority cookie and tags in the standard locations."
  14975. (with-current-buffer (or buffer (current-buffer))
  14976. (org-with-wide-buffer
  14977. (goto-char (point-min))
  14978. (let (case-fold-search)
  14979. (when (re-search-forward
  14980. (format org-complex-heading-regexp-format
  14981. (regexp-quote heading)) nil t)
  14982. (if pos-only
  14983. (match-beginning 0)
  14984. (move-marker (make-marker) (match-beginning 0))))))))
  14985. (defun org-find-exact-heading-in-directory (heading &optional dir)
  14986. "Find Org node headline HEADING in all .org files in directory DIR.
  14987. When the target headline is found, return a marker to this location."
  14988. (let ((files (directory-files (or dir default-directory)
  14989. t "\\`[^.#].*\\.org\\'"))
  14990. visiting m buffer)
  14991. (catch 'found
  14992. (dolist (file files)
  14993. (message "trying %s" file)
  14994. (setq visiting (org-find-base-buffer-visiting file))
  14995. (setq buffer (or visiting (find-file-noselect file)))
  14996. (setq m (org-find-exact-headline-in-buffer
  14997. heading buffer))
  14998. (when (and (not m) (not visiting)) (kill-buffer buffer))
  14999. (and m (throw 'found m))))))
  15000. (defun org-find-entry-with-id (ident)
  15001. "Locate the entry that contains the ID property with exact value IDENT.
  15002. IDENT can be a string, a symbol or a number, this function will search for
  15003. the string representation of it.
  15004. Return the position where this entry starts, or nil if there is no such entry."
  15005. (interactive "sID: ")
  15006. (let ((id (cond
  15007. ((stringp ident) ident)
  15008. ((symbolp ident) (symbol-name ident))
  15009. ((numberp ident) (number-to-string ident))
  15010. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15011. (org-with-wide-buffer (org-find-property "ID" id))))
  15012. ;;;; Timestamps
  15013. (defvar org-last-changed-timestamp nil)
  15014. (defvar org-last-inserted-timestamp nil
  15015. "The last time stamp inserted with `org-insert-time-stamp'.")
  15016. (defun org-time-stamp (arg &optional inactive)
  15017. "Prompt for a date/time and insert a time stamp.
  15018. If the user specifies a time like HH:MM or if this command is
  15019. called with at least one prefix argument, the time stamp contains
  15020. the date and the time. Otherwise, only the date is included.
  15021. All parts of a date not specified by the user are filled in from
  15022. the timestamp at point, if any, or the current date/time
  15023. otherwise.
  15024. If there is already a timestamp at the cursor, it is replaced.
  15025. With two universal prefix arguments, insert an active timestamp
  15026. with the current time without prompting the user.
  15027. When called from lisp, the timestamp is inactive if INACTIVE is
  15028. non-nil."
  15029. (interactive "P")
  15030. (let* ((ts (cond
  15031. ((org-at-date-range-p t)
  15032. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15033. ((org-at-timestamp-p 'lax) (match-string 0))))
  15034. ;; Default time is either the timestamp at point or today.
  15035. ;; When entering a range, only the range start is considered.
  15036. (default-time (if (not ts) (current-time)
  15037. (apply #'encode-time (org-parse-time-string ts))))
  15038. (default-input (and ts (org-get-compact-tod ts)))
  15039. (repeater (and ts
  15040. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15041. (match-string 0 ts)))
  15042. org-time-was-given
  15043. org-end-time-was-given
  15044. (time
  15045. (and (if (equal arg '(16)) (current-time)
  15046. ;; Preserve `this-command' and `last-command'.
  15047. (let ((this-command this-command)
  15048. (last-command last-command))
  15049. (org-read-date
  15050. arg 'totime nil nil default-time default-input
  15051. inactive))))))
  15052. (cond
  15053. ((and ts
  15054. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15055. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15056. (insert "--")
  15057. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15058. (ts
  15059. ;; Make sure we're on a timestamp. When in the middle of a date
  15060. ;; range, move arbitrarily to range end.
  15061. (unless (org-at-timestamp-p 'lax)
  15062. (skip-chars-forward "-")
  15063. (org-at-timestamp-p 'lax))
  15064. (replace-match "")
  15065. (setq org-last-changed-timestamp
  15066. (org-insert-time-stamp
  15067. time (or org-time-was-given arg)
  15068. inactive nil nil (list org-end-time-was-given)))
  15069. (when repeater
  15070. (backward-char)
  15071. (insert " " repeater)
  15072. (setq org-last-changed-timestamp
  15073. (concat (substring org-last-inserted-timestamp 0 -1)
  15074. " " repeater ">")))
  15075. (message "Timestamp updated"))
  15076. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15077. (t (org-insert-time-stamp
  15078. time (or org-time-was-given arg) inactive nil nil
  15079. (list org-end-time-was-given))))))
  15080. ;; FIXME: can we use this for something else, like computing time differences?
  15081. (defun org-get-compact-tod (s)
  15082. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15083. (let* ((t1 (match-string 1 s))
  15084. (h1 (string-to-number (match-string 2 s)))
  15085. (m1 (string-to-number (match-string 3 s)))
  15086. (t2 (and (match-end 4) (match-string 5 s)))
  15087. (h2 (and t2 (string-to-number (match-string 6 s))))
  15088. (m2 (and t2 (string-to-number (match-string 7 s))))
  15089. dh dm)
  15090. (if (not t2)
  15091. t1
  15092. (setq dh (- h2 h1) dm (- m2 m1))
  15093. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15094. (concat t1 "+" (number-to-string dh)
  15095. (and (/= 0 dm) (format ":%02d" dm)))))))
  15096. (defun org-time-stamp-inactive (&optional arg)
  15097. "Insert an inactive time stamp.
  15098. An inactive time stamp is enclosed in square brackets instead of angle
  15099. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15100. does not link to the calendar and cannot be changed with the S-cursor keys.
  15101. So these are more for recording a certain time/date."
  15102. (interactive "P")
  15103. (org-time-stamp arg 'inactive))
  15104. (defvar org-date-ovl (make-overlay 1 1))
  15105. (overlay-put org-date-ovl 'face 'org-date-selected)
  15106. (delete-overlay org-date-ovl)
  15107. (defvar org-ans1) ; dynamically scoped parameter
  15108. (defvar org-ans2) ; dynamically scoped parameter
  15109. (defvar org-plain-time-of-day-regexp) ; defined below
  15110. (defvar org-overriding-default-time nil) ; dynamically scoped
  15111. (defvar org-read-date-overlay nil)
  15112. (defvar org-dcst nil) ; dynamically scoped
  15113. (defvar org-read-date-history nil)
  15114. (defvar org-read-date-final-answer nil)
  15115. (defvar org-read-date-analyze-futurep nil)
  15116. (defvar org-read-date-analyze-forced-year nil)
  15117. (defvar org-read-date-inactive)
  15118. (defvar org-read-date-minibuffer-local-map
  15119. (let* ((map (make-sparse-keymap)))
  15120. (set-keymap-parent map minibuffer-local-map)
  15121. (org-defkey map (kbd ".")
  15122. (lambda () (interactive)
  15123. ;; Are we at the beginning of the prompt?
  15124. (if (looking-back "^[^:]+: "
  15125. (let ((inhibit-field-text-motion t))
  15126. (line-beginning-position)))
  15127. (org-eval-in-calendar '(calendar-goto-today))
  15128. (insert "."))))
  15129. (org-defkey map (kbd "C-.")
  15130. (lambda () (interactive)
  15131. (org-eval-in-calendar '(calendar-goto-today))))
  15132. (org-defkey map [(meta shift left)]
  15133. (lambda () (interactive)
  15134. (org-eval-in-calendar '(calendar-backward-month 1))))
  15135. (org-defkey map [(meta shift right)]
  15136. (lambda () (interactive)
  15137. (org-eval-in-calendar '(calendar-forward-month 1))))
  15138. (org-defkey map [(meta shift up)]
  15139. (lambda () (interactive)
  15140. (org-eval-in-calendar '(calendar-backward-year 1))))
  15141. (org-defkey map [(meta shift down)]
  15142. (lambda () (interactive)
  15143. (org-eval-in-calendar '(calendar-forward-year 1))))
  15144. (org-defkey map [?\e (shift left)]
  15145. (lambda () (interactive)
  15146. (org-eval-in-calendar '(calendar-backward-month 1))))
  15147. (org-defkey map [?\e (shift right)]
  15148. (lambda () (interactive)
  15149. (org-eval-in-calendar '(calendar-forward-month 1))))
  15150. (org-defkey map [?\e (shift up)]
  15151. (lambda () (interactive)
  15152. (org-eval-in-calendar '(calendar-backward-year 1))))
  15153. (org-defkey map [?\e (shift down)]
  15154. (lambda () (interactive)
  15155. (org-eval-in-calendar '(calendar-forward-year 1))))
  15156. (org-defkey map [(shift up)]
  15157. (lambda () (interactive)
  15158. (org-eval-in-calendar '(calendar-backward-week 1))))
  15159. (org-defkey map [(shift down)]
  15160. (lambda () (interactive)
  15161. (org-eval-in-calendar '(calendar-forward-week 1))))
  15162. (org-defkey map [(shift left)]
  15163. (lambda () (interactive)
  15164. (org-eval-in-calendar '(calendar-backward-day 1))))
  15165. (org-defkey map [(shift right)]
  15166. (lambda () (interactive)
  15167. (org-eval-in-calendar '(calendar-forward-day 1))))
  15168. (org-defkey map "!"
  15169. (lambda () (interactive)
  15170. (org-eval-in-calendar '(diary-view-entries))
  15171. (message "")))
  15172. (org-defkey map ">"
  15173. (lambda () (interactive)
  15174. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15175. (org-defkey map "<"
  15176. (lambda () (interactive)
  15177. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15178. (org-defkey map "\C-v"
  15179. (lambda () (interactive)
  15180. (org-eval-in-calendar
  15181. '(calendar-scroll-left-three-months 1))))
  15182. (org-defkey map "\M-v"
  15183. (lambda () (interactive)
  15184. (org-eval-in-calendar
  15185. '(calendar-scroll-right-three-months 1))))
  15186. map)
  15187. "Keymap for minibuffer commands when using `org-read-date'.")
  15188. (defvar org-def)
  15189. (defvar org-defdecode)
  15190. (defvar org-with-time)
  15191. (defvar calendar-setup) ; Dynamically scoped.
  15192. (defun org-read-date (&optional with-time to-time from-string prompt
  15193. default-time default-input inactive)
  15194. "Read a date, possibly a time, and make things smooth for the user.
  15195. The prompt will suggest to enter an ISO date, but you can also enter anything
  15196. which will at least partially be understood by `parse-time-string'.
  15197. Unrecognized parts of the date will default to the current day, month, year,
  15198. hour and minute. If this command is called to replace a timestamp at point,
  15199. or to enter the second timestamp of a range, the default time is taken
  15200. from the existing stamp. Furthermore, the command prefers the future,
  15201. so if you are giving a date where the year is not given, and the day-month
  15202. combination is already past in the current year, it will assume you
  15203. mean next year. For details, see the manual. A few examples:
  15204. 3-2-5 --> 2003-02-05
  15205. feb 15 --> currentyear-02-15
  15206. 2/15 --> currentyear-02-15
  15207. sep 12 9 --> 2009-09-12
  15208. 12:45 --> today 12:45
  15209. 22 sept 0:34 --> currentyear-09-22 0:34
  15210. 12 --> currentyear-currentmonth-12
  15211. Fri --> nearest Friday after today
  15212. -Tue --> last Tuesday
  15213. etc.
  15214. Furthermore you can specify a relative date by giving, as the *first* thing
  15215. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15216. change in days weeks, months, years.
  15217. With a single plus or minus, the date is relative to today. With a double
  15218. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15219. +4d --> four days from today
  15220. +4 --> same as above
  15221. +2w --> two weeks from today
  15222. ++5 --> five days from default date
  15223. The function understands only English month and weekday abbreviations.
  15224. While prompting, a calendar is popped up - you can also select the
  15225. date with the mouse (button 1). The calendar shows a period of three
  15226. months. To scroll it to other months, use the keys `>' and `<'.
  15227. If you don't like the calendar, turn it off with
  15228. (setq org-read-date-popup-calendar nil)
  15229. With optional argument TO-TIME, the date will immediately be converted
  15230. to an internal time.
  15231. With an optional argument WITH-TIME, the prompt will suggest to
  15232. also insert a time. Note that when WITH-TIME is not set, you can
  15233. still enter a time, and this function will inform the calling routine
  15234. about this change. The calling routine may then choose to change the
  15235. format used to insert the time stamp into the buffer to include the time.
  15236. With optional argument FROM-STRING, read from this string instead from
  15237. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15238. the time/date that is used for everything that is not specified by the
  15239. user."
  15240. (require 'parse-time)
  15241. (let* ((org-with-time with-time)
  15242. (org-time-stamp-rounding-minutes
  15243. (if (equal org-with-time '(16))
  15244. '(0 0)
  15245. org-time-stamp-rounding-minutes))
  15246. (org-dcst org-display-custom-times)
  15247. (ct (org-current-time))
  15248. (org-def (or org-overriding-default-time default-time ct))
  15249. (org-defdecode (decode-time org-def))
  15250. (cur-frame (selected-frame))
  15251. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15252. (calendar-setup
  15253. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15254. (calendar-move-hook nil)
  15255. (calendar-view-diary-initially-flag nil)
  15256. (calendar-view-holidays-initially-flag nil)
  15257. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15258. ;; Rationalize `org-def' and `org-defdecode', if required.
  15259. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15260. (setf (nth 2 org-defdecode) -1)
  15261. (setf (nth 1 org-defdecode) 59)
  15262. (setq org-def (apply #'encode-time org-defdecode))
  15263. (setq org-defdecode (decode-time org-def)))
  15264. (let* ((timestr (format-time-string
  15265. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15266. org-def))
  15267. (prompt (concat (if prompt (concat prompt " ") "")
  15268. (format "Date+time [%s]: " timestr))))
  15269. (cond
  15270. (from-string (setq ans from-string))
  15271. (org-read-date-popup-calendar
  15272. (save-excursion
  15273. (save-window-excursion
  15274. (calendar)
  15275. (when (eq calendar-setup 'calendar-only)
  15276. (setq cal-frame
  15277. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15278. (select-frame cal-frame))
  15279. (org-eval-in-calendar '(setq cursor-type nil) t)
  15280. (unwind-protect
  15281. (progn
  15282. (calendar-forward-day (- (time-to-days org-def)
  15283. (calendar-absolute-from-gregorian
  15284. (calendar-current-date))))
  15285. (org-eval-in-calendar nil t)
  15286. (let* ((old-map (current-local-map))
  15287. (map (copy-keymap calendar-mode-map))
  15288. (minibuffer-local-map
  15289. (copy-keymap org-read-date-minibuffer-local-map)))
  15290. (org-defkey map (kbd "RET") 'org-calendar-select)
  15291. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15292. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15293. (unwind-protect
  15294. (progn
  15295. (use-local-map map)
  15296. (setq org-read-date-inactive inactive)
  15297. (add-hook 'post-command-hook 'org-read-date-display)
  15298. (setq org-ans0
  15299. (read-string prompt
  15300. default-input
  15301. 'org-read-date-history
  15302. nil))
  15303. ;; org-ans0: from prompt
  15304. ;; org-ans1: from mouse click
  15305. ;; org-ans2: from calendar motion
  15306. (setq ans
  15307. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15308. (remove-hook 'post-command-hook 'org-read-date-display)
  15309. (use-local-map old-map)
  15310. (when org-read-date-overlay
  15311. (delete-overlay org-read-date-overlay)
  15312. (setq org-read-date-overlay nil)))))
  15313. (bury-buffer "*Calendar*")
  15314. (when cal-frame
  15315. (delete-frame cal-frame)
  15316. (select-frame-set-input-focus cur-frame))))))
  15317. (t ; Naked prompt only
  15318. (unwind-protect
  15319. (setq ans (read-string prompt default-input
  15320. 'org-read-date-history timestr))
  15321. (when org-read-date-overlay
  15322. (delete-overlay org-read-date-overlay)
  15323. (setq org-read-date-overlay nil))))))
  15324. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15325. (when org-read-date-analyze-forced-year
  15326. (message "Year was forced into %s"
  15327. (if org-read-date-force-compatible-dates
  15328. "compatible range (1970-2037)"
  15329. "range representable on this machine"))
  15330. (ding))
  15331. ;; One round trip to get rid of 34th of August and stuff like that....
  15332. (setq final (decode-time (apply 'encode-time final)))
  15333. (setq org-read-date-final-answer ans)
  15334. (if to-time
  15335. (apply 'encode-time final)
  15336. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15337. (format "%04d-%02d-%02d %02d:%02d"
  15338. (nth 5 final) (nth 4 final) (nth 3 final)
  15339. (nth 2 final) (nth 1 final))
  15340. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15341. (defun org-read-date-display ()
  15342. "Display the current date prompt interpretation in the minibuffer."
  15343. (when org-read-date-display-live
  15344. (when org-read-date-overlay
  15345. (delete-overlay org-read-date-overlay))
  15346. (when (minibufferp (current-buffer))
  15347. (save-excursion
  15348. (end-of-line 1)
  15349. (while (not (equal (buffer-substring
  15350. (max (point-min) (- (point) 4)) (point))
  15351. " "))
  15352. (insert " ")))
  15353. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15354. " " (or org-ans1 org-ans2)))
  15355. (org-end-time-was-given nil)
  15356. (f (org-read-date-analyze ans org-def org-defdecode))
  15357. (fmts (if org-dcst
  15358. org-time-stamp-custom-formats
  15359. org-time-stamp-formats))
  15360. (fmt (if (or org-with-time
  15361. (and (boundp 'org-time-was-given) org-time-was-given))
  15362. (cdr fmts)
  15363. (car fmts)))
  15364. (txt (format-time-string fmt (apply 'encode-time f)))
  15365. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15366. (txt (concat "=> " txt)))
  15367. (when (and org-end-time-was-given
  15368. (string-match org-plain-time-of-day-regexp txt))
  15369. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15370. org-end-time-was-given
  15371. (substring txt (match-end 0)))))
  15372. (when org-read-date-analyze-futurep
  15373. (setq txt (concat txt " (=>F)")))
  15374. (setq org-read-date-overlay
  15375. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15376. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15377. (defun org-read-date-analyze (ans def defdecode)
  15378. "Analyze the combined answer of the date prompt."
  15379. ;; FIXME: cleanup and comment
  15380. ;; Pass `current-time' result to `decode-time' (instead of calling
  15381. ;; without arguments) so that only `current-time' has to be
  15382. ;; overridden in tests.
  15383. (let ((org-def def)
  15384. (org-defdecode defdecode)
  15385. (nowdecode (decode-time (current-time)))
  15386. delta deltan deltaw deltadef year month day
  15387. hour minute second wday pm h2 m2 tl wday1
  15388. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15389. (setq org-read-date-analyze-futurep nil
  15390. org-read-date-analyze-forced-year nil)
  15391. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15392. (setq ans "+0"))
  15393. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15394. (setq ans (replace-match "" t t ans)
  15395. deltan (car delta)
  15396. deltaw (nth 1 delta)
  15397. deltadef (nth 2 delta)))
  15398. ;; Check if there is an iso week date in there. If yes, store the
  15399. ;; info and postpone interpreting it until the rest of the parsing
  15400. ;; is done.
  15401. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15402. (setq iso-year (when (match-end 1)
  15403. (org-small-year-to-year
  15404. (string-to-number (match-string 1 ans))))
  15405. iso-weekday (when (match-end 3)
  15406. (string-to-number (match-string 3 ans)))
  15407. iso-week (string-to-number (match-string 2 ans)))
  15408. (setq ans (replace-match "" t t ans)))
  15409. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15410. (when (string-match
  15411. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15412. (setq year (if (match-end 2)
  15413. (string-to-number (match-string 2 ans))
  15414. (progn (setq kill-year t)
  15415. (string-to-number (format-time-string "%Y"))))
  15416. month (string-to-number (match-string 3 ans))
  15417. day (string-to-number (match-string 4 ans)))
  15418. (setq year (org-small-year-to-year year))
  15419. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15420. t nil ans)))
  15421. ;; Help matching dotted european dates
  15422. (when (string-match
  15423. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15424. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15425. (setq kill-year t)
  15426. (string-to-number (format-time-string "%Y")))
  15427. day (string-to-number (match-string 1 ans))
  15428. month (string-to-number (match-string 2 ans))
  15429. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15430. t nil ans)))
  15431. ;; Help matching american dates, like 5/30 or 5/30/7
  15432. (when (string-match
  15433. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15434. (setq year (if (match-end 4)
  15435. (string-to-number (match-string 4 ans))
  15436. (progn (setq kill-year t)
  15437. (string-to-number (format-time-string "%Y"))))
  15438. month (string-to-number (match-string 1 ans))
  15439. day (string-to-number (match-string 2 ans)))
  15440. (setq year (org-small-year-to-year year))
  15441. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15442. t nil ans)))
  15443. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15444. ;; If there is a time with am/pm, and *no* time without it, we convert
  15445. ;; so that matching will be successful.
  15446. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15447. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15448. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15449. (setq hour (string-to-number (match-string 1 ans))
  15450. minute (if (match-end 3)
  15451. (string-to-number (match-string 3 ans))
  15452. 0)
  15453. pm (equal ?p
  15454. (string-to-char (downcase (match-string 4 ans)))))
  15455. (if (and (= hour 12) (not pm))
  15456. (setq hour 0)
  15457. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15458. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15459. t t ans))))
  15460. ;; Check if a time range is given as a duration
  15461. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15462. (setq hour (string-to-number (match-string 1 ans))
  15463. h2 (+ hour (string-to-number (match-string 3 ans)))
  15464. minute (string-to-number (match-string 2 ans))
  15465. m2 (+ minute (if (match-end 5) (string-to-number
  15466. (match-string 5 ans))0)))
  15467. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15468. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15469. t t ans)))
  15470. ;; Check if there is a time range
  15471. (when (boundp 'org-end-time-was-given)
  15472. (setq org-time-was-given nil)
  15473. (when (and (string-match org-plain-time-of-day-regexp ans)
  15474. (match-end 8))
  15475. (setq org-end-time-was-given (match-string 8 ans))
  15476. (setq ans (concat (substring ans 0 (match-beginning 7))
  15477. (substring ans (match-end 7))))))
  15478. (setq tl (parse-time-string ans)
  15479. day (or (nth 3 tl) (nth 3 org-defdecode))
  15480. month
  15481. (cond ((nth 4 tl))
  15482. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15483. ;; Day was specified. Make sure DAY+MONTH
  15484. ;; combination happens in the future.
  15485. ((nth 3 tl)
  15486. (setq futurep t)
  15487. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15488. (nth 4 nowdecode)))
  15489. (t (nth 4 org-defdecode)))
  15490. year
  15491. (cond ((and (not kill-year) (nth 5 tl)))
  15492. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15493. ;; Month was guessed in the future and is at least
  15494. ;; equal to NOWDECODE's. Fix year accordingly.
  15495. (futurep
  15496. (if (or (> month (nth 4 nowdecode))
  15497. (>= day (nth 3 nowdecode)))
  15498. (nth 5 nowdecode)
  15499. (1+ (nth 5 nowdecode))))
  15500. ;; Month was specified. Make sure MONTH+YEAR
  15501. ;; combination happens in the future.
  15502. ((nth 4 tl)
  15503. (setq futurep t)
  15504. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15505. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15506. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15507. (t (nth 5 nowdecode))))
  15508. (t (nth 5 org-defdecode)))
  15509. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15510. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15511. second (or (nth 0 tl) 0)
  15512. wday (nth 6 tl))
  15513. (when (and (eq org-read-date-prefer-future 'time)
  15514. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15515. (equal day (nth 3 nowdecode))
  15516. (equal month (nth 4 nowdecode))
  15517. (equal year (nth 5 nowdecode))
  15518. (nth 2 tl)
  15519. (or (< (nth 2 tl) (nth 2 nowdecode))
  15520. (and (= (nth 2 tl) (nth 2 nowdecode))
  15521. (nth 1 tl)
  15522. (< (nth 1 tl) (nth 1 nowdecode)))))
  15523. (setq day (1+ day)
  15524. futurep t))
  15525. ;; Special date definitions below
  15526. (cond
  15527. (iso-week
  15528. ;; There was an iso week
  15529. (require 'cal-iso)
  15530. (setq futurep nil)
  15531. (setq year (or iso-year year)
  15532. day (or iso-weekday wday 1)
  15533. wday nil ; to make sure that the trigger below does not match
  15534. iso-date (calendar-gregorian-from-absolute
  15535. (calendar-iso-to-absolute
  15536. (list iso-week day year))))
  15537. ; FIXME: Should we also push ISO weeks into the future?
  15538. ; (when (and org-read-date-prefer-future
  15539. ; (not iso-year)
  15540. ; (< (calendar-absolute-from-gregorian iso-date)
  15541. ; (time-to-days (current-time))))
  15542. ; (setq year (1+ year)
  15543. ; iso-date (calendar-gregorian-from-absolute
  15544. ; (calendar-iso-to-absolute
  15545. ; (list iso-week day year)))))
  15546. (setq month (car iso-date)
  15547. year (nth 2 iso-date)
  15548. day (nth 1 iso-date)))
  15549. (deltan
  15550. (setq futurep nil)
  15551. (unless deltadef
  15552. ;; Pass `current-time' result to `decode-time' (instead of
  15553. ;; calling without arguments) so that only `current-time' has
  15554. ;; to be overridden in tests.
  15555. (let ((now (decode-time (current-time))))
  15556. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15557. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15558. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15559. ((equal deltaw "m") (setq month (+ month deltan)))
  15560. ((equal deltaw "y") (setq year (+ year deltan)))))
  15561. ((and wday (not (nth 3 tl)))
  15562. ;; Weekday was given, but no day, so pick that day in the week
  15563. ;; on or after the derived date.
  15564. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15565. (unless (equal wday wday1)
  15566. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15567. (when (and (boundp 'org-time-was-given)
  15568. (nth 2 tl))
  15569. (setq org-time-was-given t))
  15570. (when (< year 100) (setq year (+ 2000 year)))
  15571. ;; Check of the date is representable
  15572. (if org-read-date-force-compatible-dates
  15573. (progn
  15574. (when (< year 1970)
  15575. (setq year 1970 org-read-date-analyze-forced-year t))
  15576. (when (> year 2037)
  15577. (setq year 2037 org-read-date-analyze-forced-year t)))
  15578. (condition-case nil
  15579. (ignore (encode-time second minute hour day month year))
  15580. (error
  15581. (setq year (nth 5 org-defdecode))
  15582. (setq org-read-date-analyze-forced-year t))))
  15583. (setq org-read-date-analyze-futurep futurep)
  15584. (list second minute hour day month year)))
  15585. (defvar parse-time-weekdays)
  15586. (defun org-read-date-get-relative (s today default)
  15587. "Check string S for special relative date string.
  15588. TODAY and DEFAULT are internal times, for today and for a default.
  15589. Return shift list (N what def-flag)
  15590. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15591. N is the number of WHATs to shift.
  15592. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15593. the DEFAULT date rather than TODAY."
  15594. (require 'parse-time)
  15595. (when (and
  15596. (string-match
  15597. (concat
  15598. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15599. "\\([0-9]+\\)?"
  15600. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15601. "\\([ \t]\\|$\\)") s)
  15602. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15603. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15604. (string-to-char (substring (match-string 1 s) -1))
  15605. ?+))
  15606. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15607. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15608. (what (if (match-end 3) (match-string 3 s) "d"))
  15609. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15610. (date (if rel default today))
  15611. (wday (nth 6 (decode-time date)))
  15612. delta)
  15613. (if wday1
  15614. (progn
  15615. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15616. (when (= delta 0) (setq delta 7))
  15617. (when (= dir ?-)
  15618. (setq delta (- delta 7))
  15619. (when (= delta 0) (setq delta -7)))
  15620. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15621. (list delta "d" rel))
  15622. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15623. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15624. "Turn a user-specified date into the internal representation.
  15625. The internal representation needed by the calendar is (month day year).
  15626. This is a wrapper to handle the brain-dead convention in calendar that
  15627. user function argument order change dependent on argument order."
  15628. (pcase calendar-date-style
  15629. (`american (list arg1 arg2 arg3))
  15630. (`european (list arg2 arg1 arg3))
  15631. (`iso (list arg2 arg3 arg1))))
  15632. (defun org-eval-in-calendar (form &optional keepdate)
  15633. "Eval FORM in the calendar window and return to current window.
  15634. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15635. (let ((sf (selected-frame))
  15636. (sw (selected-window)))
  15637. (select-window (get-buffer-window "*Calendar*" t))
  15638. (eval form)
  15639. (when (and (not keepdate) (calendar-cursor-to-date))
  15640. (let* ((date (calendar-cursor-to-date))
  15641. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15642. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15643. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15644. (select-window sw)
  15645. (select-frame-set-input-focus sf)))
  15646. (defun org-calendar-select ()
  15647. "Return to `org-read-date' with the date currently selected.
  15648. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15649. (interactive)
  15650. (when (calendar-cursor-to-date)
  15651. (let* ((date (calendar-cursor-to-date))
  15652. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15653. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15654. (when (active-minibuffer-window) (exit-minibuffer))))
  15655. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15656. "Insert a date stamp for the date given by the internal TIME.
  15657. See `format-time-string' for the format of TIME.
  15658. WITH-HM means use the stamp format that includes the time of the day.
  15659. INACTIVE means use square brackets instead of angular ones, so that the
  15660. stamp will not contribute to the agenda.
  15661. PRE and POST are optional strings to be inserted before and after the
  15662. stamp.
  15663. The command returns the inserted time stamp."
  15664. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15665. stamp)
  15666. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15667. (insert-before-markers (or pre ""))
  15668. (when (listp extra)
  15669. (setq extra (car extra))
  15670. (if (and (stringp extra)
  15671. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15672. (setq extra (format "-%02d:%02d"
  15673. (string-to-number (match-string 1 extra))
  15674. (string-to-number (match-string 2 extra))))
  15675. (setq extra nil)))
  15676. (when extra
  15677. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15678. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15679. (insert-before-markers (or post ""))
  15680. (setq org-last-inserted-timestamp stamp)))
  15681. (defun org-toggle-time-stamp-overlays ()
  15682. "Toggle the use of custom time stamp formats."
  15683. (interactive)
  15684. (setq org-display-custom-times (not org-display-custom-times))
  15685. (unless org-display-custom-times
  15686. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15687. (while (setq p (next-single-property-change p 'display))
  15688. (when (and (get-text-property p 'display)
  15689. (eq (get-text-property p 'face) 'org-date))
  15690. (remove-text-properties
  15691. p (setq p (next-single-property-change p 'display))
  15692. '(display t))))
  15693. (set-buffer-modified-p bmp)))
  15694. (org-restart-font-lock)
  15695. (setq org-table-may-need-update t)
  15696. (if org-display-custom-times
  15697. (message "Time stamps are overlaid with custom format")
  15698. (message "Time stamp overlays removed")))
  15699. (defun org-display-custom-time (beg end)
  15700. "Overlay modified time stamp format over timestamp between BEG and END."
  15701. (let* ((ts (buffer-substring beg end))
  15702. t1 with-hm tf time str (off 0))
  15703. (save-match-data
  15704. (setq t1 (org-parse-time-string ts t))
  15705. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15706. (setq off (- (match-end 0) (match-beginning 0)))))
  15707. (setq end (- end off))
  15708. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  15709. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15710. time (org-fix-decoded-time t1)
  15711. str (org-add-props
  15712. (format-time-string
  15713. (substring tf 1 -1) (apply 'encode-time time))
  15714. nil 'mouse-face 'highlight))
  15715. (put-text-property beg end 'display str)))
  15716. (defun org-fix-decoded-time (time)
  15717. "Set 0 instead of nil for the first 6 elements of time.
  15718. Don't touch the rest."
  15719. (let ((n 0))
  15720. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15721. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15722. "Difference between TIMESTAMP-STRING and now in days.
  15723. If SECONDS is non-nil, return the difference in seconds."
  15724. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15725. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15726. (funcall fdiff (current-time)))))
  15727. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15728. "Is the time in TIMESTAMP-STRING close to the current date?"
  15729. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15730. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15731. (not (org-entry-is-done-p))))
  15732. (defun org-get-wdays (ts &optional delay zero-delay)
  15733. "Get the deadline lead time appropriate for timestring TS.
  15734. When DELAY is non-nil, get the delay time for scheduled items
  15735. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15736. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15737. don't try to find the delay cookie in the scheduled timestamp."
  15738. (let ((tv (if delay org-scheduled-delay-days
  15739. org-deadline-warning-days)))
  15740. (cond
  15741. ((or (and delay (< tv 0))
  15742. (and delay zero-delay (<= tv 0))
  15743. (and (not delay) (<= tv 0)))
  15744. ;; Enforce this value no matter what
  15745. (- tv))
  15746. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15747. ;; lead time is specified.
  15748. (floor (* (string-to-number (match-string 1 ts))
  15749. (cdr (assoc (match-string 2 ts)
  15750. '(("d" . 1) ("w" . 7)
  15751. ("m" . 30.4) ("y" . 365.25)
  15752. ("h" . 0.041667)))))))
  15753. ;; go for the default.
  15754. (t tv))))
  15755. (defun org-calendar-select-mouse (ev)
  15756. "Return to `org-read-date' with the date currently selected.
  15757. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15758. (interactive "e")
  15759. (mouse-set-point ev)
  15760. (when (calendar-cursor-to-date)
  15761. (let* ((date (calendar-cursor-to-date))
  15762. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15763. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15764. (when (active-minibuffer-window) (exit-minibuffer))))
  15765. (defun org-check-deadlines (ndays)
  15766. "Check if there are any deadlines due or past due.
  15767. A deadline is considered due if it happens within `org-deadline-warning-days'
  15768. days from today's date. If the deadline appears in an entry marked DONE,
  15769. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15770. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15771. are shown."
  15772. (interactive "P")
  15773. (let* ((org-warn-days
  15774. (cond
  15775. ((equal ndays '(4)) 100000)
  15776. (ndays (prefix-numeric-value ndays))
  15777. (t (abs org-deadline-warning-days))))
  15778. (case-fold-search nil)
  15779. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15780. (callback
  15781. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15782. (message "%d deadlines past-due or due within %d days"
  15783. (org-occur regexp nil callback)
  15784. org-warn-days)))
  15785. (defsubst org-re-timestamp (type)
  15786. "Return a regexp for timestamp TYPE.
  15787. Allowed values for TYPE are:
  15788. all: all timestamps
  15789. active: only active timestamps (<...>)
  15790. inactive: only inactive timestamps ([...])
  15791. scheduled: only scheduled timestamps
  15792. deadline: only deadline timestamps
  15793. closed: only closed time-stamps
  15794. When TYPE is nil, fall back on returning a regexp that matches
  15795. both scheduled and deadline timestamps."
  15796. (cl-case type
  15797. (all org-ts-regexp-both)
  15798. (active org-ts-regexp)
  15799. (inactive org-ts-regexp-inactive)
  15800. (scheduled org-scheduled-time-regexp)
  15801. (deadline org-deadline-time-regexp)
  15802. (closed org-closed-time-regexp)
  15803. (otherwise
  15804. (concat "\\<"
  15805. (regexp-opt (list org-deadline-string org-scheduled-string))
  15806. " *<\\([^>]+\\)>"))))
  15807. (defun org-check-before-date (d)
  15808. "Check if there are deadlines or scheduled entries before date D."
  15809. (interactive (list (org-read-date)))
  15810. (let* ((case-fold-search nil)
  15811. (regexp (org-re-timestamp org-ts-type))
  15812. (ts-type org-ts-type)
  15813. (callback
  15814. (lambda ()
  15815. (let ((match (match-string 1)))
  15816. (and (if (memq ts-type '(active inactive all))
  15817. (eq (org-element-type (save-excursion
  15818. (backward-char)
  15819. (org-element-context)))
  15820. 'timestamp)
  15821. (org-at-planning-p))
  15822. (time-less-p
  15823. (org-time-string-to-time match t)
  15824. (org-time-string-to-time d t)))))))
  15825. (message "%d entries before %s"
  15826. (org-occur regexp nil callback)
  15827. d)))
  15828. (defun org-check-after-date (d)
  15829. "Check if there are deadlines or scheduled entries after date D."
  15830. (interactive (list (org-read-date)))
  15831. (let* ((case-fold-search nil)
  15832. (regexp (org-re-timestamp org-ts-type))
  15833. (ts-type org-ts-type)
  15834. (callback
  15835. (lambda ()
  15836. (let ((match (match-string 1)))
  15837. (and (if (memq ts-type '(active inactive all))
  15838. (eq (org-element-type (save-excursion
  15839. (backward-char)
  15840. (org-element-context)))
  15841. 'timestamp)
  15842. (org-at-planning-p))
  15843. (not (time-less-p
  15844. (org-time-string-to-time match t)
  15845. (org-time-string-to-time d t))))))))
  15846. (message "%d entries after %s"
  15847. (org-occur regexp nil callback)
  15848. d)))
  15849. (defun org-check-dates-range (start-date end-date)
  15850. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15851. (interactive (list (org-read-date nil nil nil "Range starts")
  15852. (org-read-date nil nil nil "Range end")))
  15853. (let ((case-fold-search nil)
  15854. (regexp (org-re-timestamp org-ts-type))
  15855. (callback
  15856. (let ((type org-ts-type))
  15857. (lambda ()
  15858. (let ((match (match-string 1)))
  15859. (and
  15860. (if (memq type '(active inactive all))
  15861. (eq (org-element-type (save-excursion
  15862. (backward-char)
  15863. (org-element-context)))
  15864. 'timestamp)
  15865. (org-at-planning-p))
  15866. (not (time-less-p
  15867. (org-time-string-to-time match t)
  15868. (org-time-string-to-time start-date t)))
  15869. (time-less-p
  15870. (org-time-string-to-time match t)
  15871. (org-time-string-to-time end-date t))))))))
  15872. (message "%d entries between %s and %s"
  15873. (org-occur regexp nil callback) start-date end-date)))
  15874. (defun org-evaluate-time-range (&optional to-buffer)
  15875. "Evaluate a time range by computing the difference between start and end.
  15876. Normally the result is just printed in the echo area, but with prefix arg
  15877. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15878. If the time range is actually in a table, the result is inserted into the
  15879. next column.
  15880. For time difference computation, a year is assumed to be exactly 365
  15881. days in order to avoid rounding problems."
  15882. (interactive "P")
  15883. (or
  15884. (org-clock-update-time-maybe)
  15885. (save-excursion
  15886. (unless (org-at-date-range-p t)
  15887. (goto-char (point-at-bol))
  15888. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15889. (unless (org-at-date-range-p t)
  15890. (user-error "Not at a time-stamp range, and none found in current line")))
  15891. (let* ((ts1 (match-string 1))
  15892. (ts2 (match-string 2))
  15893. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15894. (match-end (match-end 0))
  15895. (time1 (org-time-string-to-time ts1))
  15896. (time2 (org-time-string-to-time ts2))
  15897. (t1 (float-time time1))
  15898. (t2 (float-time time2))
  15899. (diff (abs (- t2 t1)))
  15900. (negative (< (- t2 t1) 0))
  15901. ;; (ys (floor (* 365 24 60 60)))
  15902. (ds (* 24 60 60))
  15903. (hs (* 60 60))
  15904. (fy "%dy %dd %02d:%02d")
  15905. (fy1 "%dy %dd")
  15906. (fd "%dd %02d:%02d")
  15907. (fd1 "%dd")
  15908. (fh "%02d:%02d")
  15909. y d h m align)
  15910. (if havetime
  15911. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15912. y 0
  15913. d (floor (/ diff ds)) diff (mod diff ds)
  15914. h (floor (/ diff hs)) diff (mod diff hs)
  15915. m (floor (/ diff 60)))
  15916. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15917. y 0
  15918. d (floor (+ (/ diff ds) 0.5))
  15919. h 0 m 0))
  15920. (if (not to-buffer)
  15921. (message "%s" (org-make-tdiff-string y d h m))
  15922. (if (org-at-table-p)
  15923. (progn
  15924. (goto-char match-end)
  15925. (setq align t)
  15926. (and (looking-at " *|") (goto-char (match-end 0))))
  15927. (goto-char match-end))
  15928. (when (looking-at
  15929. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15930. (replace-match ""))
  15931. (when negative (insert " -"))
  15932. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15933. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15934. (insert " " (format fh h m))))
  15935. (when align (org-table-align))
  15936. (message "Time difference inserted")))))
  15937. (defun org-make-tdiff-string (y d h m)
  15938. (let ((fmt "")
  15939. (l nil))
  15940. (when (> y 0)
  15941. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15942. (push y l))
  15943. (when (> d 0)
  15944. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15945. (push d l))
  15946. (when (> h 0)
  15947. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15948. (push h l))
  15949. (when (> m 0)
  15950. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15951. (push m l))
  15952. (apply 'format fmt (nreverse l))))
  15953. (defun org-time-string-to-time (s &optional zone)
  15954. "Convert timestamp string S into internal time.
  15955. The optional ZONE is omitted or nil for Emacs local time, t for
  15956. Universal Time, ‘wall’ for system wall clock time, or a string as
  15957. in the TZ environment variable."
  15958. (apply #'encode-time (org-parse-time-string s nil zone)))
  15959. (defun org-time-string-to-seconds (s &optional zone)
  15960. "Convert a timestamp string S into a number of seconds.
  15961. The optional ZONE is omitted or nil for Emacs local time, t for
  15962. Universal Time, ‘wall’ for system wall clock time, or a string as
  15963. in the TZ environment variable."
  15964. (float-time (org-time-string-to-time s zone)))
  15965. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  15966. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  15967. "Convert time stamp S to an absolute day number.
  15968. If DAYNR in non-nil, and there is a specifier for a cyclic time
  15969. stamp, get the closest date to DAYNR. If PREFER is
  15970. `past' (respectively `future') return a date past (respectively
  15971. after) or equal to DAYNR.
  15972. POS is the location of time stamp S, as a buffer position in
  15973. BUFFER.
  15974. Diary sexp timestamps are matched against DAYNR, when non-nil.
  15975. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  15976. signaled."
  15977. (cond
  15978. ((string-match "\\`%%\\((.*)\\)" s)
  15979. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  15980. ;; only able to match individual dates. If it fails, raise an
  15981. ;; error.
  15982. (if (and daynr
  15983. (org-diary-sexp-entry
  15984. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  15985. daynr
  15986. (signal 'org-diary-sexp-no-match (list s))))
  15987. (daynr (org-closest-date s daynr prefer))
  15988. (t (time-to-days
  15989. (condition-case errdata
  15990. (apply #'encode-time (org-parse-time-string s))
  15991. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15992. s
  15993. (if (not (and buffer pos)) ""
  15994. (format-message " at %d in buffer `%s'" pos buffer))
  15995. (cdr errdata))))))))
  15996. (defun org-days-to-iso-week (days)
  15997. "Return the iso week number."
  15998. (require 'cal-iso)
  15999. (car (calendar-iso-from-absolute days)))
  16000. (defun org-small-year-to-year (year)
  16001. "Convert 2-digit years into 4-digit years.
  16002. YEAR is expanded into one of the 30 next years, if possible, or
  16003. into a past one. Any year larger than 99 is returned unchanged."
  16004. (if (>= year 100) year
  16005. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16006. (century (/ current 100))
  16007. (offset (- year (% current 100))))
  16008. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16009. ((> offset -70) (+ (* century 100) year))
  16010. (t (+ (* (1+ century) 100) year))))))
  16011. (defun org-time-from-absolute (d)
  16012. "Return the time corresponding to date D.
  16013. D may be an absolute day number, or a calendar-type list (month day year)."
  16014. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16015. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16016. (defvar org-agenda-current-date)
  16017. (defun org-calendar-holiday ()
  16018. "List of holidays, for Diary display in Org mode."
  16019. (require 'holidays)
  16020. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16021. (and hl (mapconcat #'identity hl "; "))))
  16022. (defun org-diary-sexp-entry (sexp entry d)
  16023. "Process a SEXP diary ENTRY for date D."
  16024. (require 'diary-lib)
  16025. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16026. ;; dynamically.
  16027. (let* ((sexp `(let ((entry ,entry)
  16028. (date ',d))
  16029. ,(car (read-from-string sexp))))
  16030. (result (if calendar-debug-sexp (eval sexp)
  16031. (condition-case nil
  16032. (eval sexp)
  16033. (error
  16034. (beep)
  16035. (message "Bad sexp at line %d in %s: %s"
  16036. (org-current-line)
  16037. (buffer-file-name) sexp)
  16038. (sleep-for 2))))))
  16039. (cond ((stringp result) (split-string result "; "))
  16040. ((and (consp result)
  16041. (not (consp (cdr result)))
  16042. (stringp (cdr result))) (cdr result))
  16043. ((and (consp result)
  16044. (stringp (car result))) result)
  16045. (result entry))))
  16046. (defun org-diary-to-ical-string (frombuf)
  16047. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16048. This uses the icalendar.el library."
  16049. (let* ((tmpdir temporary-file-directory)
  16050. (tmpfile (make-temp-name
  16051. (expand-file-name "orgics" tmpdir)))
  16052. buf rtn b e)
  16053. (with-current-buffer frombuf
  16054. (icalendar-export-region (point-min) (point-max) tmpfile)
  16055. (setq buf (find-buffer-visiting tmpfile))
  16056. (set-buffer buf)
  16057. (goto-char (point-min))
  16058. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16059. (setq b (match-beginning 0)))
  16060. (goto-char (point-max))
  16061. (when (re-search-backward "^END:VEVENT" nil t)
  16062. (setq e (match-end 0)))
  16063. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16064. (kill-buffer buf)
  16065. (delete-file tmpfile)
  16066. rtn))
  16067. (defun org-closest-date (start current prefer)
  16068. "Return closest date to CURRENT starting from START.
  16069. CURRENT and START are both time stamps.
  16070. When PREFER is `past', return a date that is either CURRENT or
  16071. past. When PREFER is `future', return a date that is either
  16072. CURRENT or future.
  16073. Only time stamps with a repeater are modified. Any other time
  16074. stamp stay unchanged. In any case, return value is an absolute
  16075. day number."
  16076. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16077. ;; No repeater. Do not shift time stamp.
  16078. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16079. (let ((value (string-to-number (match-string 1 start)))
  16080. (type (match-string 2 start)))
  16081. (if (= 0 value)
  16082. ;; Repeater with a 0-value is considered as void.
  16083. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16084. (let* ((base (org-date-to-gregorian start))
  16085. (target (org-date-to-gregorian current))
  16086. (sday (calendar-absolute-from-gregorian base))
  16087. (cday (calendar-absolute-from-gregorian target))
  16088. n1 n2)
  16089. ;; If START is already past CURRENT, just return START.
  16090. (if (<= cday sday) sday
  16091. ;; Compute closest date before (N1) and closest date past
  16092. ;; (N2) CURRENT.
  16093. (pcase type
  16094. ("h"
  16095. (let ((missing-hours
  16096. (mod (+ (- (* 24 (- cday sday))
  16097. (nth 2 (org-parse-time-string start)))
  16098. org-extend-today-until)
  16099. value)))
  16100. (setf n1 (if (= missing-hours 0) cday
  16101. (- cday (1+ (/ missing-hours 24)))))
  16102. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16103. ((or "d" "w")
  16104. (let ((value (if (equal type "w") (* 7 value) value)))
  16105. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16106. (setf n2 (+ n1 value))))
  16107. ("m"
  16108. (let* ((add-months
  16109. (lambda (d n)
  16110. ;; Add N months to gregorian date D, i.e.,
  16111. ;; a list (MONTH DAY YEAR). Return a valid
  16112. ;; gregorian date.
  16113. (let ((m (+ (nth 0 d) n)))
  16114. (list (mod m 12)
  16115. (nth 1 d)
  16116. (+ (/ m 12) (nth 2 d))))))
  16117. (months ; Complete months to TARGET.
  16118. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16119. (- (nth 0 target) (nth 0 base))
  16120. ;; If START's day is greater than
  16121. ;; TARGET's, remove incomplete month.
  16122. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16123. value)
  16124. value))
  16125. (before (funcall add-months base months)))
  16126. (setf n1 (calendar-absolute-from-gregorian before))
  16127. (setf n2
  16128. (calendar-absolute-from-gregorian
  16129. (funcall add-months before value)))))
  16130. (_
  16131. (let* ((d (nth 1 base))
  16132. (m (nth 0 base))
  16133. (y (nth 2 base))
  16134. (years ; Complete years to TARGET.
  16135. (* (/ (- (nth 2 target)
  16136. y
  16137. ;; If START's month and day are
  16138. ;; greater than TARGET's, remove
  16139. ;; incomplete year.
  16140. (if (or (> (nth 0 target) m)
  16141. (and (= (nth 0 target) m)
  16142. (> (nth 1 target) d)))
  16143. 0
  16144. 1))
  16145. value)
  16146. value))
  16147. (before (list m d (+ y years))))
  16148. (setf n1 (calendar-absolute-from-gregorian before))
  16149. (setf n2 (calendar-absolute-from-gregorian
  16150. (list m d (+ (nth 2 before) value)))))))
  16151. ;; Handle PREFER parameter, if any.
  16152. (cond
  16153. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16154. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16155. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16156. (defun org-date-to-gregorian (d)
  16157. "Turn any specification of date D into a Gregorian date for the calendar."
  16158. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16159. ((and (listp d) (= (length d) 3)) d)
  16160. ((stringp d)
  16161. (let ((d (org-parse-time-string d)))
  16162. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16163. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16164. (defun org-parse-time-string (s &optional nodefault zone)
  16165. "Parse the standard Org time string.
  16166. This should be a lot faster than the normal `parse-time-string'.
  16167. If time is not given, defaults to 0:00. However, with optional
  16168. NODEFAULT, hour and minute fields will be nil if not given.
  16169. The optional ZONE is omitted or nil for Emacs local time, t for
  16170. Universal Time, ‘wall’ for system wall clock time, or a string as
  16171. in the TZ environment variable."
  16172. (cond ((string-match org-ts-regexp0 s)
  16173. (list 0
  16174. (when (or (match-beginning 8) (not nodefault))
  16175. (string-to-number (or (match-string 8 s) "0")))
  16176. (when (or (match-beginning 7) (not nodefault))
  16177. (string-to-number (or (match-string 7 s) "0")))
  16178. (string-to-number (match-string 4 s))
  16179. (string-to-number (match-string 3 s))
  16180. (string-to-number (match-string 2 s))
  16181. nil nil zone))
  16182. ((string-match "^<[^>]+>$" s)
  16183. ;; FIXME: `decode-time' needs to be called with ZONE as its
  16184. ;; second argument. However, this requires at least Emacs
  16185. ;; 25.1. We can do it when we switch to this version as our
  16186. ;; minimal requirement.
  16187. (decode-time (seconds-to-time (org-matcher-time s))))
  16188. (t (error "Not a standard Org time string: %s" s))))
  16189. (defun org-timestamp-up (&optional arg)
  16190. "Increase the date item at the cursor by one.
  16191. If the cursor is on the year, change the year. If it is on the month,
  16192. the day or the time, change that.
  16193. With prefix ARG, change by that many units."
  16194. (interactive "p")
  16195. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16196. (defun org-timestamp-down (&optional arg)
  16197. "Decrease the date item at the cursor by one.
  16198. If the cursor is on the year, change the year. If it is on the month,
  16199. the day or the time, change that.
  16200. With prefix ARG, change by that many units."
  16201. (interactive "p")
  16202. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16203. (defun org-timestamp-up-day (&optional arg)
  16204. "Increase the date in the time stamp by one day.
  16205. With prefix ARG, change that many days."
  16206. (interactive "p")
  16207. (if (and (not (org-at-timestamp-p 'lax))
  16208. (org-at-heading-p))
  16209. (org-todo 'up)
  16210. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16211. (defun org-timestamp-down-day (&optional arg)
  16212. "Decrease the date in the time stamp by one day.
  16213. With prefix ARG, change that many days."
  16214. (interactive "p")
  16215. (if (and (not (org-at-timestamp-p 'lax))
  16216. (org-at-heading-p))
  16217. (org-todo 'down)
  16218. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16219. (defun org-at-timestamp-p (&optional extended)
  16220. "Non-nil if point is inside a timestamp.
  16221. By default, the function only consider syntactically valid active
  16222. timestamps. However, the caller may have a broader definition
  16223. for timestamps. As a consequence, optional argument EXTENDED can
  16224. be set to the following values
  16225. `inactive'
  16226. Include also syntactically valid inactive timestamps.
  16227. `agenda'
  16228. Include timestamps allowed in Agenda, i.e., those in
  16229. properties drawers, planning lines and clock lines.
  16230. `lax'
  16231. Ignore context. The function matches any part of the
  16232. document looking like a timestamp. This includes comments,
  16233. example blocks...
  16234. For backward-compatibility with Org 9.0, every other non-nil
  16235. value is equivalent to `inactive'.
  16236. When at a timestamp, return the position of the point as a symbol
  16237. among `bracket', `after', `year', `month', `hour', `minute',
  16238. `day' or a number of character from the last know part of the
  16239. time stamp.
  16240. When matching, the match groups are the following:
  16241. group 1: year
  16242. group 2: month
  16243. group 3: day number
  16244. group 4: day name
  16245. group 5: hours, if any
  16246. group 6: minutes, if any"
  16247. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16248. (pos (point))
  16249. (match?
  16250. (let ((boundaries (org-in-regexp regexp)))
  16251. (save-match-data
  16252. (cond ((null boundaries) nil)
  16253. ((eq extended 'lax) t)
  16254. (t
  16255. (or (and (eq extended 'agenda)
  16256. (or (org-at-planning-p)
  16257. (org-at-property-p)
  16258. (and (bound-and-true-p
  16259. org-agenda-include-inactive-timestamps)
  16260. (org-at-clock-log-p))))
  16261. (eq 'timestamp
  16262. (save-excursion
  16263. (when (= pos (cdr boundaries)) (forward-char -1))
  16264. (org-element-type (org-element-context)))))))))))
  16265. (cond
  16266. ((not match?) nil)
  16267. ((= pos (match-beginning 0)) 'bracket)
  16268. ;; Distinguish location right before the closing bracket from
  16269. ;; right after it.
  16270. ((= pos (1- (match-end 0))) 'bracket)
  16271. ((= pos (match-end 0)) 'after)
  16272. ((org-pos-in-match-range pos 2) 'year)
  16273. ((org-pos-in-match-range pos 3) 'month)
  16274. ((org-pos-in-match-range pos 7) 'hour)
  16275. ((org-pos-in-match-range pos 8) 'minute)
  16276. ((or (org-pos-in-match-range pos 4)
  16277. (org-pos-in-match-range pos 5)) 'day)
  16278. ((and (> pos (or (match-end 8) (match-end 5)))
  16279. (< pos (match-end 0)))
  16280. (- pos (or (match-end 8) (match-end 5))))
  16281. (t 'day))))
  16282. (defun org-toggle-timestamp-type ()
  16283. "Toggle the type (<active> or [inactive]) of a time stamp."
  16284. (interactive)
  16285. (when (org-at-timestamp-p 'lax)
  16286. (let ((beg (match-beginning 0)) (end (match-end 0))
  16287. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16288. (save-excursion
  16289. (goto-char beg)
  16290. (while (re-search-forward "[][<>]" end t)
  16291. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16292. t t)))
  16293. (message "Timestamp is now %sactive"
  16294. (if (equal (char-after beg) ?<) "" "in")))))
  16295. (defun org-at-clock-log-p ()
  16296. "Non-nil if point is on a clock log line."
  16297. (and (org-match-line org-clock-line-re)
  16298. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16299. (defvar org-clock-history) ; defined in org-clock.el
  16300. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16301. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16302. "Change the date in the time stamp at point.
  16303. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16304. `year', `minute', `second'. If WHAT is not given, the cursor position
  16305. in the timestamp determines what will be changed.
  16306. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16307. (let ((origin (point))
  16308. (timestamp? (org-at-timestamp-p 'lax))
  16309. origin-cat
  16310. with-hm inactive
  16311. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16312. extra rem
  16313. ts time time0 fixnext clrgx)
  16314. (unless timestamp? (user-error "Not at a timestamp"))
  16315. (if (and (not what) (eq timestamp? 'bracket))
  16316. (org-toggle-timestamp-type)
  16317. ;; Point isn't on brackets. Remember the part of the time-stamp
  16318. ;; the point was in. Indeed, size of time-stamps may change,
  16319. ;; but point must be kept in the same category nonetheless.
  16320. (setq origin-cat timestamp?)
  16321. (when (and (not what) (not (eq timestamp? 'day))
  16322. org-display-custom-times
  16323. (get-text-property (point) 'display)
  16324. (not (get-text-property (1- (point)) 'display)))
  16325. (setq timestamp? 'day))
  16326. (setq timestamp? (or what timestamp?)
  16327. inactive (= (char-after (match-beginning 0)) ?\[)
  16328. ts (match-string 0))
  16329. (replace-match "")
  16330. (when (string-match
  16331. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16332. ts)
  16333. (setq extra (match-string 1 ts))
  16334. (when suppress-tmp-delay
  16335. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16336. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16337. (setq with-hm t))
  16338. (setq time0 (org-parse-time-string ts))
  16339. (when (and updown
  16340. (eq timestamp? 'minute)
  16341. (not current-prefix-arg))
  16342. ;; This looks like s-up and s-down. Change by one rounding step.
  16343. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16344. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16345. (setcar (cdr time0) (+ (nth 1 time0)
  16346. (if (> n 0) (- rem) (- dm rem))))))
  16347. (setq time
  16348. (apply #'encode-time
  16349. (or (car time0) 0)
  16350. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16351. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16352. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16353. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16354. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16355. (nthcdr 6 time0)))
  16356. (when (and (memq timestamp? '(hour minute))
  16357. extra
  16358. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16359. (setq extra (org-modify-ts-extra
  16360. extra
  16361. (if (eq timestamp? 'hour) 2 5)
  16362. n dm)))
  16363. (when (integerp timestamp?)
  16364. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16365. (when (eq what 'calendar)
  16366. (let ((cal-date (org-get-date-from-calendar)))
  16367. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16368. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16369. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16370. (setcar time0 (or (car time0) 0))
  16371. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16372. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16373. (setq time (apply 'encode-time time0))))
  16374. ;; Insert the new time-stamp, and ensure point stays in the same
  16375. ;; category as before (i.e. not after the last position in that
  16376. ;; category).
  16377. (let ((pos (point)))
  16378. ;; Stay before inserted string. `save-excursion' is of no use.
  16379. (setq org-last-changed-timestamp
  16380. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16381. (goto-char pos))
  16382. (save-match-data
  16383. (looking-at org-ts-regexp3)
  16384. (goto-char
  16385. (pcase origin-cat
  16386. ;; `day' category ends before `hour' if any, or at the end
  16387. ;; of the day name.
  16388. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16389. (`hour (min (match-end 7) origin))
  16390. (`minute (min (1- (match-end 8)) origin))
  16391. ((pred integerp) (min (1- (match-end 0)) origin))
  16392. ;; Point was right after the time-stamp. However, the
  16393. ;; time-stamp length might have changed, so refer to
  16394. ;; (match-end 0) instead.
  16395. (`after (match-end 0))
  16396. ;; `year' and `month' have both fixed size: point couldn't
  16397. ;; have moved into another part.
  16398. (_ origin))))
  16399. ;; Update clock if on a CLOCK line.
  16400. (org-clock-update-time-maybe)
  16401. ;; Maybe adjust the closest clock in `org-clock-history'
  16402. (when org-clock-adjust-closest
  16403. (if (not (and (org-at-clock-log-p)
  16404. (< 1 (length (delq nil (mapcar 'marker-position
  16405. org-clock-history))))))
  16406. (message "No clock to adjust")
  16407. (cond ((save-excursion ; fix previous clock?
  16408. (re-search-backward org-ts-regexp0 nil t)
  16409. (looking-back (concat org-clock-string " \\[")
  16410. (line-beginning-position)))
  16411. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16412. ((save-excursion ; fix next clock?
  16413. (re-search-backward org-ts-regexp0 nil t)
  16414. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16415. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16416. (save-window-excursion
  16417. ;; Find closest clock to point, adjust the previous/next one in history
  16418. (let* ((p (save-excursion (org-back-to-heading t)))
  16419. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16420. (clfixnth
  16421. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16422. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16423. (if (not clfixpos)
  16424. (message "No clock to adjust")
  16425. (save-excursion
  16426. (org-goto-marker-or-bmk clfixpos)
  16427. (org-show-subtree)
  16428. (when (re-search-forward clrgx nil t)
  16429. (goto-char (match-beginning 1))
  16430. (let (org-clock-adjust-closest)
  16431. (org-timestamp-change n timestamp? updown))
  16432. (message "Clock adjusted in %s for heading: %s"
  16433. (file-name-nondirectory (buffer-file-name))
  16434. (org-get-heading t t)))))))))
  16435. ;; Try to recenter the calendar window, if any.
  16436. (when (and org-calendar-follow-timestamp-change
  16437. (get-buffer-window "*Calendar*" t)
  16438. (memq timestamp? '(day month year)))
  16439. (org-recenter-calendar (time-to-days time))))))
  16440. (defun org-modify-ts-extra (s pos n dm)
  16441. "Change the different parts of the lead-time and repeat fields in timestamp."
  16442. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16443. ng h m new rem)
  16444. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16445. (cond
  16446. ((or (org-pos-in-match-range pos 2)
  16447. (org-pos-in-match-range pos 3))
  16448. (setq m (string-to-number (match-string 3 s))
  16449. h (string-to-number (match-string 2 s)))
  16450. (if (org-pos-in-match-range pos 2)
  16451. (setq h (+ h n))
  16452. (setq n (* dm (with-no-warnings (signum n))))
  16453. (unless (= 0 (setq rem (% m dm)))
  16454. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16455. (setq m (+ m n)))
  16456. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16457. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16458. (setq h (mod h 24))
  16459. (setq ng 1 new (format "-%02d:%02d" h m)))
  16460. ((org-pos-in-match-range pos 6)
  16461. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16462. ((org-pos-in-match-range pos 5)
  16463. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16464. ((org-pos-in-match-range pos 9)
  16465. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16466. ((org-pos-in-match-range pos 8)
  16467. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16468. (when ng
  16469. (setq s (concat
  16470. (substring s 0 (match-beginning ng))
  16471. new
  16472. (substring s (match-end ng))))))
  16473. s))
  16474. (defun org-recenter-calendar (d)
  16475. "If the calendar is visible, recenter it to date D."
  16476. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16477. (when cwin
  16478. (let ((calendar-move-hook nil))
  16479. (with-selected-window cwin
  16480. (calendar-goto-date
  16481. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16482. (defun org-goto-calendar (&optional arg)
  16483. "Go to the Emacs calendar at the current date.
  16484. If there is a time stamp in the current line, go to that date.
  16485. A prefix ARG can be used to force the current date."
  16486. (interactive "P")
  16487. (let ((calendar-move-hook nil)
  16488. (calendar-view-holidays-initially-flag nil)
  16489. (calendar-view-diary-initially-flag nil)
  16490. diff)
  16491. (when (or (org-at-timestamp-p 'lax)
  16492. (org-match-line (concat ".*" org-ts-regexp)))
  16493. (let ((d1 (time-to-days (current-time)))
  16494. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  16495. (setq diff (- d2 d1))))
  16496. (calendar)
  16497. (calendar-goto-today)
  16498. (when (and diff (not arg)) (calendar-forward-day diff))))
  16499. (defun org-get-date-from-calendar ()
  16500. "Return a list (month day year) of date at point in calendar."
  16501. (with-current-buffer "*Calendar*"
  16502. (save-match-data
  16503. (calendar-cursor-to-date))))
  16504. (defun org-date-from-calendar ()
  16505. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16506. If there is already a time stamp at the cursor position, update it."
  16507. (interactive)
  16508. (if (org-at-timestamp-p 'lax)
  16509. (org-timestamp-change 0 'calendar)
  16510. (let ((cal-date (org-get-date-from-calendar)))
  16511. (org-insert-time-stamp
  16512. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16513. (defcustom org-effort-durations
  16514. `(("min" . 1)
  16515. ("h" . 60)
  16516. ("d" . ,(* 60 8))
  16517. ("w" . ,(* 60 8 5))
  16518. ("m" . ,(* 60 8 5 4))
  16519. ("y" . ,(* 60 8 5 40)))
  16520. "Conversion factor to minutes for an effort modifier.
  16521. Each entry has the form (MODIFIER . MINUTES).
  16522. In an effort string, a number followed by MODIFIER is multiplied
  16523. by the specified number of MINUTES to obtain an effort in
  16524. minutes.
  16525. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16526. effort string \"2hours\" is equivalent to 120 minutes."
  16527. :group 'org-agenda
  16528. :version "26.1"
  16529. :package-version '(Org . "8.3")
  16530. :type '(alist :key-type (string :tag "Modifier")
  16531. :value-type (number :tag "Minutes")))
  16532. (defcustom org-image-actual-width t
  16533. "Should we use the actual width of images when inlining them?
  16534. When set to t, always use the image width.
  16535. When set to a number, use imagemagick (when available) to set
  16536. the image's width to this value.
  16537. When set to a number in a list, try to get the width from any
  16538. #+ATTR.* keyword if it matches a width specification like
  16539. #+ATTR_HTML: :width 300px
  16540. and fall back on that number if none is found.
  16541. When set to nil, try to get the width from an #+ATTR.* keyword
  16542. and fall back on the original width if none is found.
  16543. This requires Emacs >= 24.1, build with imagemagick support."
  16544. :group 'org-appearance
  16545. :version "24.4"
  16546. :package-version '(Org . "8.0")
  16547. :type '(choice
  16548. (const :tag "Use the image width" t)
  16549. (integer :tag "Use a number of pixels")
  16550. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16551. (const :tag "Use #+ATTR* or don't resize" nil)))
  16552. (defcustom org-agenda-inhibit-startup nil
  16553. "Inhibit startup when preparing agenda buffers.
  16554. When this variable is t, the initialization of the Org agenda
  16555. buffers is inhibited: e.g. the visibility state is not set, the
  16556. tables are not re-aligned, etc."
  16557. :type 'boolean
  16558. :version "24.3"
  16559. :group 'org-agenda)
  16560. (defcustom org-agenda-ignore-properties nil
  16561. "Avoid updating text properties when building the agenda.
  16562. Properties are used to prepare buffers for effort estimates,
  16563. appointments, statistics and subtree-local categories.
  16564. If you don't use these in the agenda, you can add them to this
  16565. list and agenda building will be a bit faster.
  16566. The value is a list, with zero or more of the symbols `effort', `appt',
  16567. `stats' or `category'."
  16568. :type '(set :greedy t
  16569. (const effort)
  16570. (const appt)
  16571. (const stats)
  16572. (const category))
  16573. :version "26.1"
  16574. :package-version '(Org . "8.3")
  16575. :group 'org-agenda)
  16576. ;;;; Files
  16577. (defun org-save-all-org-buffers ()
  16578. "Save all Org buffers without user confirmation."
  16579. (interactive)
  16580. (message "Saving all Org buffers...")
  16581. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16582. (when (featurep 'org-id) (org-id-locations-save))
  16583. (message "Saving all Org buffers... done"))
  16584. (defun org-revert-all-org-buffers ()
  16585. "Revert all Org buffers.
  16586. Prompt for confirmation when there are unsaved changes.
  16587. Be sure you know what you are doing before letting this function
  16588. overwrite your changes.
  16589. This function is useful in a setup where one tracks org files
  16590. with a version control system, to revert on one machine after pulling
  16591. changes from another. I believe the procedure must be like this:
  16592. 1. M-x org-save-all-org-buffers
  16593. 2. Pull changes from the other machine, resolve conflicts
  16594. 3. M-x org-revert-all-org-buffers"
  16595. (interactive)
  16596. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16597. (user-error "Abort"))
  16598. (save-excursion
  16599. (save-window-excursion
  16600. (dolist (b (buffer-list))
  16601. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16602. (with-current-buffer b buffer-file-name))
  16603. (pop-to-buffer-same-window b)
  16604. (revert-buffer t 'no-confirm)))
  16605. (when (and (featurep 'org-id) org-id-track-globally)
  16606. (org-id-locations-load)))))
  16607. ;;;; Agenda files
  16608. ;;;###autoload
  16609. (defun org-switchb (&optional arg)
  16610. "Switch between Org buffers.
  16611. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16612. With `\\[universal-argument] \\[universal-argument]' \
  16613. prefix, restrict available buffers to agenda files."
  16614. (interactive "P")
  16615. (let ((blist (org-buffer-list
  16616. (cond ((equal arg '(4)) 'files)
  16617. ((equal arg '(16)) 'agenda)))))
  16618. (pop-to-buffer-same-window
  16619. (completing-read "Org buffer: "
  16620. (mapcar #'list (mapcar #'buffer-name blist))
  16621. nil t))))
  16622. (defun org-buffer-list (&optional predicate exclude-tmp)
  16623. "Return a list of Org buffers.
  16624. PREDICATE can be `export', `files' or `agenda'.
  16625. export restrict the list to Export buffers.
  16626. files restrict the list to buffers visiting Org files.
  16627. agenda restrict the list to buffers visiting agenda files.
  16628. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16629. (let* ((bfn nil)
  16630. (agenda-files (and (eq predicate 'agenda)
  16631. (mapcar 'file-truename (org-agenda-files t))))
  16632. (filter
  16633. (cond
  16634. ((eq predicate 'files)
  16635. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16636. ((eq predicate 'export)
  16637. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16638. ((eq predicate 'agenda)
  16639. (lambda (b)
  16640. (with-current-buffer b
  16641. (and (derived-mode-p 'org-mode)
  16642. (setq bfn (buffer-file-name b))
  16643. (member (file-truename bfn) agenda-files)))))
  16644. (t (lambda (b) (with-current-buffer b
  16645. (or (derived-mode-p 'org-mode)
  16646. (string-match "\\*Org .*Export"
  16647. (buffer-name b)))))))))
  16648. (delq nil
  16649. (mapcar
  16650. (lambda(b)
  16651. (if (and (funcall filter b)
  16652. (or (not exclude-tmp)
  16653. (not (string-match "tmp" (buffer-name b)))))
  16654. b
  16655. nil))
  16656. (buffer-list)))))
  16657. (defun org-agenda-files (&optional unrestricted archives)
  16658. "Get the list of agenda files.
  16659. Optional UNRESTRICTED means return the full list even if a restriction
  16660. is currently in place.
  16661. When ARCHIVES is t, include all archive files that are really being
  16662. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16663. `org-agenda-archives-mode' is t."
  16664. (let ((files
  16665. (cond
  16666. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16667. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16668. ((listp org-agenda-files) org-agenda-files)
  16669. (t (error "Invalid value of `org-agenda-files'")))))
  16670. (setq files (apply 'append
  16671. (mapcar (lambda (f)
  16672. (if (file-directory-p f)
  16673. (directory-files
  16674. f t org-agenda-file-regexp)
  16675. (list f)))
  16676. files)))
  16677. (when org-agenda-skip-unavailable-files
  16678. (setq files (delq nil
  16679. (mapcar (function
  16680. (lambda (file)
  16681. (and (file-readable-p file) file)))
  16682. files))))
  16683. (when (or (eq archives t)
  16684. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16685. (setq files (org-add-archive-files files)))
  16686. files))
  16687. (defun org-agenda-file-p (&optional file)
  16688. "Return non-nil, if FILE is an agenda file.
  16689. If FILE is omitted, use the file associated with the current
  16690. buffer."
  16691. (let ((fname (or file (buffer-file-name))))
  16692. (and fname
  16693. (member (file-truename fname)
  16694. (mapcar #'file-truename (org-agenda-files t))))))
  16695. (defun org-edit-agenda-file-list ()
  16696. "Edit the list of agenda files.
  16697. Depending on setup, this either uses customize to edit the variable
  16698. `org-agenda-files', or it visits the file that is holding the list. In the
  16699. latter case, the buffer is set up in a way that saving it automatically kills
  16700. the buffer and restores the previous window configuration."
  16701. (interactive)
  16702. (if (stringp org-agenda-files)
  16703. (let ((cw (current-window-configuration)))
  16704. (find-file org-agenda-files)
  16705. (setq-local org-window-configuration cw)
  16706. (add-hook 'after-save-hook
  16707. (lambda ()
  16708. (set-window-configuration
  16709. (prog1 org-window-configuration
  16710. (kill-buffer (current-buffer))))
  16711. (org-install-agenda-files-menu)
  16712. (message "New agenda file list installed"))
  16713. nil 'local)
  16714. (message "%s" (substitute-command-keys
  16715. "Edit list and finish with \\[save-buffer]")))
  16716. (customize-variable 'org-agenda-files)))
  16717. (defun org-store-new-agenda-file-list (list)
  16718. "Set new value for the agenda file list and save it correctly."
  16719. (if (stringp org-agenda-files)
  16720. (let ((fe (org-read-agenda-file-list t)) b u)
  16721. (while (setq b (find-buffer-visiting org-agenda-files))
  16722. (kill-buffer b))
  16723. (with-temp-file org-agenda-files
  16724. (insert
  16725. (mapconcat
  16726. (lambda (f) ;; Keep un-expanded entries.
  16727. (if (setq u (assoc f fe))
  16728. (cdr u)
  16729. f))
  16730. list "\n")
  16731. "\n")))
  16732. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16733. (org-insert-mode-line-in-empty-file nil))
  16734. (setq org-agenda-files list)
  16735. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16736. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16737. "Read the list of agenda files from a file.
  16738. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16739. filenames, used by `org-store-new-agenda-file-list' to write back
  16740. un-expanded file names."
  16741. (when (file-directory-p org-agenda-files)
  16742. (error "`org-agenda-files' cannot be a single directory"))
  16743. (when (stringp org-agenda-files)
  16744. (with-temp-buffer
  16745. (insert-file-contents org-agenda-files)
  16746. (mapcar
  16747. (lambda (f)
  16748. (let ((e (expand-file-name (substitute-in-file-name f)
  16749. org-directory)))
  16750. (if pair-with-expansion
  16751. (cons e f)
  16752. e)))
  16753. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16754. ;;;###autoload
  16755. (defun org-cycle-agenda-files ()
  16756. "Cycle through the files in `org-agenda-files'.
  16757. If the current buffer visits an agenda file, find the next one in the list.
  16758. If the current buffer does not, find the first agenda file."
  16759. (interactive)
  16760. (let* ((fs (or (org-agenda-files t)
  16761. (user-error "No agenda files")))
  16762. (files (copy-sequence fs))
  16763. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16764. file)
  16765. (when tcf
  16766. (while (and (setq file (pop files))
  16767. (not (equal (file-truename file) tcf)))))
  16768. (find-file (car (or files fs)))
  16769. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16770. (defun org-agenda-file-to-front (&optional to-end)
  16771. "Move/add the current file to the top of the agenda file list.
  16772. If the file is not present in the list, it is added to the front. If it is
  16773. present, it is moved there. With optional argument TO-END, add/move to the
  16774. end of the list."
  16775. (interactive "P")
  16776. (let ((org-agenda-skip-unavailable-files nil)
  16777. (file-alist (mapcar (lambda (x)
  16778. (cons (file-truename x) x))
  16779. (org-agenda-files t)))
  16780. (ctf (file-truename
  16781. (or buffer-file-name
  16782. (user-error "Please save the current buffer to a file"))))
  16783. x had)
  16784. (setq x (assoc ctf file-alist) had x)
  16785. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16786. (if to-end
  16787. (setq file-alist (append (delq x file-alist) (list x)))
  16788. (setq file-alist (cons x (delq x file-alist))))
  16789. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16790. (org-install-agenda-files-menu)
  16791. (message "File %s to %s of agenda file list"
  16792. (if had "moved" "added") (if to-end "end" "front"))))
  16793. (defun org-remove-file (&optional file)
  16794. "Remove current file from the list of files in variable `org-agenda-files'.
  16795. These are the files which are being checked for agenda entries.
  16796. Optional argument FILE means use this file instead of the current."
  16797. (interactive)
  16798. (let* ((org-agenda-skip-unavailable-files nil)
  16799. (file (or file buffer-file-name
  16800. (user-error "Current buffer does not visit a file")))
  16801. (true-file (file-truename file))
  16802. (afile (abbreviate-file-name file))
  16803. (files (delq nil (mapcar
  16804. (lambda (x)
  16805. (unless (equal true-file
  16806. (file-truename x))
  16807. x))
  16808. (org-agenda-files t)))))
  16809. (if (not (= (length files) (length (org-agenda-files t))))
  16810. (progn
  16811. (org-store-new-agenda-file-list files)
  16812. (org-install-agenda-files-menu)
  16813. (message "Removed from Org Agenda list: %s" afile))
  16814. (message "File was not in list: %s (not removed)" afile))))
  16815. (defun org-file-menu-entry (file)
  16816. (vector file (list 'find-file file) t))
  16817. (defun org-check-agenda-file (file)
  16818. "Make sure FILE exists. If not, ask user what to do."
  16819. (unless (file-exists-p file)
  16820. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16821. (abbreviate-file-name file))
  16822. (let ((r (downcase (read-char-exclusive))))
  16823. (cond
  16824. ((equal r ?r)
  16825. (org-remove-file file)
  16826. (throw 'nextfile t))
  16827. (t (user-error "Abort"))))))
  16828. (defun org-get-agenda-file-buffer (file)
  16829. "Get an agenda buffer visiting FILE.
  16830. If the buffer needs to be created, add it to the list of buffers
  16831. which might be released later."
  16832. (let ((buf (org-find-base-buffer-visiting file)))
  16833. (if buf
  16834. buf ; just return it
  16835. ;; Make a new buffer and remember it
  16836. (setq buf (find-file-noselect file))
  16837. (when buf (push buf org-agenda-new-buffers))
  16838. buf)))
  16839. (defun org-release-buffers (blist)
  16840. "Release all buffers in list, asking the user for confirmation when needed.
  16841. When a buffer is unmodified, it is just killed. When modified, it is saved
  16842. \(if the user agrees) and then killed."
  16843. (let (file)
  16844. (dolist (buf blist)
  16845. (setq file (buffer-file-name buf))
  16846. (when (and (buffer-modified-p buf)
  16847. file
  16848. (y-or-n-p (format "Save file %s? " file)))
  16849. (with-current-buffer buf (save-buffer)))
  16850. (kill-buffer buf))))
  16851. (defun org-agenda-prepare-buffers (files)
  16852. "Create buffers for all agenda files, protect archived trees and comments."
  16853. (interactive)
  16854. (let ((pa '(:org-archived t))
  16855. (pc '(:org-comment t))
  16856. (pall '(:org-archived t :org-comment t))
  16857. (inhibit-read-only t)
  16858. (org-inhibit-startup org-agenda-inhibit-startup)
  16859. (rea (concat ":" org-archive-tag ":"))
  16860. re pos)
  16861. (setq org-tag-alist-for-agenda nil
  16862. org-tag-groups-alist-for-agenda nil)
  16863. (save-excursion
  16864. (save-restriction
  16865. (dolist (file files)
  16866. (catch 'nextfile
  16867. (if (bufferp file)
  16868. (set-buffer file)
  16869. (org-check-agenda-file file)
  16870. (set-buffer (org-get-agenda-file-buffer file)))
  16871. (widen)
  16872. (org-set-regexps-and-options 'tags-only)
  16873. (setq pos (point))
  16874. (or (memq 'category org-agenda-ignore-properties)
  16875. (org-refresh-category-properties))
  16876. (or (memq 'stats org-agenda-ignore-properties)
  16877. (org-refresh-stats-properties))
  16878. (or (memq 'effort org-agenda-ignore-properties)
  16879. (org-refresh-effort-properties))
  16880. (or (memq 'appt org-agenda-ignore-properties)
  16881. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16882. (setq org-todo-keywords-for-agenda
  16883. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16884. (setq org-done-keywords-for-agenda
  16885. (append org-done-keywords-for-agenda org-done-keywords))
  16886. (setq org-todo-keyword-alist-for-agenda
  16887. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16888. (setq org-tag-alist-for-agenda
  16889. (org-uniquify
  16890. (append org-tag-alist-for-agenda
  16891. org-current-tag-alist)))
  16892. ;; Merge current file's tag groups into global
  16893. ;; `org-tag-groups-alist-for-agenda'.
  16894. (when org-group-tags
  16895. (dolist (alist org-tag-groups-alist)
  16896. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16897. (if old
  16898. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16899. (push alist org-tag-groups-alist-for-agenda)))))
  16900. (org-with-silent-modifications
  16901. (save-excursion
  16902. (remove-text-properties (point-min) (point-max) pall)
  16903. (when org-agenda-skip-archived-trees
  16904. (goto-char (point-min))
  16905. (while (re-search-forward rea nil t)
  16906. (when (org-at-heading-p t)
  16907. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16908. (goto-char (point-min))
  16909. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16910. (while (re-search-forward re nil t)
  16911. (when (save-match-data (org-in-commented-heading-p t))
  16912. (add-text-properties
  16913. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16914. (goto-char pos)))))
  16915. (setq org-todo-keywords-for-agenda
  16916. (org-uniquify org-todo-keywords-for-agenda))
  16917. (setq org-todo-keyword-alist-for-agenda
  16918. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16919. ;;;; CDLaTeX minor mode
  16920. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16921. "Keymap for the minor `org-cdlatex-mode'.")
  16922. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16923. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16924. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16925. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16926. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16927. (defvar org-cdlatex-texmathp-advice-is-done nil
  16928. "Flag remembering if we have applied the advice to texmathp already.")
  16929. (define-minor-mode org-cdlatex-mode
  16930. "Toggle the minor `org-cdlatex-mode'.
  16931. This mode supports entering LaTeX environment and math in LaTeX fragments
  16932. in Org mode.
  16933. \\{org-cdlatex-mode-map}"
  16934. nil " OCDL" nil
  16935. (when org-cdlatex-mode
  16936. (require 'cdlatex)
  16937. (run-hooks 'cdlatex-mode-hook)
  16938. (cdlatex-compute-tables))
  16939. (unless org-cdlatex-texmathp-advice-is-done
  16940. (setq org-cdlatex-texmathp-advice-is-done t)
  16941. (defadvice texmathp (around org-math-always-on activate)
  16942. "Always return t in Org buffers.
  16943. This is because we want to insert math symbols without dollars even outside
  16944. the LaTeX math segments. If Org mode thinks that point is actually inside
  16945. an embedded LaTeX fragment, let `texmathp' do its job.
  16946. `\\[org-cdlatex-mode-map]'"
  16947. (interactive)
  16948. (let (p)
  16949. (cond
  16950. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16951. ((eq this-command 'cdlatex-math-symbol)
  16952. (setq ad-return-value t
  16953. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16954. (t
  16955. (let ((p (org-inside-LaTeX-fragment-p)))
  16956. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16957. (setq ad-return-value t
  16958. texmathp-why '("Org mode embedded math" . 0))
  16959. (when p ad-do-it)))))))))
  16960. (defun turn-on-org-cdlatex ()
  16961. "Unconditionally turn on `org-cdlatex-mode'."
  16962. (org-cdlatex-mode 1))
  16963. (defun org-try-cdlatex-tab ()
  16964. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16965. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16966. - inside a LaTeX fragment, or
  16967. - after the first word in a line, where an abbreviation expansion could
  16968. insert a LaTeX environment."
  16969. (when org-cdlatex-mode
  16970. (cond
  16971. ;; Before any word on the line: No expansion possible.
  16972. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  16973. ;; Just after first word on the line: Expand it. Make sure it
  16974. ;; cannot happen on headlines, though.
  16975. ((save-excursion
  16976. (skip-chars-backward "a-zA-Z0-9*")
  16977. (skip-chars-backward " \t")
  16978. (and (bolp) (not (org-at-heading-p))))
  16979. (cdlatex-tab) t)
  16980. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  16981. (defun org-cdlatex-underscore-caret (&optional _arg)
  16982. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  16983. Revert to the normal definition outside of these fragments."
  16984. (interactive "P")
  16985. (if (org-inside-LaTeX-fragment-p)
  16986. (call-interactively 'cdlatex-sub-superscript)
  16987. (let (org-cdlatex-mode)
  16988. (call-interactively (key-binding (vector last-input-event))))))
  16989. (defun org-cdlatex-math-modify (&optional _arg)
  16990. "Execute `cdlatex-math-modify' in LaTeX fragments.
  16991. Revert to the normal definition outside of these fragments."
  16992. (interactive "P")
  16993. (if (org-inside-LaTeX-fragment-p)
  16994. (call-interactively 'cdlatex-math-modify)
  16995. (let (org-cdlatex-mode)
  16996. (call-interactively (key-binding (vector last-input-event))))))
  16997. (defun org-cdlatex-environment-indent (&optional environment item)
  16998. "Execute `cdlatex-environment' and indent the inserted environment.
  16999. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17000. The inserted environment is indented to current indentation
  17001. unless point is at the beginning of the line, in which the
  17002. environment remains unintended."
  17003. (interactive)
  17004. ;; cdlatex-environment always return nil. Therefore, capture output
  17005. ;; first and determine if an environment was selected.
  17006. (let* ((beg (point-marker))
  17007. (end (copy-marker (point) t))
  17008. (inserted (progn
  17009. (ignore-errors (cdlatex-environment environment item))
  17010. (< beg end)))
  17011. ;; Figure out how many lines to move forward after the
  17012. ;; environment has been inserted.
  17013. (lines (when inserted
  17014. (save-excursion
  17015. (- (cl-loop while (< beg (point))
  17016. with x = 0
  17017. do (forward-line -1)
  17018. (cl-incf x)
  17019. finally return x)
  17020. (if (progn (goto-char beg)
  17021. (and (progn (skip-chars-forward " \t") (eolp))
  17022. (progn (skip-chars-backward " \t") (bolp))))
  17023. 1 0)))))
  17024. (env (org-trim (delete-and-extract-region beg end))))
  17025. (when inserted
  17026. ;; Get indentation of next line unless at column 0.
  17027. (let ((ind (if (bolp) 0
  17028. (save-excursion
  17029. (org-return-indent)
  17030. (prog1 (org-get-indentation)
  17031. (when (progn (skip-chars-forward " \t") (eolp))
  17032. (delete-region beg (point)))))))
  17033. (bol (progn (skip-chars-backward " \t") (bolp))))
  17034. ;; Insert a newline before environment unless at column zero
  17035. ;; to "escape" the current line. Insert a newline if
  17036. ;; something is one the same line as \end{ENVIRONMENT}.
  17037. (insert
  17038. (concat (unless bol "\n") env
  17039. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17040. (unless (zerop ind)
  17041. (save-excursion
  17042. (goto-char beg)
  17043. (while (< (point) end)
  17044. (unless (eolp) (indent-line-to ind))
  17045. (forward-line))))
  17046. (goto-char beg)
  17047. (forward-line lines)
  17048. (indent-line-to ind)))
  17049. (set-marker beg nil)
  17050. (set-marker end nil)))
  17051. ;;;; LaTeX fragments
  17052. (defun org-inside-LaTeX-fragment-p ()
  17053. "Test if point is inside a LaTeX fragment.
  17054. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17055. sequence appearing also before point.
  17056. Even though the matchers for math are configurable, this function assumes
  17057. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17058. delimiters are skipped when they have been removed by customization.
  17059. The return value is nil, or a cons cell with the delimiter and the
  17060. position of this delimiter.
  17061. This function does a reasonably good job, but can locally be fooled by
  17062. for example currency specifications. For example it will assume being in
  17063. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17064. fragments that are properly closed, but during editing, we have to live
  17065. with the uncertainty caused by missing closing delimiters. This function
  17066. looks only before point, not after."
  17067. (catch 'exit
  17068. (let ((pos (point))
  17069. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17070. (lim (save-excursion (org-backward-paragraph) (point)))
  17071. dd-on str (start 0) m re)
  17072. (goto-char pos)
  17073. (when dodollar
  17074. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17075. re (nth 1 (assoc "$" org-latex-regexps)))
  17076. (while (string-match re str start)
  17077. (cond
  17078. ((= (match-end 0) (length str))
  17079. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17080. ((= (match-end 0) (- (length str) 5))
  17081. (throw 'exit nil))
  17082. (t (setq start (match-end 0))))))
  17083. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17084. (goto-char pos)
  17085. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17086. (and (match-beginning 2) (throw 'exit nil))
  17087. ;; count $$
  17088. (while (re-search-backward "\\$\\$" lim t)
  17089. (setq dd-on (not dd-on)))
  17090. (goto-char pos)
  17091. (when dd-on (cons "$$" m))))))
  17092. (defun org-inside-latex-macro-p ()
  17093. "Is point inside a LaTeX macro or its arguments?"
  17094. (save-match-data
  17095. (org-in-regexp
  17096. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17097. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17098. "Build an overlay between BEG and END using IMAGE file.
  17099. Argument IMAGETYPE is the extension of the displayed image,
  17100. as a string. It defaults to \"png\"."
  17101. (let ((ov (make-overlay beg end))
  17102. (imagetype (or (intern imagetype) 'png)))
  17103. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17104. (overlay-put ov 'evaporate t)
  17105. (overlay-put ov
  17106. 'modification-hooks
  17107. (list (lambda (o _flag _beg _end &optional _l)
  17108. (delete-overlay o))))
  17109. (overlay-put ov
  17110. 'display
  17111. (list 'image :type imagetype :file image :ascent 'center))))
  17112. (defun org--list-latex-overlays (&optional beg end)
  17113. "List all Org LaTeX overlays in current buffer.
  17114. Limit to overlays between BEG and END when those are provided."
  17115. (cl-remove-if-not
  17116. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17117. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17118. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17119. "Remove all overlays with LaTeX fragment images in current buffer.
  17120. When optional arguments BEG and END are non-nil, remove all
  17121. overlays between them instead. Return a non-nil value when some
  17122. overlays were removed, nil otherwise."
  17123. (let ((overlays (org--list-latex-overlays beg end)))
  17124. (mapc #'delete-overlay overlays)
  17125. overlays))
  17126. (defun org-toggle-latex-fragment (&optional arg)
  17127. "Preview the LaTeX fragment at point, or all locally or globally.
  17128. If the cursor is on a LaTeX fragment, create the image and overlay
  17129. it over the source code, if there is none. Remove it otherwise.
  17130. If there is no fragment at point, display all fragments in the
  17131. current section.
  17132. With prefix ARG, preview or clear image for all fragments in the
  17133. current subtree or in the whole buffer when used before the first
  17134. headline. With a prefix ARG `\\[universal-argument] \
  17135. \\[universal-argument]' preview or clear images
  17136. for all fragments in the buffer."
  17137. (interactive "P")
  17138. (when (display-graphic-p)
  17139. (catch 'exit
  17140. (save-excursion
  17141. (let (beg end msg)
  17142. (cond
  17143. ((or (equal arg '(16))
  17144. (and (equal arg '(4))
  17145. (org-with-limited-levels (org-before-first-heading-p))))
  17146. (if (org-remove-latex-fragment-image-overlays)
  17147. (progn (message "LaTeX fragments images removed from buffer")
  17148. (throw 'exit nil))
  17149. (setq msg "Creating images for buffer...")))
  17150. ((equal arg '(4))
  17151. (org-with-limited-levels (org-back-to-heading t))
  17152. (setq beg (point))
  17153. (setq end (progn (org-end-of-subtree t) (point)))
  17154. (if (org-remove-latex-fragment-image-overlays beg end)
  17155. (progn
  17156. (message "LaTeX fragment images removed from subtree")
  17157. (throw 'exit nil))
  17158. (setq msg "Creating images for subtree...")))
  17159. ((let ((datum (org-element-context)))
  17160. (when (memq (org-element-type datum)
  17161. '(latex-environment latex-fragment))
  17162. (setq beg (org-element-property :begin datum))
  17163. (setq end (org-element-property :end datum))
  17164. (if (org-remove-latex-fragment-image-overlays beg end)
  17165. (progn (message "LaTeX fragment image removed")
  17166. (throw 'exit nil))
  17167. (setq msg "Creating image...")))))
  17168. (t
  17169. (org-with-limited-levels
  17170. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17171. (outline-previous-heading)
  17172. (point)))
  17173. (setq end (progn (outline-next-heading) (point)))
  17174. (if (org-remove-latex-fragment-image-overlays beg end)
  17175. (progn
  17176. (message "LaTeX fragment images removed from section")
  17177. (throw 'exit nil))
  17178. (setq msg "Creating images for section...")))))
  17179. (let ((file (buffer-file-name (buffer-base-buffer))))
  17180. (org-format-latex
  17181. (concat org-preview-latex-image-directory "org-ltximg")
  17182. beg end
  17183. ;; Emacs cannot overlay images from remote hosts. Create
  17184. ;; it in `temporary-file-directory' instead.
  17185. (if (or (not file) (file-remote-p file))
  17186. temporary-file-directory
  17187. default-directory)
  17188. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17189. (message (concat msg "done")))))))
  17190. (defun org-format-latex
  17191. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17192. "Replace LaTeX fragments with links to an image.
  17193. The function takes care of creating the replacement image.
  17194. Only consider fragments between BEG and END when those are
  17195. provided.
  17196. When optional argument OVERLAYS is non-nil, display the image on
  17197. top of the fragment instead of replacing it.
  17198. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17199. Some of the options can be changed using the variable
  17200. `org-format-latex-options', which see."
  17201. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17202. (unless (eq processing-type 'verbatim)
  17203. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17204. (cnt 0)
  17205. checkdir-flag)
  17206. (goto-char (or beg (point-min)))
  17207. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17208. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17209. (overlay-recenter (or end (point-max))))
  17210. (while (re-search-forward math-regexp end t)
  17211. (unless (and overlays
  17212. (eq (get-char-property (point) 'org-overlay-type)
  17213. 'org-latex-overlay))
  17214. (let* ((context (org-element-context))
  17215. (type (org-element-type context)))
  17216. (when (memq type '(latex-environment latex-fragment))
  17217. (let ((block-type (eq type 'latex-environment))
  17218. (value (org-element-property :value context))
  17219. (beg (org-element-property :begin context))
  17220. (end (save-excursion
  17221. (goto-char (org-element-property :end context))
  17222. (skip-chars-backward " \r\t\n")
  17223. (point))))
  17224. (cond
  17225. ((eq processing-type 'mathjax)
  17226. ;; Prepare for MathJax processing.
  17227. (if (not (string-match "\\`\\$\\$?" value))
  17228. (goto-char end)
  17229. (delete-region beg end)
  17230. (if (string= (match-string 0 value) "$$")
  17231. (insert "\\[" (substring value 2 -2) "\\]")
  17232. (insert "\\(" (substring value 1 -1) "\\)"))))
  17233. ((assq processing-type org-preview-latex-process-alist)
  17234. ;; Process to an image.
  17235. (cl-incf cnt)
  17236. (goto-char beg)
  17237. (let* ((processing-info
  17238. (cdr (assq processing-type org-preview-latex-process-alist)))
  17239. (face (face-at-point))
  17240. ;; Get the colors from the face at point.
  17241. (fg
  17242. (let ((color (plist-get org-format-latex-options
  17243. :foreground)))
  17244. (if (and forbuffer (eq color 'auto))
  17245. (face-attribute face :foreground nil 'default)
  17246. color)))
  17247. (bg
  17248. (let ((color (plist-get org-format-latex-options
  17249. :background)))
  17250. (if (and forbuffer (eq color 'auto))
  17251. (face-attribute face :background nil 'default)
  17252. color)))
  17253. (hash (sha1 (prin1-to-string
  17254. (list org-format-latex-header
  17255. org-latex-default-packages-alist
  17256. org-latex-packages-alist
  17257. org-format-latex-options
  17258. forbuffer value fg bg))))
  17259. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17260. (absprefix (expand-file-name prefix dir))
  17261. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17262. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17263. (sep (and block-type "\n\n"))
  17264. (link (concat sep "[[file:" linkfile "]]" sep))
  17265. (options
  17266. (org-combine-plists
  17267. org-format-latex-options
  17268. `(:foreground ,fg :background ,bg))))
  17269. (when msg (message msg cnt))
  17270. (unless checkdir-flag ; Ensure the directory exists.
  17271. (setq checkdir-flag t)
  17272. (let ((todir (file-name-directory absprefix)))
  17273. (unless (file-directory-p todir)
  17274. (make-directory todir t))))
  17275. (unless (file-exists-p movefile)
  17276. (org-create-formula-image
  17277. value movefile options forbuffer processing-type))
  17278. (if overlays
  17279. (progn
  17280. (dolist (o (overlays-in beg end))
  17281. (when (eq (overlay-get o 'org-overlay-type)
  17282. 'org-latex-overlay)
  17283. (delete-overlay o)))
  17284. (org--format-latex-make-overlay beg end movefile imagetype)
  17285. (goto-char end))
  17286. (delete-region beg end)
  17287. (insert
  17288. (org-add-props link
  17289. (list 'org-latex-src
  17290. (replace-regexp-in-string "\"" "" value)
  17291. 'org-latex-src-embed-type
  17292. (if block-type 'paragraph 'character)))))))
  17293. ((eq processing-type 'mathml)
  17294. ;; Process to MathML.
  17295. (unless (org-format-latex-mathml-available-p)
  17296. (user-error "LaTeX to MathML converter not configured"))
  17297. (cl-incf cnt)
  17298. (when msg (message msg cnt))
  17299. (goto-char beg)
  17300. (delete-region beg end)
  17301. (insert (org-format-latex-as-mathml
  17302. value block-type prefix dir)))
  17303. (t
  17304. (error "Unknown conversion process %s for LaTeX fragments"
  17305. processing-type)))))))))))
  17306. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17307. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17308. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17309. sucessful, return the portion between \"<math...> </math>\"
  17310. elements otherwise return nil. When MATHML-FILE is specified,
  17311. write the results in to that file. When invoked as an
  17312. interactive command, prompt for LATEX-FRAG, with initial value
  17313. set to the current active region and echo the results for user
  17314. inspection."
  17315. (interactive (list (let ((frag (when (org-region-active-p)
  17316. (buffer-substring-no-properties
  17317. (region-beginning) (region-end)))))
  17318. (read-string "LaTeX Fragment: " frag nil frag))))
  17319. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17320. (let* ((tmp-in-file
  17321. (let ((file (file-relative-name
  17322. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17323. (write-region latex-frag nil file)
  17324. file))
  17325. (tmp-out-file (file-relative-name
  17326. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17327. (cmd (format-spec
  17328. org-latex-to-mathml-convert-command
  17329. `((?j . ,(and org-latex-to-mathml-jar-file
  17330. (shell-quote-argument
  17331. (expand-file-name
  17332. org-latex-to-mathml-jar-file))))
  17333. (?I . ,(shell-quote-argument tmp-in-file))
  17334. (?i . ,latex-frag)
  17335. (?o . ,(shell-quote-argument tmp-out-file)))))
  17336. mathml shell-command-output)
  17337. (when (called-interactively-p 'any)
  17338. (unless (org-format-latex-mathml-available-p)
  17339. (user-error "LaTeX to MathML converter not configured")))
  17340. (message "Running %s" cmd)
  17341. (setq shell-command-output (shell-command-to-string cmd))
  17342. (setq mathml
  17343. (when (file-readable-p tmp-out-file)
  17344. (with-current-buffer (find-file-noselect tmp-out-file t)
  17345. (goto-char (point-min))
  17346. (when (re-search-forward
  17347. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17348. (regexp-quote
  17349. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17350. nil t)
  17351. (prog1 (match-string 0) (kill-buffer))))))
  17352. (cond
  17353. (mathml
  17354. (setq mathml
  17355. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17356. (when mathml-file
  17357. (write-region mathml nil mathml-file))
  17358. (when (called-interactively-p 'any)
  17359. (message mathml)))
  17360. ((message "LaTeX to MathML conversion failed")
  17361. (message shell-command-output)))
  17362. (delete-file tmp-in-file)
  17363. (when (file-exists-p tmp-out-file)
  17364. (delete-file tmp-out-file))
  17365. mathml))
  17366. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17367. prefix &optional dir)
  17368. "Use `org-create-math-formula' but check local cache first."
  17369. (let* ((absprefix (expand-file-name prefix dir))
  17370. (print-length nil) (print-level nil)
  17371. (formula-id (concat
  17372. "formula-"
  17373. (sha1
  17374. (prin1-to-string
  17375. (list latex-frag
  17376. org-latex-to-mathml-convert-command)))))
  17377. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17378. (formula-cache-dir (file-name-directory formula-cache)))
  17379. (unless (file-directory-p formula-cache-dir)
  17380. (make-directory formula-cache-dir t))
  17381. (unless (file-exists-p formula-cache)
  17382. (org-create-math-formula latex-frag formula-cache))
  17383. (if (file-exists-p formula-cache)
  17384. ;; Successful conversion. Return the link to MathML file.
  17385. (org-add-props
  17386. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17387. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17388. 'org-latex-src-embed-type (if latex-frag-type
  17389. 'paragraph 'character)))
  17390. ;; Failed conversion. Return the LaTeX fragment verbatim
  17391. latex-frag)))
  17392. (defun org--get-display-dpi ()
  17393. "Get the DPI of the display.
  17394. The function assumes that the display has the same pixel width in
  17395. the horizontal and vertical directions."
  17396. (if (display-graphic-p)
  17397. (round (/ (display-pixel-height)
  17398. (/ (display-mm-height) 25.4)))
  17399. (error "Attempt to calculate the dpi of a non-graphic display")))
  17400. (defun org-create-formula-image
  17401. (string tofile options buffer &optional processing-type)
  17402. "Create an image from LaTeX source using external processes.
  17403. The LaTeX STRING is saved to a temporary LaTeX file, then
  17404. converted to an image file by process PROCESSING-TYPE defined in
  17405. `org-preview-latex-process-alist'. A nil value defaults to
  17406. `org-preview-latex-default-process'.
  17407. The generated image file is eventually moved to TOFILE.
  17408. The OPTIONS argument controls the size, foreground color and
  17409. background color of the generated image.
  17410. When BUFFER non-nil, this function is used for LaTeX previewing.
  17411. Otherwise, it is used to deal with LaTeX snippets showed in
  17412. a HTML file."
  17413. (let* ((processing-type (or processing-type
  17414. org-preview-latex-default-process))
  17415. (processing-info
  17416. (cdr (assq processing-type org-preview-latex-process-alist)))
  17417. (programs (plist-get processing-info :programs))
  17418. (error-message (or (plist-get processing-info :message) ""))
  17419. (use-xcolor (plist-get processing-info :use-xcolor))
  17420. (image-input-type (plist-get processing-info :image-input-type))
  17421. (image-output-type (plist-get processing-info :image-output-type))
  17422. (post-clean (or (plist-get processing-info :post-clean)
  17423. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17424. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17425. (latex-header
  17426. (or (plist-get processing-info :latex-header)
  17427. (org-latex-make-preamble
  17428. (org-export-get-environment (org-export-get-backend 'latex))
  17429. org-format-latex-header
  17430. 'snippet)))
  17431. (latex-compiler (plist-get processing-info :latex-compiler))
  17432. (image-converter (plist-get processing-info :image-converter))
  17433. (tmpdir temporary-file-directory)
  17434. (texfilebase (make-temp-name
  17435. (expand-file-name "orgtex" tmpdir)))
  17436. (texfile (concat texfilebase ".tex"))
  17437. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17438. '(1.0 . 1.0)))
  17439. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17440. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17441. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17442. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17443. "Black"))
  17444. (bg (or (plist-get options (if buffer :background :html-background))
  17445. "Transparent"))
  17446. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17447. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17448. (dolist (program programs)
  17449. (org-check-external-command program error-message))
  17450. (if use-xcolor
  17451. (progn (if (eq fg 'default)
  17452. (setq fg (org-latex-color :foreground))
  17453. (setq fg (org-latex-color-format fg)))
  17454. (if (eq bg 'default)
  17455. (setq bg (org-latex-color :background))
  17456. (setq bg (org-latex-color-format
  17457. (if (string= bg "Transparent") "white" bg))))
  17458. (with-temp-file texfile
  17459. (insert latex-header)
  17460. (insert "\n\\begin{document}\n"
  17461. "\\definecolor{fg}{rgb}{" fg "}\n"
  17462. "\\definecolor{bg}{rgb}{" bg "}\n"
  17463. "\n\\pagecolor{bg}\n"
  17464. "\n{\\color{fg}\n"
  17465. string
  17466. "\n}\n"
  17467. "\n\\end{document}\n")))
  17468. (if (eq fg 'default)
  17469. (setq fg (org-dvipng-color :foreground))
  17470. (unless (string= fg "Transparent")
  17471. (setq fg (org-dvipng-color-format fg))))
  17472. (if (eq bg 'default)
  17473. (setq bg (org-dvipng-color :background))
  17474. (unless (string= bg "Transparent")
  17475. (setq bg (org-dvipng-color-format bg))))
  17476. (with-temp-file texfile
  17477. (insert latex-header)
  17478. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17479. (let* ((err-msg (format "Please adjust `%s' part of \
  17480. `org-preview-latex-process-alist'."
  17481. processing-type))
  17482. (image-input-file
  17483. (org-compile-file
  17484. texfile latex-compiler image-input-type err-msg log-buf))
  17485. (image-output-file
  17486. (org-compile-file
  17487. image-input-file image-converter image-output-type err-msg log-buf
  17488. `((?F . ,(shell-quote-argument fg))
  17489. (?B . ,(shell-quote-argument bg))
  17490. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17491. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17492. (copy-file image-output-file tofile 'replace)
  17493. (dolist (e post-clean)
  17494. (when (file-exists-p (concat texfilebase e))
  17495. (delete-file (concat texfilebase e))))
  17496. image-output-file)))
  17497. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17498. "Fill a LaTeX header template TPL.
  17499. In the template, the following place holders will be recognized:
  17500. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17501. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17502. [PACKAGES] \\usepackage statements for PKG
  17503. [NO-PACKAGES] do not include PKG
  17504. [EXTRA] the string EXTRA
  17505. [NO-EXTRA] do not include EXTRA
  17506. For backward compatibility, if both the positive and the negative place
  17507. holder is missing, the positive one (without the \"NO-\") will be
  17508. assumed to be present at the end of the template.
  17509. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17510. EXTRA is a string.
  17511. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17512. (let (rpl (end ""))
  17513. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17514. (setq rpl (if (or (match-end 1) (not def-pkg))
  17515. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17516. tpl (replace-match rpl t t tpl))
  17517. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17518. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17519. (setq rpl (if (or (match-end 1) (not pkg))
  17520. "" (org-latex-packages-to-string pkg snippets-p t))
  17521. tpl (replace-match rpl t t tpl))
  17522. (when pkg (setq end
  17523. (concat end "\n"
  17524. (org-latex-packages-to-string pkg snippets-p)))))
  17525. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17526. (setq rpl (if (or (match-end 1) (not extra))
  17527. "" (concat extra "\n"))
  17528. tpl (replace-match rpl t t tpl))
  17529. (when (and extra (string-match "\\S-" extra))
  17530. (setq end (concat end "\n" extra))))
  17531. (if (string-match "\\S-" end)
  17532. (concat tpl "\n" end)
  17533. tpl)))
  17534. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17535. "Turn an alist of packages into a string with the \\usepackage macros."
  17536. (setq pkg (mapconcat (lambda(p)
  17537. (cond
  17538. ((stringp p) p)
  17539. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17540. (format "%% Package %s omitted" (cadr p)))
  17541. ((equal "" (car p))
  17542. (format "\\usepackage{%s}" (cadr p)))
  17543. (t
  17544. (format "\\usepackage[%s]{%s}"
  17545. (car p) (cadr p)))))
  17546. pkg
  17547. "\n"))
  17548. (if newline (concat pkg "\n") pkg))
  17549. (defun org-dvipng-color (attr)
  17550. "Return a RGB color specification for dvipng."
  17551. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17552. (defun org-dvipng-color-format (color-name)
  17553. "Convert COLOR-NAME to a RGB color value for dvipng."
  17554. (apply #'format "rgb %s %s %s"
  17555. (mapcar 'org-normalize-color
  17556. (color-values color-name))))
  17557. (defun org-latex-color (attr)
  17558. "Return a RGB color for the LaTeX color package."
  17559. (org-latex-color-format (face-attribute 'default attr nil)))
  17560. (defun org-latex-color-format (color-name)
  17561. "Convert COLOR-NAME to a RGB color value."
  17562. (apply #'format "%s,%s,%s"
  17563. (mapcar 'org-normalize-color
  17564. (color-values color-name))))
  17565. (defun org-normalize-color (value)
  17566. "Return string to be used as color value for an RGB component."
  17567. (format "%g" (/ value 65535.0)))
  17568. ;; Image display
  17569. (defvar-local org-inline-image-overlays nil)
  17570. (defun org-toggle-inline-images (&optional include-linked)
  17571. "Toggle the display of inline images.
  17572. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17573. (interactive "P")
  17574. (if org-inline-image-overlays
  17575. (progn
  17576. (org-remove-inline-images)
  17577. (when (called-interactively-p 'interactive)
  17578. (message "Inline image display turned off")))
  17579. (org-display-inline-images include-linked)
  17580. (when (called-interactively-p 'interactive)
  17581. (message (if org-inline-image-overlays
  17582. (format "%d images displayed inline"
  17583. (length org-inline-image-overlays))
  17584. "No images to display inline")))))
  17585. (defun org-redisplay-inline-images ()
  17586. "Refresh the display of inline images."
  17587. (interactive)
  17588. (if (not org-inline-image-overlays)
  17589. (org-toggle-inline-images)
  17590. (org-toggle-inline-images)
  17591. (org-toggle-inline-images)))
  17592. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17593. "Display inline images.
  17594. An inline image is a link which follows either of these
  17595. conventions:
  17596. 1. Its path is a file with an extension matching return value
  17597. from `image-file-name-regexp' and it has no contents.
  17598. 2. Its description consists in a single link of the previous
  17599. type.
  17600. When optional argument INCLUDE-LINKED is non-nil, also links with
  17601. a text description part will be inlined. This can be nice for
  17602. a quick look at those images, but it does not reflect what
  17603. exported files will look like.
  17604. When optional argument REFRESH is non-nil, refresh existing
  17605. images between BEG and END. This will create new image displays
  17606. only if necessary. BEG and END default to the buffer
  17607. boundaries."
  17608. (interactive "P")
  17609. (when (display-graphic-p)
  17610. (unless refresh
  17611. (org-remove-inline-images)
  17612. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17613. (org-with-wide-buffer
  17614. (goto-char (or beg (point-min)))
  17615. (let* ((case-fold-search t)
  17616. (file-extension-re (image-file-name-regexp))
  17617. (link-abbrevs (mapcar #'car
  17618. (append org-link-abbrev-alist-local
  17619. org-link-abbrev-alist)))
  17620. ;; Check absolute, relative file names and explicit
  17621. ;; "file:" links. Also check link abbreviations since
  17622. ;; some might expand to "file" links.
  17623. (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
  17624. (and link-abbrevs
  17625. (format "\\|\\(?:%s:\\)"
  17626. (regexp-opt link-abbrevs))))))
  17627. (while (re-search-forward file-types-re end t)
  17628. (let ((link (save-match-data (org-element-context))))
  17629. ;; Check if we're at an inline image, i.e., an image file
  17630. ;; link without a description (unless INCLUDE-LINKED is
  17631. ;; non-nil).
  17632. (when (and (equal "file" (org-element-property :type link))
  17633. (or include-linked
  17634. (null (org-element-contents link)))
  17635. (string-match-p file-extension-re
  17636. (org-element-property :path link)))
  17637. (let ((file (expand-file-name
  17638. (org-link-unescape
  17639. (org-element-property :path link)))))
  17640. (when (file-exists-p file)
  17641. (let ((width
  17642. ;; Apply `org-image-actual-width' specifications.
  17643. (cond
  17644. ((not (image-type-available-p 'imagemagick)) nil)
  17645. ((eq org-image-actual-width t) nil)
  17646. ((listp org-image-actual-width)
  17647. (or
  17648. ;; First try to find a width among
  17649. ;; attributes associated to the paragraph
  17650. ;; containing link.
  17651. (let ((paragraph
  17652. (let ((e link))
  17653. (while (and (setq e (org-element-property
  17654. :parent e))
  17655. (not (eq (org-element-type e)
  17656. 'paragraph))))
  17657. e)))
  17658. (when paragraph
  17659. (save-excursion
  17660. (goto-char (org-element-property :begin paragraph))
  17661. (when
  17662. (re-search-forward
  17663. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17664. (org-element-property
  17665. :post-affiliated paragraph)
  17666. t)
  17667. (string-to-number (match-string 1))))))
  17668. ;; Otherwise, fall-back to provided number.
  17669. (car org-image-actual-width)))
  17670. ((numberp org-image-actual-width)
  17671. org-image-actual-width)))
  17672. (old (get-char-property-and-overlay
  17673. (org-element-property :begin link)
  17674. 'org-image-overlay)))
  17675. (if (and (car-safe old) refresh)
  17676. (image-refresh (overlay-get (cdr old) 'display))
  17677. (let ((image (create-image file
  17678. (and width 'imagemagick)
  17679. nil
  17680. :width width)))
  17681. (when image
  17682. (let ((ov (make-overlay
  17683. (org-element-property :begin link)
  17684. (progn
  17685. (goto-char
  17686. (org-element-property :end link))
  17687. (skip-chars-backward " \t")
  17688. (point)))))
  17689. (overlay-put ov 'display image)
  17690. (overlay-put ov 'face 'default)
  17691. (overlay-put ov 'org-image-overlay t)
  17692. (overlay-put
  17693. ov 'modification-hooks
  17694. (list 'org-display-inline-remove-overlay))
  17695. (push ov org-inline-image-overlays)))))))))))))))
  17696. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17697. "Remove inline-display overlay if a corresponding region is modified."
  17698. (let ((inhibit-modification-hooks t))
  17699. (when (and ov after)
  17700. (delete ov org-inline-image-overlays)
  17701. (delete-overlay ov))))
  17702. (defun org-remove-inline-images ()
  17703. "Remove inline display of images."
  17704. (interactive)
  17705. (mapc #'delete-overlay org-inline-image-overlays)
  17706. (setq org-inline-image-overlays nil))
  17707. ;;;; Key bindings
  17708. (defun org-remap (map &rest commands)
  17709. "In MAP, remap the functions given in COMMANDS.
  17710. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  17711. (let (new old)
  17712. (while commands
  17713. (setq old (pop commands) new (pop commands))
  17714. (org-defkey map (vector 'remap old) new))))
  17715. ;; Outline functions from `outline-mode-prefix-map'
  17716. ;; that can be remapped in Org:
  17717. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17718. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17719. (define-key org-mode-map [remap outline-forward-same-level]
  17720. 'org-forward-heading-same-level)
  17721. (define-key org-mode-map [remap outline-backward-same-level]
  17722. 'org-backward-heading-same-level)
  17723. (define-key org-mode-map [remap outline-show-branches]
  17724. 'org-kill-note-or-show-branches)
  17725. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17726. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17727. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17728. (define-key org-mode-map [remap outline-next-visible-heading]
  17729. 'org-next-visible-heading)
  17730. (define-key org-mode-map [remap outline-previous-visible-heading]
  17731. 'org-previous-visible-heading)
  17732. (define-key org-mode-map [remap show-children] 'org-show-children)
  17733. ;; Outline functions from `outline-mode-prefix-map' that can not
  17734. ;; be remapped in Org:
  17735. ;; - the column "key binding" shows whether the Outline function is still
  17736. ;; available in Org mode on the same key that it has been bound to in
  17737. ;; Outline mode:
  17738. ;; - "overridden": key used for a different functionality in Org mode
  17739. ;; - else: key still bound to the same Outline function in Org mode
  17740. ;; | Outline function | key binding | Org replacement |
  17741. ;; |------------------------------------+-------------+--------------------------|
  17742. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17743. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17744. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17745. ;; | `show-entry' | overridden | no replacement |
  17746. ;; | `show-branches' | `C-c C-k' | still same function |
  17747. ;; | `show-subtree' | overridden | visibility cycling |
  17748. ;; | `show-all' | overridden | no replacement |
  17749. ;; | `hide-subtree' | overridden | visibility cycling |
  17750. ;; | `hide-body' | overridden | no replacement |
  17751. ;; | `hide-entry' | overridden | visibility cycling |
  17752. ;; | `hide-leaves' | overridden | no replacement |
  17753. ;; | `hide-sublevels' | overridden | no replacement |
  17754. ;; | `hide-other' | overridden | no replacement |
  17755. ;; Make `C-c C-x' a prefix key
  17756. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17757. ;; TAB key with modifiers
  17758. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17759. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17760. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17761. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17762. ;; The following line is necessary under Suse GNU/Linux
  17763. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17764. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17765. (define-key org-mode-map [backtab] 'org-shifttab)
  17766. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17767. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17768. (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
  17769. ;; Cursor keys with modifiers
  17770. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17771. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17772. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17773. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17774. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17775. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17776. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17777. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17778. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17779. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17780. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17781. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17782. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17783. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17784. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17785. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17786. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17787. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17788. ;; Babel keys
  17789. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17790. (dolist (pair org-babel-key-bindings)
  17791. (define-key org-babel-map (car pair) (cdr pair)))
  17792. ;;; Extra keys for tty access.
  17793. ;; We only set them when really needed because otherwise the
  17794. ;; menus don't show the simple keys
  17795. (when (or org-use-extra-keys (not window-system))
  17796. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17797. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17798. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17799. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17800. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17801. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17802. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17803. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17804. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17805. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17806. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17807. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17808. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17809. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17810. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17811. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17812. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17813. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17814. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17815. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17816. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17817. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17818. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17819. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17820. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17821. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17822. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17823. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17824. ;; All the other keys
  17825. (org-remap org-mode-map
  17826. 'self-insert-command 'org-self-insert-command
  17827. 'delete-char 'org-delete-char
  17828. 'delete-backward-char 'org-delete-backward-char)
  17829. (org-defkey org-mode-map "|" 'org-force-self-insert)
  17830. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17831. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17832. (if (boundp 'narrow-map)
  17833. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17834. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17835. (if (boundp 'narrow-map)
  17836. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17837. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17838. (if (boundp 'narrow-map)
  17839. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17840. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17841. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17842. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17843. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17844. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17845. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17846. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17847. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17848. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17849. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17850. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17851. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17852. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17853. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17854. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17855. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17856. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17857. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17858. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17859. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17860. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17861. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17862. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17863. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17864. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17865. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17866. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17867. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17868. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17869. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17870. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17871. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17872. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17873. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17874. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17875. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17876. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17877. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17878. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17879. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17880. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17881. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17882. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17883. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17884. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17885. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17886. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17887. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17888. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17889. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17890. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17891. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17892. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17893. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17894. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17895. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17896. (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
  17897. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17898. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17899. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17900. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17901. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17902. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17903. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17904. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17905. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17906. (org-defkey org-mode-map "\C-m" 'org-return)
  17907. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17908. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17909. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17910. (org-defkey org-mode-map (kbd "C-c TAB") #'org-table-toggle-column-width)
  17911. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17912. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17913. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17914. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17915. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17916. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17917. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17918. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17919. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17920. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17921. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17922. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17923. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17924. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17925. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17926. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17927. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17928. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17929. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17930. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17931. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17932. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17933. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17934. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17935. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17936. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17937. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17938. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17939. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17940. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17941. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17942. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17943. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17944. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17945. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17946. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17947. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17948. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17949. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17950. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17951. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17952. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17953. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17954. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17955. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17956. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17957. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17958. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17959. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17960. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17961. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17962. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17963. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17964. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17965. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17966. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17967. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17968. (defconst org-speed-commands-default
  17969. '(
  17970. ("Outline Navigation")
  17971. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17972. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17973. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17974. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17975. ("F" . org-next-block)
  17976. ("B" . org-previous-block)
  17977. ("u" . (org-speed-move-safe 'outline-up-heading))
  17978. ("j" . org-goto)
  17979. ("g" . (org-refile t))
  17980. ("Outline Visibility")
  17981. ("c" . org-cycle)
  17982. ("C" . org-shifttab)
  17983. (" " . org-display-outline-path)
  17984. ("s" . org-narrow-to-subtree)
  17985. ("=" . org-columns)
  17986. ("Outline Structure Editing")
  17987. ("U" . org-metaup)
  17988. ("D" . org-metadown)
  17989. ("r" . org-metaright)
  17990. ("l" . org-metaleft)
  17991. ("R" . org-shiftmetaright)
  17992. ("L" . org-shiftmetaleft)
  17993. ("i" . (progn (forward-char 1) (call-interactively
  17994. 'org-insert-heading-respect-content)))
  17995. ("^" . org-sort)
  17996. ("w" . org-refile)
  17997. ("a" . org-archive-subtree-default-with-confirmation)
  17998. ("@" . org-mark-subtree)
  17999. ("#" . org-toggle-comment)
  18000. ("Clock Commands")
  18001. ("I" . org-clock-in)
  18002. ("O" . org-clock-out)
  18003. ("Meta Data Editing")
  18004. ("t" . org-todo)
  18005. ("," . (org-priority))
  18006. ("0" . (org-priority ?\ ))
  18007. ("1" . (org-priority ?A))
  18008. ("2" . (org-priority ?B))
  18009. ("3" . (org-priority ?C))
  18010. (":" . org-set-tags-command)
  18011. ("e" . org-set-effort)
  18012. ("E" . org-inc-effort)
  18013. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18014. (org-entry-put (point) "APPT_WARNTIME" m)))
  18015. ("Agenda Views etc")
  18016. ("v" . org-agenda)
  18017. ("/" . org-sparse-tree)
  18018. ("Misc")
  18019. ("o" . org-open-at-point)
  18020. ("?" . org-speed-command-help)
  18021. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18022. (">" . (org-agenda-remove-restriction-lock))
  18023. )
  18024. "The default speed commands.")
  18025. (defun org-print-speed-command (e)
  18026. (if (> (length (car e)) 1)
  18027. (progn
  18028. (princ "\n")
  18029. (princ (car e))
  18030. (princ "\n")
  18031. (princ (make-string (length (car e)) ?-))
  18032. (princ "\n"))
  18033. (princ (car e))
  18034. (princ " ")
  18035. (if (symbolp (cdr e))
  18036. (princ (symbol-name (cdr e)))
  18037. (prin1 (cdr e)))
  18038. (princ "\n")))
  18039. (defun org-speed-command-help ()
  18040. "Show the available speed commands."
  18041. (interactive)
  18042. (if (not org-use-speed-commands)
  18043. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18044. (with-output-to-temp-buffer "*Help*"
  18045. (princ "User-defined Speed commands\n===========================\n")
  18046. (mapc #'org-print-speed-command org-speed-commands-user)
  18047. (princ "\n")
  18048. (princ "Built-in Speed commands\n=======================\n")
  18049. (mapc #'org-print-speed-command org-speed-commands-default))
  18050. (with-current-buffer "*Help*"
  18051. (setq truncate-lines t))))
  18052. (defun org-speed-move-safe (cmd)
  18053. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18054. If not, return to the original position and throw an error."
  18055. (interactive)
  18056. (let ((pos (point)))
  18057. (call-interactively cmd)
  18058. (unless (and (bolp) (org-at-heading-p))
  18059. (goto-char pos)
  18060. (error "Boundary reached while executing %s" cmd))))
  18061. (defvar org-self-insert-command-undo-counter 0)
  18062. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18063. (defvar org-speed-command nil)
  18064. (defun org-speed-command-activate (keys)
  18065. "Hook for activating single-letter speed commands.
  18066. `org-speed-commands-default' specifies a minimal command set.
  18067. Use `org-speed-commands-user' for further customization."
  18068. (when (or (and (bolp) (looking-at org-outline-regexp))
  18069. (and (functionp org-use-speed-commands)
  18070. (funcall org-use-speed-commands)))
  18071. (cdr (assoc keys (append org-speed-commands-user
  18072. org-speed-commands-default)))))
  18073. (defun org-babel-speed-command-activate (keys)
  18074. "Hook for activating single-letter code block commands."
  18075. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18076. (cdr (assoc keys org-babel-key-bindings))))
  18077. (defcustom org-speed-command-hook
  18078. '(org-speed-command-activate org-babel-speed-command-activate)
  18079. "Hook for activating speed commands at strategic locations.
  18080. Hook functions are called in sequence until a valid handler is
  18081. found.
  18082. Each hook takes a single argument, a user-pressed command key
  18083. which is also a `self-insert-command' from the global map.
  18084. Within the hook, examine the cursor position and the command key
  18085. and return nil or a valid handler as appropriate. Handler could
  18086. be one of an interactive command, a function, or a form.
  18087. Set `org-use-speed-commands' to non-nil value to enable this
  18088. hook. The default setting is `org-speed-command-activate'."
  18089. :group 'org-structure
  18090. :version "24.1"
  18091. :type 'hook)
  18092. (defun org-self-insert-command (N)
  18093. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18094. If the cursor is in a table looking at whitespace, the whitespace is
  18095. overwritten, and the table is not marked as requiring realignment."
  18096. (interactive "p")
  18097. (org-check-before-invisible-edit 'insert)
  18098. (cond
  18099. ((and org-use-speed-commands
  18100. (let ((kv (this-command-keys-vector)))
  18101. (setq org-speed-command
  18102. (run-hook-with-args-until-success
  18103. 'org-speed-command-hook
  18104. (make-string 1 (aref kv (1- (length kv))))))))
  18105. (cond
  18106. ((commandp org-speed-command)
  18107. (setq this-command org-speed-command)
  18108. (call-interactively org-speed-command))
  18109. ((functionp org-speed-command)
  18110. (funcall org-speed-command))
  18111. ((and org-speed-command (listp org-speed-command))
  18112. (eval org-speed-command))
  18113. (t (let (org-use-speed-commands)
  18114. (call-interactively 'org-self-insert-command)))))
  18115. ((and
  18116. (org-at-table-p)
  18117. (eq N 1)
  18118. (not (org-region-active-p))
  18119. (progn
  18120. ;; Check if we blank the field, and if that triggers align.
  18121. (and (featurep 'org-table) org-table-auto-blank-field
  18122. (memq last-command
  18123. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18124. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18125. ;; Got extra space, this field does not determine
  18126. ;; column width.
  18127. (let (org-table-may-need-update) (org-table-blank-field))
  18128. ;; No extra space, this field may determine column
  18129. ;; width.
  18130. (org-table-blank-field)))
  18131. t)
  18132. (looking-at "[^|\n]* \\( \\)|"))
  18133. ;; There is room for insertion without re-aligning the table.
  18134. (delete-region (match-beginning 1) (match-end 1))
  18135. (self-insert-command N))
  18136. (t
  18137. (setq org-table-may-need-update t)
  18138. (self-insert-command N)
  18139. (org-fix-tags-on-the-fly)
  18140. (when org-self-insert-cluster-for-undo
  18141. (if (not (eq last-command 'org-self-insert-command))
  18142. (setq org-self-insert-command-undo-counter 1)
  18143. (if (>= org-self-insert-command-undo-counter 20)
  18144. (setq org-self-insert-command-undo-counter 1)
  18145. (and (> org-self-insert-command-undo-counter 0)
  18146. buffer-undo-list (listp buffer-undo-list)
  18147. (not (cadr buffer-undo-list)) ; remove nil entry
  18148. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18149. (setq org-self-insert-command-undo-counter
  18150. (1+ org-self-insert-command-undo-counter))))))))
  18151. (defun org-check-before-invisible-edit (kind)
  18152. "Check is editing if kind KIND would be dangerous with invisible text around.
  18153. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18154. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18155. (when (and org-catch-invisible-edits
  18156. (or (not (boundp 'visible-mode)) (not visible-mode))
  18157. (or (get-char-property (point) 'invisible)
  18158. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18159. ;; OK, we need to take a closer look. Do not consider
  18160. ;; invisibility obtained through text properties (e.g., link
  18161. ;; fontification), as it cannot be toggled.
  18162. (let* ((invisible-at-point
  18163. (pcase (get-char-property-and-overlay (point) 'invisible)
  18164. (`(,_ . ,(and (pred overlayp) o)) o)))
  18165. ;; Assume that point cannot land in the middle of an
  18166. ;; overlay, or between two overlays.
  18167. (invisible-before-point
  18168. (and (not invisible-at-point)
  18169. (not (bobp))
  18170. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18171. (`(,_ . ,(and (pred overlayp) o)) o))))
  18172. (border-and-ok-direction
  18173. (or
  18174. ;; Check if we are acting predictably before invisible
  18175. ;; text.
  18176. (and invisible-at-point
  18177. (memq kind '(insert delete-backward)))
  18178. ;; Check if we are acting predictably after invisible text
  18179. ;; This works not well, and I have turned it off. It seems
  18180. ;; better to always show and stop after invisible text.
  18181. ;; (and (not invisible-at-point) invisible-before-point
  18182. ;; (memq kind '(insert delete)))
  18183. )))
  18184. (when (or invisible-at-point invisible-before-point)
  18185. (when (eq org-catch-invisible-edits 'error)
  18186. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18187. (if (and org-custom-properties-overlays
  18188. (y-or-n-p "Display invisible properties in this buffer? "))
  18189. (org-toggle-custom-properties-visibility)
  18190. ;; Make the area visible
  18191. (save-excursion
  18192. (when invisible-before-point
  18193. (goto-char
  18194. (previous-single-char-property-change (point) 'invisible)))
  18195. ;; Remove whatever overlay is currently making yet-to-be
  18196. ;; edited text invisible. Also remove nested invisibility
  18197. ;; related overlays.
  18198. (delete-overlay (or invisible-at-point invisible-before-point))
  18199. (let ((origin (if invisible-at-point (point) (1- (point)))))
  18200. (while (pcase (get-char-property-and-overlay origin 'invisible)
  18201. (`(,_ . ,(and (pred overlayp) o))
  18202. (delete-overlay o)
  18203. t)))))
  18204. (cond
  18205. ((eq org-catch-invisible-edits 'show)
  18206. ;; That's it, we do the edit after showing
  18207. (message
  18208. "Unfolding invisible region around point before editing")
  18209. (sit-for 1))
  18210. ((and (eq org-catch-invisible-edits 'smart)
  18211. border-and-ok-direction)
  18212. (message "Unfolding invisible region around point before editing"))
  18213. (t
  18214. ;; Don't do the edit, make the user repeat it in full visibility
  18215. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18216. (defun org-fix-tags-on-the-fly ()
  18217. "Align tags in headline at point.
  18218. Unlike to `org-set-tags', it ignores region and sorting."
  18219. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18220. (org-at-heading-p))
  18221. (let ((org-ignore-region t)
  18222. (org-tags-sort-function nil))
  18223. (org-set-tags nil t))))
  18224. (defun org-delete-backward-char (N)
  18225. "Like `delete-backward-char', insert whitespace at field end in tables.
  18226. When deleting backwards, in tables this function will insert whitespace in
  18227. front of the next \"|\" separator, to keep the table aligned. The table will
  18228. still be marked for re-alignment if the field did fill the entire column,
  18229. because, in this case the deletion might narrow the column."
  18230. (interactive "p")
  18231. (save-match-data
  18232. (org-check-before-invisible-edit 'delete-backward)
  18233. (if (and (org-at-table-p)
  18234. (eq N 1)
  18235. (not (org-region-active-p))
  18236. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18237. (looking-at ".*?|"))
  18238. (let ((pos (point))
  18239. (noalign (looking-at "[^|\n\r]* |"))
  18240. (c org-table-may-need-update))
  18241. (backward-delete-char N)
  18242. (unless overwrite-mode
  18243. (skip-chars-forward "^|")
  18244. (insert " ")
  18245. (goto-char (1- pos)))
  18246. ;; noalign: if there were two spaces at the end, this field
  18247. ;; does not determine the width of the column.
  18248. (when noalign (setq org-table-may-need-update c)))
  18249. (backward-delete-char N)
  18250. (org-fix-tags-on-the-fly))))
  18251. (defun org-delete-char (N)
  18252. "Like `delete-char', but insert whitespace at field end in tables.
  18253. When deleting characters, in tables this function will insert whitespace in
  18254. front of the next \"|\" separator, to keep the table aligned. The table will
  18255. still be marked for re-alignment if the field did fill the entire column,
  18256. because, in this case the deletion might narrow the column."
  18257. (interactive "p")
  18258. (save-match-data
  18259. (org-check-before-invisible-edit 'delete)
  18260. (if (and (org-at-table-p)
  18261. (not (bolp))
  18262. (not (= (char-after) ?|))
  18263. (eq N 1))
  18264. (if (looking-at ".*?|")
  18265. (let ((pos (point))
  18266. (noalign (looking-at "[^|\n\r]* |"))
  18267. (c org-table-may-need-update))
  18268. (replace-match
  18269. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18270. (goto-char pos)
  18271. ;; noalign: if there were two spaces at the end, this field
  18272. ;; does not determine the width of the column.
  18273. (when noalign (setq org-table-may-need-update c)))
  18274. (delete-char N))
  18275. (delete-char N)
  18276. (org-fix-tags-on-the-fly))))
  18277. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18278. (put 'org-self-insert-command 'delete-selection
  18279. (lambda ()
  18280. (not (run-hook-with-args-until-success
  18281. 'self-insert-uses-region-functions))))
  18282. (put 'orgtbl-self-insert-command 'delete-selection
  18283. (lambda ()
  18284. (not (run-hook-with-args-until-success
  18285. 'self-insert-uses-region-functions))))
  18286. (put 'org-delete-char 'delete-selection 'supersede)
  18287. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18288. (put 'org-yank 'delete-selection 'yank)
  18289. ;; Make `flyspell-mode' delay after some commands
  18290. (put 'org-self-insert-command 'flyspell-delayed t)
  18291. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18292. (put 'org-delete-char 'flyspell-delayed t)
  18293. (put 'org-delete-backward-char 'flyspell-delayed t)
  18294. ;; Make pabbrev-mode expand after Org mode commands
  18295. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18296. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18297. (defun org-transpose-words ()
  18298. "Transpose words for Org.
  18299. This uses the `org-mode-transpose-word-syntax-table' syntax
  18300. table, which interprets characters in `org-emphasis-alist' as
  18301. word constituents."
  18302. (interactive)
  18303. (with-syntax-table org-mode-transpose-word-syntax-table
  18304. (call-interactively 'transpose-words)))
  18305. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18306. (defvar org-ctrl-c-ctrl-c-hook nil
  18307. "Hook for functions attaching themselves to `C-c C-c'.
  18308. This can be used to add additional functionality to the C-c C-c
  18309. key which executes context-dependent commands. This hook is run
  18310. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18311. run after the last test.
  18312. Each function will be called with no arguments. The function
  18313. must check if the context is appropriate for it to act. If yes,
  18314. it should do its thing and then return a non-nil value. If the
  18315. context is wrong, just do nothing and return nil.")
  18316. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18317. "Hook for functions attaching themselves to `C-c C-c'.
  18318. This can be used to add additional functionality to the C-c C-c
  18319. key which executes context-dependent commands. This hook is run
  18320. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18321. before the first test.
  18322. Each function will be called with no arguments. The function
  18323. must check if the context is appropriate for it to act. If yes,
  18324. it should do its thing and then return a non-nil value. If the
  18325. context is wrong, just do nothing and return nil.")
  18326. (defvar org-tab-first-hook nil
  18327. "Hook for functions to attach themselves to TAB.
  18328. See `org-ctrl-c-ctrl-c-hook' for more information.
  18329. This hook runs as the first action when TAB is pressed, even before
  18330. `org-cycle' messes around with the `outline-regexp' to cater for
  18331. inline tasks and plain list item folding.
  18332. If any function in this hook returns t, any other actions that
  18333. would have been caused by TAB (such as table field motion or visibility
  18334. cycling) will not occur.")
  18335. (defvar org-tab-after-check-for-table-hook nil
  18336. "Hook for functions to attach themselves to TAB.
  18337. See `org-ctrl-c-ctrl-c-hook' for more information.
  18338. This hook runs after it has been established that the cursor is not in a
  18339. table, but before checking if the cursor is in a headline or if global cycling
  18340. should be done.
  18341. If any function in this hook returns t, not other actions like visibility
  18342. cycling will be done.")
  18343. (defvar org-tab-after-check-for-cycling-hook nil
  18344. "Hook for functions to attach themselves to TAB.
  18345. See `org-ctrl-c-ctrl-c-hook' for more information.
  18346. This hook runs after it has been established that not table field motion and
  18347. not visibility should be done because of current context. This is probably
  18348. the place where a package like yasnippets can hook in.")
  18349. (defvar org-tab-before-tab-emulation-hook nil
  18350. "Hook for functions to attach themselves to TAB.
  18351. See `org-ctrl-c-ctrl-c-hook' for more information.
  18352. This hook runs after every other options for TAB have been exhausted, but
  18353. before indentation and \t insertion takes place.")
  18354. (defvar org-metaleft-hook nil
  18355. "Hook for functions attaching themselves to `M-left'.
  18356. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18357. (defvar org-metaright-hook nil
  18358. "Hook for functions attaching themselves to `M-right'.
  18359. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18360. (defvar org-metaup-hook nil
  18361. "Hook for functions attaching themselves to `M-up'.
  18362. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18363. (defvar org-metadown-hook nil
  18364. "Hook for functions attaching themselves to `M-down'.
  18365. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18366. (defvar org-shiftmetaleft-hook nil
  18367. "Hook for functions attaching themselves to `M-S-left'.
  18368. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18369. (defvar org-shiftmetaright-hook nil
  18370. "Hook for functions attaching themselves to `M-S-right'.
  18371. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18372. (defvar org-shiftmetaup-hook nil
  18373. "Hook for functions attaching themselves to `M-S-up'.
  18374. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18375. (defvar org-shiftmetadown-hook nil
  18376. "Hook for functions attaching themselves to `M-S-down'.
  18377. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18378. (defvar org-metareturn-hook nil
  18379. "Hook for functions attaching themselves to `M-RET'.
  18380. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18381. (defvar org-shiftup-hook nil
  18382. "Hook for functions attaching themselves to `S-up'.
  18383. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18384. (defvar org-shiftup-final-hook nil
  18385. "Hook for functions attaching themselves to `S-up'.
  18386. This one runs after all other options except shift-select have been excluded.
  18387. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18388. (defvar org-shiftdown-hook nil
  18389. "Hook for functions attaching themselves to `S-down'.
  18390. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18391. (defvar org-shiftdown-final-hook nil
  18392. "Hook for functions attaching themselves to `S-down'.
  18393. This one runs after all other options except shift-select have been excluded.
  18394. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18395. (defvar org-shiftleft-hook nil
  18396. "Hook for functions attaching themselves to `S-left'.
  18397. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18398. (defvar org-shiftleft-final-hook nil
  18399. "Hook for functions attaching themselves to `S-left'.
  18400. This one runs after all other options except shift-select have been excluded.
  18401. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18402. (defvar org-shiftright-hook nil
  18403. "Hook for functions attaching themselves to `S-right'.
  18404. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18405. (defvar org-shiftright-final-hook nil
  18406. "Hook for functions attaching themselves to `S-right'.
  18407. This one runs after all other options except shift-select have been excluded.
  18408. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18409. (defun org-modifier-cursor-error ()
  18410. "Throw an error, a modified cursor command was applied in wrong context."
  18411. (user-error "This command is active in special context like tables, headlines or items"))
  18412. (defun org-shiftselect-error ()
  18413. "Throw an error because Shift-Cursor command was applied in wrong context."
  18414. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18415. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18416. (user-error "This command works only in special context like headlines or timestamps")))
  18417. (defun org-call-for-shift-select (cmd)
  18418. (let ((this-command-keys-shift-translated t))
  18419. (call-interactively cmd)))
  18420. (defun org-shifttab (&optional arg)
  18421. "Global visibility cycling or move to previous table field.
  18422. Call `org-table-previous-field' within a table.
  18423. When ARG is nil, cycle globally through visibility states.
  18424. When ARG is a numeric prefix, show contents of this level."
  18425. (interactive "P")
  18426. (cond
  18427. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18428. ((integerp arg)
  18429. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18430. (message "Content view to level: %d" arg)
  18431. (org-content (prefix-numeric-value arg2))
  18432. (org-cycle-show-empty-lines t)
  18433. (setq org-cycle-global-status 'overview)))
  18434. (t (call-interactively 'org-global-cycle))))
  18435. (defun org-shiftmetaleft ()
  18436. "Promote subtree or delete table column.
  18437. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18438. `org-table-delete-column', depending on context. See the
  18439. individual commands for more information."
  18440. (interactive)
  18441. (cond
  18442. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18443. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18444. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18445. ((if (not (org-region-active-p)) (org-at-item-p)
  18446. (save-excursion (goto-char (region-beginning))
  18447. (org-at-item-p)))
  18448. (call-interactively 'org-outdent-item-tree))
  18449. (t (org-modifier-cursor-error))))
  18450. (defun org-shiftmetaright ()
  18451. "Demote subtree or insert table column.
  18452. Calls `org-demote-subtree', `org-indent-item-tree', or
  18453. `org-table-insert-column', depending on context. See the
  18454. individual commands for more information."
  18455. (interactive)
  18456. (cond
  18457. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18458. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18459. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18460. ((if (not (org-region-active-p)) (org-at-item-p)
  18461. (save-excursion (goto-char (region-beginning))
  18462. (org-at-item-p)))
  18463. (call-interactively 'org-indent-item-tree))
  18464. (t (org-modifier-cursor-error))))
  18465. (defun org-shiftmetaup (&optional _arg)
  18466. "Drag the line at point up.
  18467. In a table, kill the current row.
  18468. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18469. but also adjust the previous clocked item in the clock history.
  18470. Everywhere else, drag the line at point up."
  18471. (interactive "P")
  18472. (cond
  18473. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18474. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18475. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18476. (call-interactively 'org-timestamp-up)))
  18477. (t (call-interactively 'org-drag-line-backward))))
  18478. (defun org-shiftmetadown (&optional _arg)
  18479. "Drag the line at point down.
  18480. In a table, insert an empty row at the current line.
  18481. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18482. but also adjust the previous clocked item in the clock history.
  18483. Everywhere else, drag the line at point down."
  18484. (interactive "P")
  18485. (cond
  18486. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18487. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18488. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18489. (call-interactively 'org-timestamp-down)))
  18490. (t (call-interactively 'org-drag-line-forward))))
  18491. (defsubst org-hidden-tree-error ()
  18492. (user-error
  18493. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18494. (defun org-metaleft (&optional _arg)
  18495. "Promote heading, list item at point or move table column left.
  18496. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18497. depending on context. With no specific context, calls the Emacs
  18498. default `backward-word'. See the individual commands for more
  18499. information.
  18500. This function runs the hook `org-metaleft-hook' as a first step,
  18501. and returns at first non-nil value."
  18502. (interactive "P")
  18503. (cond
  18504. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18505. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18506. ((org-with-limited-levels
  18507. (or (org-at-heading-p)
  18508. (and (org-region-active-p)
  18509. (save-excursion
  18510. (goto-char (region-beginning))
  18511. (org-at-heading-p)))))
  18512. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18513. (call-interactively 'org-do-promote))
  18514. ;; At an inline task.
  18515. ((org-at-heading-p)
  18516. (call-interactively 'org-inlinetask-promote))
  18517. ((or (org-at-item-p)
  18518. (and (org-region-active-p)
  18519. (save-excursion
  18520. (goto-char (region-beginning))
  18521. (org-at-item-p))))
  18522. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18523. (call-interactively 'org-outdent-item))
  18524. (t (call-interactively 'backward-word))))
  18525. (defun org-metaright (&optional _arg)
  18526. "Demote heading, list item at point or move table column right.
  18527. In front of a drawer or a block keyword, indent it correctly.
  18528. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18529. `org-indent-drawer' or `org-indent-block' depending on context.
  18530. With no specific context, calls the Emacs default `forward-word'.
  18531. See the individual commands for more information.
  18532. This function runs the hook `org-metaright-hook' as a first step,
  18533. and returns at first non-nil value."
  18534. (interactive "P")
  18535. (cond
  18536. ((run-hook-with-args-until-success 'org-metaright-hook))
  18537. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18538. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18539. ((org-at-block-p) (call-interactively 'org-indent-block))
  18540. ((org-with-limited-levels
  18541. (or (org-at-heading-p)
  18542. (and (org-region-active-p)
  18543. (save-excursion
  18544. (goto-char (region-beginning))
  18545. (org-at-heading-p)))))
  18546. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18547. (call-interactively 'org-do-demote))
  18548. ;; At an inline task.
  18549. ((org-at-heading-p)
  18550. (call-interactively 'org-inlinetask-demote))
  18551. ((or (org-at-item-p)
  18552. (and (org-region-active-p)
  18553. (save-excursion
  18554. (goto-char (region-beginning))
  18555. (org-at-item-p))))
  18556. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18557. (call-interactively 'org-indent-item))
  18558. (t (call-interactively 'forward-word))))
  18559. (defun org-check-for-hidden (what)
  18560. "Check if there are hidden headlines/items in the current visual line.
  18561. WHAT can be either `headlines' or `items'. If the current line is
  18562. an outline or item heading and it has a folded subtree below it,
  18563. this function returns t, nil otherwise."
  18564. (let ((re (cond
  18565. ((eq what 'headlines) org-outline-regexp-bol)
  18566. ((eq what 'items) (org-item-beginning-re))
  18567. (t (error "This should not happen"))))
  18568. beg end)
  18569. (save-excursion
  18570. (catch 'exit
  18571. (unless (org-region-active-p)
  18572. (setq beg (point-at-bol))
  18573. (beginning-of-line 2)
  18574. (while (and (not (eobp)) ;; this is like `next-line'
  18575. (get-char-property (1- (point)) 'invisible))
  18576. (beginning-of-line 2))
  18577. (setq end (point))
  18578. (goto-char beg)
  18579. (goto-char (point-at-eol))
  18580. (setq end (max end (point)))
  18581. (while (re-search-forward re end t)
  18582. (when (get-char-property (match-beginning 0) 'invisible)
  18583. (throw 'exit t))))
  18584. nil))))
  18585. (defun org-metaup (&optional _arg)
  18586. "Move subtree up or move table row up.
  18587. Calls `org-move-subtree-up' or `org-table-move-row' or
  18588. `org-move-item-up', depending on context. See the individual commands
  18589. for more information."
  18590. (interactive "P")
  18591. (cond
  18592. ((run-hook-with-args-until-success 'org-metaup-hook))
  18593. ((org-region-active-p)
  18594. (let* ((a (min (region-beginning) (region-end)))
  18595. (b (1- (max (region-beginning) (region-end))))
  18596. (c (save-excursion (goto-char a)
  18597. (move-beginning-of-line 0)))
  18598. (d (save-excursion (goto-char a)
  18599. (move-end-of-line 0) (point))))
  18600. (transpose-regions a b c d)
  18601. (goto-char c)))
  18602. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18603. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18604. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18605. (t (org-drag-element-backward))))
  18606. (defun org-metadown (&optional _arg)
  18607. "Move subtree down or move table row down.
  18608. Calls `org-move-subtree-down' or `org-table-move-row' or
  18609. `org-move-item-down', depending on context. See the individual
  18610. commands for more information."
  18611. (interactive "P")
  18612. (cond
  18613. ((run-hook-with-args-until-success 'org-metadown-hook))
  18614. ((org-region-active-p)
  18615. (let* ((a (min (region-beginning) (region-end)))
  18616. (b (max (region-beginning) (region-end)))
  18617. (c (save-excursion (goto-char b)
  18618. (move-beginning-of-line 1)))
  18619. (d (save-excursion (goto-char b)
  18620. (move-end-of-line 1) (1+ (point)))))
  18621. (transpose-regions a b c d)
  18622. (goto-char d)))
  18623. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18624. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18625. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18626. (t (org-drag-element-forward))))
  18627. (defun org-shiftup (&optional arg)
  18628. "Increase item in timestamp or increase priority of current headline.
  18629. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18630. depending on context. See the individual commands for more information."
  18631. (interactive "P")
  18632. (cond
  18633. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18634. ((and org-support-shift-select (org-region-active-p))
  18635. (org-call-for-shift-select 'previous-line))
  18636. ((org-at-timestamp-p 'lax)
  18637. (call-interactively (if org-edit-timestamp-down-means-later
  18638. 'org-timestamp-down 'org-timestamp-up)))
  18639. ((and (not (eq org-support-shift-select 'always))
  18640. org-enable-priority-commands
  18641. (org-at-heading-p))
  18642. (call-interactively 'org-priority-up))
  18643. ((and (not org-support-shift-select) (org-at-item-p))
  18644. (call-interactively 'org-previous-item))
  18645. ((org-clocktable-try-shift 'up arg))
  18646. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18647. (org-support-shift-select
  18648. (org-call-for-shift-select 'previous-line))
  18649. (t (org-shiftselect-error))))
  18650. (defun org-shiftdown (&optional arg)
  18651. "Decrease item in timestamp or decrease priority of current headline.
  18652. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18653. depending on context. See the individual commands for more information."
  18654. (interactive "P")
  18655. (cond
  18656. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18657. ((and org-support-shift-select (org-region-active-p))
  18658. (org-call-for-shift-select 'next-line))
  18659. ((org-at-timestamp-p 'lax)
  18660. (call-interactively (if org-edit-timestamp-down-means-later
  18661. 'org-timestamp-up 'org-timestamp-down)))
  18662. ((and (not (eq org-support-shift-select 'always))
  18663. org-enable-priority-commands
  18664. (org-at-heading-p))
  18665. (call-interactively 'org-priority-down))
  18666. ((and (not org-support-shift-select) (org-at-item-p))
  18667. (call-interactively 'org-next-item))
  18668. ((org-clocktable-try-shift 'down arg))
  18669. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18670. (org-support-shift-select
  18671. (org-call-for-shift-select 'next-line))
  18672. (t (org-shiftselect-error))))
  18673. (defun org-shiftright (&optional arg)
  18674. "Cycle the thing at point or in the current line, depending on context.
  18675. Depending on context, this does one of the following:
  18676. - switch a timestamp at point one day into the future
  18677. - on a headline, switch to the next TODO keyword.
  18678. - on an item, switch entire list to the next bullet type
  18679. - on a property line, switch to the next allowed value
  18680. - on a clocktable definition line, move time block into the future"
  18681. (interactive "P")
  18682. (cond
  18683. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18684. ((and org-support-shift-select (org-region-active-p))
  18685. (org-call-for-shift-select 'forward-char))
  18686. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18687. ((and (not (eq org-support-shift-select 'always))
  18688. (org-at-heading-p))
  18689. (let ((org-inhibit-logging
  18690. (not org-treat-S-cursor-todo-selection-as-state-change))
  18691. (org-inhibit-blocking
  18692. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18693. (org-call-with-arg 'org-todo 'right)))
  18694. ((or (and org-support-shift-select
  18695. (not (eq org-support-shift-select 'always))
  18696. (org-at-item-bullet-p))
  18697. (and (not org-support-shift-select) (org-at-item-p)))
  18698. (org-call-with-arg 'org-cycle-list-bullet nil))
  18699. ((and (not (eq org-support-shift-select 'always))
  18700. (org-at-property-p))
  18701. (call-interactively 'org-property-next-allowed-value))
  18702. ((org-clocktable-try-shift 'right arg))
  18703. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18704. (org-support-shift-select
  18705. (org-call-for-shift-select 'forward-char))
  18706. (t (org-shiftselect-error))))
  18707. (defun org-shiftleft (&optional arg)
  18708. "Cycle the thing at point or in the current line, depending on context.
  18709. Depending on context, this does one of the following:
  18710. - switch a timestamp at point one day into the past
  18711. - on a headline, switch to the previous TODO keyword.
  18712. - on an item, switch entire list to the previous bullet type
  18713. - on a property line, switch to the previous allowed value
  18714. - on a clocktable definition line, move time block into the past"
  18715. (interactive "P")
  18716. (cond
  18717. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18718. ((and org-support-shift-select (org-region-active-p))
  18719. (org-call-for-shift-select 'backward-char))
  18720. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18721. ((and (not (eq org-support-shift-select 'always))
  18722. (org-at-heading-p))
  18723. (let ((org-inhibit-logging
  18724. (not org-treat-S-cursor-todo-selection-as-state-change))
  18725. (org-inhibit-blocking
  18726. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18727. (org-call-with-arg 'org-todo 'left)))
  18728. ((or (and org-support-shift-select
  18729. (not (eq org-support-shift-select 'always))
  18730. (org-at-item-bullet-p))
  18731. (and (not org-support-shift-select) (org-at-item-p)))
  18732. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18733. ((and (not (eq org-support-shift-select 'always))
  18734. (org-at-property-p))
  18735. (call-interactively 'org-property-previous-allowed-value))
  18736. ((org-clocktable-try-shift 'left arg))
  18737. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18738. (org-support-shift-select
  18739. (org-call-for-shift-select 'backward-char))
  18740. (t (org-shiftselect-error))))
  18741. (defun org-shiftcontrolright ()
  18742. "Switch to next TODO set."
  18743. (interactive)
  18744. (cond
  18745. ((and org-support-shift-select (org-region-active-p))
  18746. (org-call-for-shift-select 'forward-word))
  18747. ((and (not (eq org-support-shift-select 'always))
  18748. (org-at-heading-p))
  18749. (org-call-with-arg 'org-todo 'nextset))
  18750. (org-support-shift-select
  18751. (org-call-for-shift-select 'forward-word))
  18752. (t (org-shiftselect-error))))
  18753. (defun org-shiftcontrolleft ()
  18754. "Switch to previous TODO set."
  18755. (interactive)
  18756. (cond
  18757. ((and org-support-shift-select (org-region-active-p))
  18758. (org-call-for-shift-select 'backward-word))
  18759. ((and (not (eq org-support-shift-select 'always))
  18760. (org-at-heading-p))
  18761. (org-call-with-arg 'org-todo 'previousset))
  18762. (org-support-shift-select
  18763. (org-call-for-shift-select 'backward-word))
  18764. (t (org-shiftselect-error))))
  18765. (defun org-shiftcontrolup (&optional n)
  18766. "Change timestamps synchronously up in CLOCK log lines.
  18767. Optional argument N tells to change by that many units."
  18768. (interactive "P")
  18769. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18770. (let (org-support-shift-select)
  18771. (org-clock-timestamps-up n))
  18772. (user-error "Not at a clock log")))
  18773. (defun org-shiftcontroldown (&optional n)
  18774. "Change timestamps synchronously down in CLOCK log lines.
  18775. Optional argument N tells to change by that many units."
  18776. (interactive "P")
  18777. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18778. (let (org-support-shift-select)
  18779. (org-clock-timestamps-down n))
  18780. (user-error "Not at a clock log")))
  18781. (defun org-increase-number-at-point (&optional inc)
  18782. "Increment the number at point.
  18783. With an optional prefix numeric argument INC, increment using
  18784. this numeric value."
  18785. (interactive "p")
  18786. (if (not (number-at-point))
  18787. (user-error "Not on a number")
  18788. (unless inc (setq inc 1))
  18789. (let ((pos (point))
  18790. (beg (skip-chars-backward "-+^/*0-9eE."))
  18791. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18792. (setq nap (buffer-substring-no-properties
  18793. (+ pos beg) (+ pos beg end)))
  18794. (delete-region (+ pos beg) (+ pos beg end))
  18795. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18796. (when (org-at-table-p)
  18797. (org-table-align)
  18798. (org-table-end-of-field 1))))
  18799. (defun org-decrease-number-at-point (&optional inc)
  18800. "Decrement the number at point.
  18801. With an optional prefix numeric argument INC, decrement using
  18802. this numeric value."
  18803. (interactive "p")
  18804. (org-increase-number-at-point (- (or inc 1))))
  18805. (defun org-ctrl-c-ret ()
  18806. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18807. (interactive)
  18808. (cond
  18809. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18810. (t (call-interactively 'org-insert-heading))))
  18811. (defun org-find-visible ()
  18812. (let ((s (point)))
  18813. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18814. (get-char-property s 'invisible)))
  18815. s))
  18816. (defun org-find-invisible ()
  18817. (let ((s (point)))
  18818. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18819. (not (get-char-property s 'invisible))))
  18820. s))
  18821. (defun org-copy-visible (beg end)
  18822. "Copy the visible parts of the region."
  18823. (interactive "r")
  18824. (let ((result ""))
  18825. (while (/= beg end)
  18826. (when (get-char-property beg 'invisible)
  18827. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  18828. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  18829. (setq result (concat result (buffer-substring beg next)))
  18830. (setq beg next)))
  18831. (kill-new result)))
  18832. (defun org-copy-special ()
  18833. "Copy region in table or copy current subtree.
  18834. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18835. context. See the individual commands for more information."
  18836. (interactive)
  18837. (call-interactively
  18838. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18839. (defun org-cut-special ()
  18840. "Cut region in table or cut current subtree.
  18841. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18842. context. See the individual commands for more information."
  18843. (interactive)
  18844. (call-interactively
  18845. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18846. (defun org-paste-special (arg)
  18847. "Paste rectangular region into table, or past subtree relative to level.
  18848. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18849. See the individual commands for more information."
  18850. (interactive "P")
  18851. (if (org-at-table-p)
  18852. (org-table-paste-rectangle)
  18853. (org-paste-subtree arg)))
  18854. (defun org-edit-special (&optional arg)
  18855. "Call a special editor for the element at point.
  18856. When at a table, call the formula editor with `org-table-edit-formulas'.
  18857. When in a source code block, call `org-edit-src-code'.
  18858. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18859. When in an export block, call `org-edit-export-block'.
  18860. When in a LaTeX environment, call `org-edit-latex-environment'.
  18861. When at an #+INCLUDE keyword, visit the included file.
  18862. When at a footnote reference, call `org-edit-footnote-reference'
  18863. On a link, call `ffap' to visit the link at point.
  18864. Otherwise, return a user error."
  18865. (interactive "P")
  18866. (let ((element (org-element-at-point)))
  18867. (barf-if-buffer-read-only)
  18868. (pcase (org-element-type element)
  18869. (`src-block
  18870. (if (not arg) (org-edit-src-code)
  18871. (let* ((info (org-babel-get-src-block-info))
  18872. (lang (nth 0 info))
  18873. (params (nth 2 info))
  18874. (session (cdr (assq :session params))))
  18875. (if (not session) (org-edit-src-code)
  18876. ;; At a src-block with a session and function called with
  18877. ;; an ARG: switch to the buffer related to the inferior
  18878. ;; process.
  18879. (switch-to-buffer
  18880. (funcall (intern (concat "org-babel-prep-session:" lang))
  18881. session params))))))
  18882. (`keyword
  18883. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18884. (org-open-link-from-string
  18885. (format "[[%s]]"
  18886. (expand-file-name
  18887. (let ((value (org-element-property :value element)))
  18888. (cond ((org-file-url-p value)
  18889. (user-error "The file is specified as a URL, cannot be edited"))
  18890. ((not (org-string-nw-p value))
  18891. (user-error "No file to edit"))
  18892. ((string-match "\\`\"\\(.*?\\)\"" value)
  18893. (match-string 1 value))
  18894. ((string-match "\\`[^ \t\"]\\S-*" value)
  18895. (match-string 0 value))
  18896. (t (user-error "No valid file specified")))))))
  18897. (user-error "No special environment to edit here")))
  18898. (`table
  18899. (if (eq (org-element-property :type element) 'table.el)
  18900. (org-edit-table.el)
  18901. (call-interactively 'org-table-edit-formulas)))
  18902. ;; Only Org tables contain `table-row' type elements.
  18903. (`table-row (call-interactively 'org-table-edit-formulas))
  18904. (`example-block (org-edit-src-code))
  18905. (`export-block (org-edit-export-block))
  18906. (`fixed-width (org-edit-fixed-width-region))
  18907. (`latex-environment (org-edit-latex-environment))
  18908. (_
  18909. ;; No notable element at point. Though, we may be at a link or
  18910. ;; a footnote reference, which are objects. Thus, scan deeper.
  18911. (let ((context (org-element-context element)))
  18912. (pcase (org-element-type context)
  18913. (`footnote-reference (org-edit-footnote-reference))
  18914. (`inline-src-block (org-edit-inline-src-code))
  18915. (`link (call-interactively #'ffap))
  18916. (_ (user-error "No special environment to edit here"))))))))
  18917. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18918. (defun org-ctrl-c-ctrl-c (&optional arg)
  18919. "Set tags in headline, or update according to changed information at point.
  18920. This command does many different things, depending on context:
  18921. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18922. this is what we do.
  18923. - If the cursor is on a statistics cookie, update it.
  18924. - If the cursor is in a headline, prompt for tags and insert them
  18925. into the current line, aligned to `org-tags-column'. When called
  18926. with prefix arg, realign all tags in the current buffer.
  18927. - If the cursor is in one of the special #+KEYWORD lines, this
  18928. triggers scanning the buffer for these lines and updating the
  18929. information.
  18930. - If the cursor is inside a table, realign the table. This command
  18931. works even if the automatic table editor has been turned off.
  18932. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18933. the entire table.
  18934. - If the cursor is at a footnote reference or definition, jump to
  18935. the corresponding definition or references, respectively.
  18936. - If the cursor is a the beginning of a dynamic block, update it.
  18937. - If the current buffer is a capture buffer, close note and file it.
  18938. - If the cursor is on a <<<target>>>, update radio targets and
  18939. corresponding links in this buffer.
  18940. - If the cursor is on a numbered item in a plain list, renumber the
  18941. ordered list.
  18942. - If the cursor is on a checkbox, toggle it.
  18943. - If the cursor is on a code block, evaluate it. The variable
  18944. `org-confirm-babel-evaluate' can be used to control prompting
  18945. before code block evaluation, by default every code block
  18946. evaluation requires confirmation. Code block evaluation can be
  18947. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18948. (interactive "P")
  18949. (cond
  18950. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18951. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18952. (org-remove-occur-highlights)
  18953. (message "Temporary highlights/overlays removed from current buffer"))
  18954. ((and (local-variable-p 'org-finish-function)
  18955. (fboundp org-finish-function))
  18956. (funcall org-finish-function))
  18957. ((org-babel-hash-at-point))
  18958. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18959. (t
  18960. (let* ((context
  18961. (org-element-lineage
  18962. (org-element-context)
  18963. ;; Limit to supported contexts.
  18964. '(babel-call clock dynamic-block footnote-definition
  18965. footnote-reference inline-babel-call inline-src-block
  18966. inlinetask item keyword node-property paragraph
  18967. plain-list property-drawer radio-target src-block
  18968. statistics-cookie table table-cell table-row
  18969. timestamp)
  18970. t))
  18971. (type (org-element-type context)))
  18972. ;; For convenience: at the first line of a paragraph on the same
  18973. ;; line as an item, apply function on that item instead.
  18974. (when (eq type 'paragraph)
  18975. (let ((parent (org-element-property :parent context)))
  18976. (when (and (eq (org-element-type parent) 'item)
  18977. (= (line-beginning-position)
  18978. (org-element-property :begin parent)))
  18979. (setq context parent)
  18980. (setq type 'item))))
  18981. ;; Act according to type of element or object at point.
  18982. ;;
  18983. ;; Do nothing on a blank line, except if it is contained in
  18984. ;; a src block. Hence, we first check if point is in such
  18985. ;; a block and then if it is at a blank line.
  18986. (pcase type
  18987. ((or `inline-src-block `src-block)
  18988. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  18989. (org-babel-eval-wipe-error-buffer)
  18990. (org-babel-execute-src-block
  18991. current-prefix-arg (org-babel-get-src-block-info nil context))))
  18992. ((guard (org-match-line "[ \t]*$"))
  18993. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  18994. (user-error
  18995. (substitute-command-keys
  18996. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  18997. ((or `babel-call `inline-babel-call)
  18998. (let ((info (org-babel-lob-get-info context)))
  18999. (when info (org-babel-execute-src-block nil info))))
  19000. (`clock (org-clock-update-time-maybe))
  19001. (`dynamic-block
  19002. (save-excursion
  19003. (goto-char (org-element-property :post-affiliated context))
  19004. (org-update-dblock)))
  19005. (`footnote-definition
  19006. (goto-char (org-element-property :post-affiliated context))
  19007. (call-interactively 'org-footnote-action))
  19008. (`footnote-reference (call-interactively #'org-footnote-action))
  19009. ((or `headline `inlinetask)
  19010. (save-excursion (goto-char (org-element-property :begin context))
  19011. (call-interactively #'org-set-tags)))
  19012. (`item
  19013. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19014. ;; unconditionally, whereas `C-u' will toggle its presence.
  19015. ;; Without a universal argument, if the item has a checkbox,
  19016. ;; toggle it. Otherwise repair the list.
  19017. (let* ((box (org-element-property :checkbox context))
  19018. (struct (org-element-property :structure context))
  19019. (old-struct (copy-tree struct))
  19020. (parents (org-list-parents-alist struct))
  19021. (prevs (org-list-prevs-alist struct))
  19022. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19023. (org-list-set-checkbox
  19024. (org-element-property :begin context) struct
  19025. (cond ((equal arg '(16)) "[-]")
  19026. ((and (not box) (equal arg '(4))) "[ ]")
  19027. ((or (not box) (equal arg '(4))) nil)
  19028. ((eq box 'on) "[ ]")
  19029. (t "[X]")))
  19030. ;; Mimic `org-list-write-struct' but with grabbing a return
  19031. ;; value from `org-list-struct-fix-box'.
  19032. (org-list-struct-fix-ind struct parents 2)
  19033. (org-list-struct-fix-item-end struct)
  19034. (org-list-struct-fix-bul struct prevs)
  19035. (org-list-struct-fix-ind struct parents)
  19036. (let ((block-item
  19037. (org-list-struct-fix-box struct parents prevs orderedp)))
  19038. (if (and box (equal struct old-struct))
  19039. (if (equal arg '(16))
  19040. (message "Checkboxes already reset")
  19041. (user-error "Cannot toggle this checkbox: %s"
  19042. (if (eq box 'on)
  19043. "all subitems checked"
  19044. "unchecked subitems")))
  19045. (org-list-struct-apply-struct struct old-struct)
  19046. (org-update-checkbox-count-maybe))
  19047. (when block-item
  19048. (message "Checkboxes were removed due to empty box at line %d"
  19049. (org-current-line block-item))))))
  19050. (`keyword
  19051. (let ((org-inhibit-startup-visibility-stuff t)
  19052. (org-startup-align-all-tables nil))
  19053. (when (boundp 'org-table-coordinate-overlays)
  19054. (mapc #'delete-overlay org-table-coordinate-overlays)
  19055. (setq org-table-coordinate-overlays nil))
  19056. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19057. (message "Local setup has been refreshed"))
  19058. (`plain-list
  19059. ;; At a plain list, with a double C-u argument, set
  19060. ;; checkboxes of each item to "[-]", whereas a single one
  19061. ;; will toggle their presence according to the state of the
  19062. ;; first item in the list. Without an argument, repair the
  19063. ;; list.
  19064. (let* ((begin (org-element-property :contents-begin context))
  19065. (beginm (move-marker (make-marker) begin))
  19066. (struct (org-element-property :structure context))
  19067. (old-struct (copy-tree struct))
  19068. (first-box (save-excursion
  19069. (goto-char begin)
  19070. (looking-at org-list-full-item-re)
  19071. (match-string-no-properties 3)))
  19072. (new-box (cond ((equal arg '(16)) "[-]")
  19073. ((equal arg '(4)) (unless first-box "[ ]"))
  19074. ((equal first-box "[X]") "[ ]")
  19075. (t "[X]"))))
  19076. (cond
  19077. (arg
  19078. (dolist (pos
  19079. (org-list-get-all-items
  19080. begin struct (org-list-prevs-alist struct)))
  19081. (org-list-set-checkbox pos struct new-box)))
  19082. ((and first-box (eq (point) begin))
  19083. ;; For convenience, when point is at bol on the first
  19084. ;; item of the list and no argument is provided, simply
  19085. ;; toggle checkbox of that item, if any.
  19086. (org-list-set-checkbox begin struct new-box)))
  19087. (org-list-write-struct
  19088. struct (org-list-parents-alist struct) old-struct)
  19089. (org-update-checkbox-count-maybe)
  19090. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19091. ((or `property-drawer `node-property)
  19092. (call-interactively #'org-property-action))
  19093. (`radio-target
  19094. (call-interactively #'org-update-radio-target-regexp))
  19095. (`statistics-cookie
  19096. (call-interactively #'org-update-statistics-cookies))
  19097. ((or `table `table-cell `table-row)
  19098. ;; At a table, recalculate every field and align it. Also
  19099. ;; send the table if necessary. If the table has
  19100. ;; a `table.el' type, just give up. At a table row or cell,
  19101. ;; maybe recalculate line but always align table.
  19102. (if (eq (org-element-property :type context) 'table.el)
  19103. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19104. Use `\\[org-edit-special]' to edit table.el tables"))
  19105. (if (or (eq type 'table)
  19106. ;; Check if point is at a TBLFM line.
  19107. (and (eq type 'table-row)
  19108. (= (point) (org-element-property :end context))))
  19109. (save-excursion
  19110. (if (org-at-TBLFM-p)
  19111. (progn (require 'org-table)
  19112. (org-table-calc-current-TBLFM))
  19113. (goto-char (org-element-property :contents-begin context))
  19114. (org-call-with-arg 'org-table-recalculate (or arg t))
  19115. (orgtbl-send-table 'maybe)))
  19116. (org-table-maybe-eval-formula)
  19117. (cond (arg (call-interactively #'org-table-recalculate))
  19118. ((org-table-maybe-recalculate-line))
  19119. (t (org-table-align))))))
  19120. (`timestamp (org-timestamp-change 0 'day))
  19121. ((and `nil (guard (org-at-heading-p)))
  19122. ;; When point is on an unsupported object type, we can miss
  19123. ;; the fact that it also is at a heading. Handle it here.
  19124. (call-interactively #'org-set-tags))
  19125. ((guard
  19126. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19127. (_
  19128. (user-error
  19129. (substitute-command-keys
  19130. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19131. (defun org-mode-restart ()
  19132. (interactive)
  19133. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19134. (funcall major-mode)
  19135. (hack-local-variables)
  19136. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19137. (org-indent-mode -1))
  19138. (org-reset-file-cache))
  19139. (message "%s restarted" major-mode))
  19140. (defun org-kill-note-or-show-branches ()
  19141. "Abort storing current note, or call `outline-show-branches'."
  19142. (interactive)
  19143. (if (not org-finish-function)
  19144. (progn
  19145. (outline-hide-subtree)
  19146. (call-interactively 'outline-show-branches))
  19147. (let ((org-note-abort t))
  19148. (funcall org-finish-function))))
  19149. (defun org-delete-indentation (&optional arg)
  19150. "Join current line to previous and fix whitespace at join.
  19151. If previous line is a headline add to headline title. Otherwise
  19152. the function calls `delete-indentation'.
  19153. With a non-nil optional argument, join it to the following one."
  19154. (interactive "*P")
  19155. (if (save-excursion
  19156. (beginning-of-line (if arg 1 0))
  19157. (let ((case-fold-search nil))
  19158. (looking-at org-complex-heading-regexp)))
  19159. ;; At headline.
  19160. (let ((tags-column (when (match-beginning 5)
  19161. (save-excursion (goto-char (match-beginning 5))
  19162. (current-column))))
  19163. (string (concat " " (progn (when arg (forward-line 1))
  19164. (org-trim (delete-and-extract-region
  19165. (line-beginning-position)
  19166. (line-end-position)))))))
  19167. (unless (bobp) (delete-region (point) (1- (point))))
  19168. (goto-char (or (match-end 4)
  19169. (match-beginning 5)
  19170. (match-end 0)))
  19171. (skip-chars-backward " \t")
  19172. (save-excursion (insert string))
  19173. ;; Adjust alignment of tags.
  19174. (cond
  19175. ((not tags-column)) ;no tags
  19176. (org-auto-align-tags (org-set-tags nil t))
  19177. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19178. (delete-indentation arg)))
  19179. (defun org-open-line (n)
  19180. "Insert a new row in tables, call `open-line' elsewhere.
  19181. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19182. As a special case, when a document starts with a table, allow to
  19183. call `open-line' on the very first character."
  19184. (interactive "*p")
  19185. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19186. (org-table-insert-row)
  19187. (open-line n)))
  19188. (defun org-return (&optional indent)
  19189. "Goto next table row or insert a newline.
  19190. Calls `org-table-next-row' or `newline', depending on context.
  19191. When optional INDENT argument is non-nil, call
  19192. `newline-and-indent' instead of `newline'.
  19193. When `org-return-follows-link' is non-nil and point is on
  19194. a timestamp or a link, call `org-open-at-point'. However, it
  19195. will not happen if point is in a table or on a \"dead\"
  19196. object (e.g., within a comment). In these case, you need to use
  19197. `org-open-at-point' directly."
  19198. (interactive)
  19199. (let ((context (if org-return-follows-link (org-element-context)
  19200. (org-element-at-point))))
  19201. (cond
  19202. ;; In a table, call `org-table-next-row'.
  19203. ((or (and (eq (org-element-type context) 'table)
  19204. (>= (point) (org-element-property :contents-begin context))
  19205. (< (point) (org-element-property :contents-end context)))
  19206. (org-element-lineage context '(table-row table-cell) t))
  19207. (org-table-justify-field-maybe)
  19208. (call-interactively #'org-table-next-row))
  19209. ;; On a link or a timestamp, call `org-open-at-point' if
  19210. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19211. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19212. ((and org-return-follows-link
  19213. (or (org-in-regexp org-ts-regexp-both nil t)
  19214. (org-in-regexp org-tsr-regexp-both nil t)
  19215. (org-in-regexp org-any-link-re nil t)))
  19216. (call-interactively #'org-open-at-point))
  19217. ;; Insert newline in heading, but preserve tags.
  19218. ((and (not (bolp))
  19219. (save-excursion (beginning-of-line)
  19220. (let ((case-fold-search nil))
  19221. (looking-at org-complex-heading-regexp))))
  19222. ;; At headline. Split line. However, if point is on keyword,
  19223. ;; priority cookie or tags, do not break any of them: add
  19224. ;; a newline after the headline instead.
  19225. (let ((tags-column (and (match-beginning 5)
  19226. (save-excursion (goto-char (match-beginning 5))
  19227. (current-column))))
  19228. (string
  19229. (when (and (match-end 4) (org-point-in-group (point) 4))
  19230. (delete-and-extract-region (point) (match-end 4)))))
  19231. ;; Adjust tag alignment.
  19232. (cond
  19233. ((not (and tags-column string)))
  19234. (org-auto-align-tags (org-set-tags nil t))
  19235. (t (org--align-tags-here tags-column))) ;preserve tags column
  19236. (end-of-line)
  19237. (org-show-entry)
  19238. (if indent (newline-and-indent) (newline))
  19239. (when string (save-excursion (insert (org-trim string))))))
  19240. ;; In a list, make sure indenting keeps trailing text within.
  19241. ((and indent
  19242. (not (eolp))
  19243. (org-element-lineage context '(item)))
  19244. (let ((trailing-data
  19245. (delete-and-extract-region (point) (line-end-position))))
  19246. (newline-and-indent)
  19247. (save-excursion (insert trailing-data))))
  19248. (t (if indent (newline-and-indent) (newline))))))
  19249. (defun org-return-indent ()
  19250. "Goto next table row or insert a newline and indent.
  19251. Calls `org-table-next-row' or `newline-and-indent', depending on
  19252. context. See the individual commands for more information."
  19253. (interactive)
  19254. (org-return t))
  19255. (defun org-ctrl-c-tab (&optional _arg)
  19256. "Toggle columns width in a table, or show children.
  19257. Call `org-table-toggle-column-width' if point is in a table.
  19258. Otherwise, call `org-show-children'."
  19259. (interactive "p")
  19260. (call-interactively
  19261. (if (org-at-table-p) #'org-table-toggle-column-width
  19262. #'org-show-children)))
  19263. (defun org-ctrl-c-star ()
  19264. "Compute table, or change heading status of lines.
  19265. Calls `org-table-recalculate' or `org-toggle-heading',
  19266. depending on context."
  19267. (interactive)
  19268. (cond
  19269. ((org-at-table-p)
  19270. (call-interactively 'org-table-recalculate))
  19271. (t
  19272. ;; Convert all lines in region to list items
  19273. (call-interactively 'org-toggle-heading))))
  19274. (defun org-ctrl-c-minus ()
  19275. "Insert separator line in table or modify bullet status of line.
  19276. Also turns a plain line or a region of lines into list items.
  19277. Calls `org-table-insert-hline', `org-toggle-item', or
  19278. `org-cycle-list-bullet', depending on context."
  19279. (interactive)
  19280. (cond
  19281. ((org-at-table-p)
  19282. (call-interactively 'org-table-insert-hline))
  19283. ((org-region-active-p)
  19284. (call-interactively 'org-toggle-item))
  19285. ((org-in-item-p)
  19286. (call-interactively 'org-cycle-list-bullet))
  19287. (t
  19288. (call-interactively 'org-toggle-item))))
  19289. (defun org-toggle-heading (&optional nstars)
  19290. "Convert headings to normal text, or items or text to headings.
  19291. If there is no active region, only convert the current line.
  19292. With a `\\[universal-argument]' prefix, convert the whole list at
  19293. point into heading.
  19294. In a region:
  19295. - If the first non blank line is a headline, remove the stars
  19296. from all headlines in the region.
  19297. - If it is a normal line, turn each and every normal line (i.e.,
  19298. not an heading or an item) in the region into headings. If you
  19299. want to convert only the first line of this region, use one
  19300. universal prefix argument.
  19301. - If it is a plain list item, turn all plain list items into headings.
  19302. When converting a line into a heading, the number of stars is chosen
  19303. such that the lines become children of the current entry. However,
  19304. when a numeric prefix argument is given, its value determines the
  19305. number of stars to add."
  19306. (interactive "P")
  19307. (let ((skip-blanks
  19308. (function
  19309. ;; Return beginning of first non-blank line, starting from
  19310. ;; line at POS.
  19311. (lambda (pos)
  19312. (save-excursion
  19313. (goto-char pos)
  19314. (while (org-at-comment-p) (forward-line))
  19315. (skip-chars-forward " \r\t\n")
  19316. (point-at-bol)))))
  19317. beg end toggled)
  19318. ;; Determine boundaries of changes. If a universal prefix has
  19319. ;; been given, put the list in a region. If region ends at a bol,
  19320. ;; do not consider the last line to be in the region.
  19321. (when (and current-prefix-arg (org-at-item-p))
  19322. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19323. (org-mark-element))
  19324. (if (org-region-active-p)
  19325. (setq beg (funcall skip-blanks (region-beginning))
  19326. end (copy-marker (save-excursion
  19327. (goto-char (region-end))
  19328. (if (bolp) (point) (point-at-eol)))))
  19329. (setq beg (funcall skip-blanks (point-at-bol))
  19330. end (copy-marker (point-at-eol))))
  19331. ;; Ensure inline tasks don't count as headings.
  19332. (org-with-limited-levels
  19333. (save-excursion
  19334. (goto-char beg)
  19335. (cond
  19336. ;; Case 1. Started at an heading: de-star headings.
  19337. ((org-at-heading-p)
  19338. (while (< (point) end)
  19339. (when (org-at-heading-p t)
  19340. (looking-at org-outline-regexp) (replace-match "")
  19341. (setq toggled t))
  19342. (forward-line)))
  19343. ;; Case 2. Started at an item: change items into headlines.
  19344. ;; One star will be added by `org-list-to-subtree'.
  19345. ((org-at-item-p)
  19346. (while (< (point) end)
  19347. (when (org-at-item-p)
  19348. ;; Pay attention to cases when region ends before list.
  19349. (let* ((struct (org-list-struct))
  19350. (list-end
  19351. (min (org-list-get-bottom-point struct) (1+ end))))
  19352. (save-restriction
  19353. (narrow-to-region (point) list-end)
  19354. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19355. (setq toggled t))
  19356. (forward-line)))
  19357. ;; Case 3. Started at normal text: make every line an heading,
  19358. ;; skipping headlines and items.
  19359. (t (let* ((stars
  19360. (make-string
  19361. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19362. (add-stars
  19363. (cond (nstars "") ; stars from prefix only
  19364. ((equal stars "") "*") ; before first heading
  19365. (org-odd-levels-only "**") ; inside heading, odd
  19366. (t "*"))) ; inside heading, oddeven
  19367. (rpl (concat stars add-stars " "))
  19368. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19369. (while (< (point) (if (equal nstars '(4)) lend end))
  19370. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19371. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19372. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19373. (forward-line)))))))
  19374. (unless toggled (message "Cannot toggle heading from here"))))
  19375. (defun org-meta-return (&optional arg)
  19376. "Insert a new heading or wrap a region in a table.
  19377. Calls `org-insert-heading', `org-insert-item' or
  19378. `org-table-wrap-region', depending on context. When called with
  19379. an argument, unconditionally call `org-insert-heading'."
  19380. (interactive "P")
  19381. (org-check-before-invisible-edit 'insert)
  19382. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19383. (call-interactively (cond (arg #'org-insert-heading)
  19384. ((org-at-table-p) #'org-table-wrap-region)
  19385. ((org-in-item-p) #'org-insert-item)
  19386. (t #'org-insert-heading)))))
  19387. ;;; Menu entries
  19388. (defsubst org-in-subtree-not-table-p ()
  19389. "Are we in a subtree and not in a table?"
  19390. (and (not (org-before-first-heading-p))
  19391. (not (org-at-table-p))))
  19392. ;; Define the Org mode menus
  19393. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19394. '("Tbl"
  19395. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19396. ["Next Field" org-cycle (org-at-table-p)]
  19397. ["Previous Field" org-shifttab (org-at-table-p)]
  19398. ["Next Row" org-return (org-at-table-p)]
  19399. "--"
  19400. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19401. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19402. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19403. "--"
  19404. ("Column"
  19405. ["Move Column Left" org-metaleft (org-at-table-p)]
  19406. ["Move Column Right" org-metaright (org-at-table-p)]
  19407. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19408. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  19409. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  19410. ("Row"
  19411. ["Move Row Up" org-metaup (org-at-table-p)]
  19412. ["Move Row Down" org-metadown (org-at-table-p)]
  19413. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19414. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19415. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19416. "--"
  19417. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19418. ("Rectangle"
  19419. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19420. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19421. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19422. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19423. "--"
  19424. ("Calculate"
  19425. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19426. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19427. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19428. "--"
  19429. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19430. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19431. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19432. "--"
  19433. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19434. "--"
  19435. ["Sum Column/Rectangle" org-table-sum
  19436. (or (org-at-table-p) (org-region-active-p))]
  19437. ["Which Column?" org-table-current-column (org-at-table-p)])
  19438. ["Debug Formulas"
  19439. org-table-toggle-formula-debugger
  19440. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19441. ["Show Col/Row Numbers"
  19442. org-table-toggle-coordinate-overlays
  19443. :style toggle
  19444. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19445. "--"
  19446. ["Create" org-table-create (not (org-at-table-p))]
  19447. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19448. ["Import from File" org-table-import (not (org-at-table-p))]
  19449. ["Export to File" org-table-export (org-at-table-p)]
  19450. "--"
  19451. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19452. "--"
  19453. ("Plot"
  19454. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19455. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19456. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19457. '("Org"
  19458. ("Show/Hide"
  19459. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19460. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19461. ["Sparse Tree..." org-sparse-tree t]
  19462. ["Reveal Context" org-reveal t]
  19463. ["Show All" outline-show-all t]
  19464. "--"
  19465. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19466. "--"
  19467. ["New Heading" org-insert-heading t]
  19468. ("Navigate Headings"
  19469. ["Up" outline-up-heading t]
  19470. ["Next" outline-next-visible-heading t]
  19471. ["Previous" outline-previous-visible-heading t]
  19472. ["Next Same Level" outline-forward-same-level t]
  19473. ["Previous Same Level" outline-backward-same-level t]
  19474. "--"
  19475. ["Jump" org-goto t])
  19476. ("Edit Structure"
  19477. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19478. "--"
  19479. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19480. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19481. "--"
  19482. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19483. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19484. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19485. "--"
  19486. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19487. "--"
  19488. ["Copy visible text" org-copy-visible t]
  19489. "--"
  19490. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19491. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19492. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19493. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19494. "--"
  19495. ["Sort Region/Children" org-sort t]
  19496. "--"
  19497. ["Convert to odd levels" org-convert-to-odd-levels t]
  19498. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19499. ("Editing"
  19500. ["Emphasis..." org-emphasize t]
  19501. ["Edit Source Example" org-edit-special t]
  19502. "--"
  19503. ["Footnote new/jump" org-footnote-action t]
  19504. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19505. ("Archive"
  19506. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19507. "--"
  19508. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19509. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19510. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19511. )
  19512. "--"
  19513. ("Hyperlinks"
  19514. ["Store Link (Global)" org-store-link t]
  19515. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19516. ["Insert Link" org-insert-link t]
  19517. ["Follow Link" org-open-at-point t]
  19518. "--"
  19519. ["Next link" org-next-link t]
  19520. ["Previous link" org-previous-link t]
  19521. "--"
  19522. ["Descriptive Links"
  19523. org-toggle-link-display
  19524. :style radio
  19525. :selected org-descriptive-links
  19526. ]
  19527. ["Literal Links"
  19528. org-toggle-link-display
  19529. :style radio
  19530. :selected (not org-descriptive-links)])
  19531. "--"
  19532. ("TODO Lists"
  19533. ["TODO/DONE/-" org-todo t]
  19534. ("Select keyword"
  19535. ["Next keyword" org-shiftright (org-at-heading-p)]
  19536. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19537. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19538. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19539. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19540. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19541. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19542. "--"
  19543. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19544. :selected org-enforce-todo-dependencies :style toggle :active t]
  19545. "Settings for tree at point"
  19546. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19547. :selected (org-entry-get nil "ORDERED")
  19548. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19549. ["Do Children parallel" org-toggle-ordered-property :style radio
  19550. :selected (not (org-entry-get nil "ORDERED"))
  19551. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19552. "--"
  19553. ["Set Priority" org-priority t]
  19554. ["Priority Up" org-shiftup t]
  19555. ["Priority Down" org-shiftdown t]
  19556. "--"
  19557. ["Get news from all feeds" org-feed-update-all t]
  19558. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19559. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19560. ("TAGS and Properties"
  19561. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19562. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19563. "--"
  19564. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19565. ["Column view of properties" org-columns t]
  19566. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19567. ("Dates and Scheduling"
  19568. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19569. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19570. ("Change Date"
  19571. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19572. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19573. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19574. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19575. ["Compute Time Range" org-evaluate-time-range t]
  19576. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19577. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19578. "--"
  19579. ["Custom time format" org-toggle-time-stamp-overlays
  19580. :style radio :selected org-display-custom-times]
  19581. "--"
  19582. ["Goto Calendar" org-goto-calendar t]
  19583. ["Date from Calendar" org-date-from-calendar t]
  19584. "--"
  19585. ["Start/Restart Timer" org-timer-start t]
  19586. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19587. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19588. ["Insert Timer String" org-timer t]
  19589. ["Insert Timer Item" org-timer-item t])
  19590. ("Logging work"
  19591. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19592. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19593. ["Clock out" org-clock-out t]
  19594. ["Clock cancel" org-clock-cancel t]
  19595. "--"
  19596. ["Mark as default task" org-clock-mark-default-task t]
  19597. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19598. ["Goto running clock" org-clock-goto t]
  19599. "--"
  19600. ["Display times" org-clock-display t]
  19601. ["Create clock table" org-clock-report t]
  19602. "--"
  19603. ["Record DONE time"
  19604. (progn (setq org-log-done (not org-log-done))
  19605. (message "Switching to %s will %s record a timestamp"
  19606. (car org-done-keywords)
  19607. (if org-log-done "automatically" "not")))
  19608. :style toggle :selected org-log-done])
  19609. "--"
  19610. ["Agenda Command..." org-agenda t]
  19611. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19612. ("File List for Agenda")
  19613. ("Special views current file"
  19614. ["TODO Tree" org-show-todo-tree t]
  19615. ["Check Deadlines" org-check-deadlines t]
  19616. ["Tags/Property tree" org-match-sparse-tree t])
  19617. "--"
  19618. ["Export/Publish..." org-export-dispatch t]
  19619. ("LaTeX"
  19620. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19621. :selected org-cdlatex-mode]
  19622. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19623. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19624. ["Modify math symbol" org-cdlatex-math-modify
  19625. (org-inside-LaTeX-fragment-p)]
  19626. ["Insert citation" org-reftex-citation t])
  19627. "--"
  19628. ("MobileOrg"
  19629. ["Push Files and Views" org-mobile-push t]
  19630. ["Get Captured and Flagged" org-mobile-pull t]
  19631. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19632. "--"
  19633. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19634. "--"
  19635. ("Documentation"
  19636. ["Show Version" org-version t]
  19637. ["Info Documentation" org-info t])
  19638. ("Customize"
  19639. ["Browse Org Group" org-customize t]
  19640. "--"
  19641. ["Expand This Menu" org-create-customize-menu
  19642. (fboundp 'customize-menu-create)])
  19643. ["Send bug report" org-submit-bug-report t]
  19644. "--"
  19645. ("Refresh/Reload"
  19646. ["Refresh setup current buffer" org-mode-restart t]
  19647. ["Reload Org (after update)" org-reload t]
  19648. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19649. ))
  19650. (defun org-info (&optional node)
  19651. "Read documentation for Org in the info system.
  19652. With optional NODE, go directly to that node."
  19653. (interactive)
  19654. (info (format "(org)%s" (or node ""))))
  19655. ;;;###autoload
  19656. (defun org-submit-bug-report ()
  19657. "Submit a bug report on Org via mail.
  19658. Don't hesitate to report any problems or inaccurate documentation.
  19659. If you don't have setup sending mail from (X)Emacs, please copy the
  19660. output buffer into your mail program, as it gives us important
  19661. information about your Org version and configuration."
  19662. (interactive)
  19663. (require 'reporter)
  19664. (defvar reporter-prompt-for-summary-p)
  19665. (org-load-modules-maybe)
  19666. (org-require-autoloaded-modules)
  19667. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19668. (reporter-submit-bug-report
  19669. "emacs-orgmode@gnu.org"
  19670. (org-version nil 'full)
  19671. (let (list)
  19672. (save-window-excursion
  19673. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19674. (delete-other-windows)
  19675. (erase-buffer)
  19676. (insert "You are about to submit a bug report to the Org mailing list.
  19677. We would like to add your full Org and Outline configuration to the
  19678. bug report. This greatly simplifies the work of the maintainer and
  19679. other experts on the mailing list.
  19680. HOWEVER, some variables you have customized may contain private
  19681. information. The names of customers, colleagues, or friends, might
  19682. appear in the form of file names, tags, todo states, or search strings.
  19683. If you answer yes to the prompt, you might want to check and remove
  19684. such private information before sending the email.")
  19685. (add-text-properties (point-min) (point-max) '(face org-warning))
  19686. (when (yes-or-no-p "Include your Org configuration ")
  19687. (mapatoms
  19688. (lambda (v)
  19689. (and (boundp v)
  19690. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19691. (or (and (symbol-value v)
  19692. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19693. (and
  19694. (get v 'custom-type) (get v 'standard-value)
  19695. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19696. (push v list)))))
  19697. (kill-buffer (get-buffer "*Warn about privacy*"))
  19698. list))
  19699. nil nil
  19700. "Remember to cover the basics, that is, what you expected to happen and
  19701. what in fact did happen. You don't know how to make a good report? See
  19702. http://orgmode.org/manual/Feedback.html#Feedback
  19703. Your bug report will be posted to the Org mailing list.
  19704. ------------------------------------------------------------------------")
  19705. (save-excursion
  19706. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19707. (replace-match "\\1Bug: \\3 [\\2]")))))
  19708. (defun org-install-agenda-files-menu ()
  19709. (let ((bl (buffer-list)))
  19710. (save-excursion
  19711. (while bl
  19712. (set-buffer (pop bl))
  19713. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19714. (when (derived-mode-p 'org-mode)
  19715. (easy-menu-change
  19716. '("Org") "File List for Agenda"
  19717. (append
  19718. (list
  19719. ["Edit File List" (org-edit-agenda-file-list) t]
  19720. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19721. ["Remove Current File from List" org-remove-file t]
  19722. ["Cycle through agenda files" org-cycle-agenda-files t]
  19723. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19724. "--")
  19725. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19726. ;;;; Documentation
  19727. (defun org-require-autoloaded-modules ()
  19728. (interactive)
  19729. (mapc #'require
  19730. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19731. org-table org-timer)))
  19732. ;;;###autoload
  19733. (defun org-reload (&optional uncompiled)
  19734. "Reload all org lisp files.
  19735. With prefix arg UNCOMPILED, load the uncompiled versions."
  19736. (interactive "P")
  19737. (require 'loadhist)
  19738. (let* ((org-dir (org-find-library-dir "org"))
  19739. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19740. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19741. (remove-re (format "\\`%s\\'"
  19742. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19743. (feats (delete-dups
  19744. (mapcar 'file-name-sans-extension
  19745. (mapcar 'file-name-nondirectory
  19746. (delq nil
  19747. (mapcar 'feature-file
  19748. features))))))
  19749. (lfeat (append
  19750. (sort
  19751. (setq feats
  19752. (delq nil (mapcar
  19753. (lambda (f)
  19754. (if (and (string-match feature-re f)
  19755. (not (string-match remove-re f)))
  19756. f nil))
  19757. feats)))
  19758. 'string-lessp)
  19759. (list "org-version" "org")))
  19760. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19761. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19762. load-uncore load-misses)
  19763. (setq load-misses
  19764. (delq 't
  19765. (mapcar (lambda (f)
  19766. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19767. (and (string= org-dir contrib-dir)
  19768. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19769. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19770. (add-to-list 'load-uncore f 'append)
  19771. 't)
  19772. f))
  19773. lfeat)))
  19774. (when load-uncore
  19775. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19776. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19777. (if load-misses
  19778. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19779. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19780. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19781. ;;;###autoload
  19782. (defun org-customize ()
  19783. "Call the customize function with org as argument."
  19784. (interactive)
  19785. (org-load-modules-maybe)
  19786. (org-require-autoloaded-modules)
  19787. (customize-browse 'org))
  19788. (defun org-create-customize-menu ()
  19789. "Create a full customization menu for Org mode, insert it into the menu."
  19790. (interactive)
  19791. (org-load-modules-maybe)
  19792. (org-require-autoloaded-modules)
  19793. (if (fboundp 'customize-menu-create)
  19794. (progn
  19795. (easy-menu-change
  19796. '("Org") "Customize"
  19797. `(["Browse Org group" org-customize t]
  19798. "--"
  19799. ,(customize-menu-create 'org)
  19800. ["Set" Custom-set t]
  19801. ["Save" Custom-save t]
  19802. ["Reset to Current" Custom-reset-current t]
  19803. ["Reset to Saved" Custom-reset-saved t]
  19804. ["Reset to Standard Settings" Custom-reset-standard t]))
  19805. (message "\"Org\"-menu now contains full customization menu"))
  19806. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19807. ;;;; Miscellaneous stuff
  19808. ;;; Generally useful functions
  19809. (defun org-get-at-eol (property n)
  19810. "Get text property PROPERTY at the end of line less N characters."
  19811. (get-text-property (- (point-at-eol) n) property))
  19812. (defun org-find-text-property-in-string (prop s)
  19813. "Return the first non-nil value of property PROP in string S."
  19814. (or (get-text-property 0 prop s)
  19815. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19816. prop s)))
  19817. (defun org-display-warning (message)
  19818. "Display the given MESSAGE as a warning."
  19819. (display-warning 'org message :warning))
  19820. (defun org-eval (form)
  19821. "Eval FORM and return result."
  19822. (condition-case error
  19823. (eval form)
  19824. (error (format "%%![Error: %s]" error))))
  19825. (defun org-in-clocktable-p ()
  19826. "Check if the cursor is in a clocktable."
  19827. (let ((pos (point)) start)
  19828. (save-excursion
  19829. (end-of-line 1)
  19830. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19831. (setq start (match-beginning 0))
  19832. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19833. (>= (match-end 0) pos)
  19834. start))))
  19835. (defun org-in-verbatim-emphasis ()
  19836. (save-match-data
  19837. (and (org-in-regexp org-verbatim-re 2)
  19838. (>= (point) (match-beginning 3))
  19839. (<= (point) (match-end 4)))))
  19840. (defun org-overlay-display (ovl text &optional face evap)
  19841. "Make overlay OVL display TEXT with face FACE."
  19842. (overlay-put ovl 'display text)
  19843. (if face (overlay-put ovl 'face face))
  19844. (if evap (overlay-put ovl 'evaporate t)))
  19845. (defun org-overlay-before-string (ovl text &optional face evap)
  19846. "Make overlay OVL display TEXT with face FACE."
  19847. (if face (org-add-props text nil 'face face))
  19848. (overlay-put ovl 'before-string text)
  19849. (if evap (overlay-put ovl 'evaporate t)))
  19850. (defun org-find-overlays (prop &optional pos delete)
  19851. "Find all overlays specifying PROP at POS or point.
  19852. If DELETE is non-nil, delete all those overlays."
  19853. (let (found)
  19854. (dolist (ov (overlays-at (or pos (point))) found)
  19855. (cond ((not (overlay-get ov prop)))
  19856. (delete (delete-overlay ov))
  19857. (t (push ov found))))))
  19858. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19859. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19860. (if (and marker (marker-buffer marker)
  19861. (buffer-live-p (marker-buffer marker)))
  19862. (progn
  19863. (pop-to-buffer-same-window (marker-buffer marker))
  19864. (when (or (> marker (point-max)) (< marker (point-min)))
  19865. (widen))
  19866. (goto-char marker)
  19867. (org-show-context 'org-goto))
  19868. (if bookmark
  19869. (bookmark-jump bookmark)
  19870. (error "Cannot find location"))))
  19871. (defun org-quote-csv-field (s)
  19872. "Quote field for inclusion in CSV material."
  19873. (if (string-match "[\",]" s)
  19874. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19875. s))
  19876. (defun org-force-self-insert (N)
  19877. "Needed to enforce self-insert under remapping."
  19878. (interactive "p")
  19879. (self-insert-command N))
  19880. (defun org-shorten-string (s maxlength)
  19881. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19882. If the string is shorter or has length MAXLENGTH, just return the
  19883. original string. If it is longer, the functions finds a space in the
  19884. string, breaks this string off at that locations and adds three dots
  19885. as ellipsis. Including the ellipsis, the string will not be longer
  19886. than MAXLENGTH. If finding a good breaking point in the string does
  19887. not work, the string is just chopped off in the middle of a word
  19888. if necessary."
  19889. (if (<= (length s) maxlength)
  19890. s
  19891. (let* ((n (max (- maxlength 4) 1))
  19892. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19893. (if (string-match re s)
  19894. (concat (match-string 1 s) "...")
  19895. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19896. (defun org-get-indentation (&optional line)
  19897. "Get the indentation of the current line, interpreting tabs.
  19898. When LINE is given, assume it represents a line and compute its indentation."
  19899. (if line
  19900. (when (string-match "^ *" (org-remove-tabs line))
  19901. (match-end 0))
  19902. (save-excursion
  19903. (beginning-of-line 1)
  19904. (skip-chars-forward " \t")
  19905. (current-column))))
  19906. (defun org-get-string-indentation (s)
  19907. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19908. (let ((n -1) (i 0) (w tab-width) c)
  19909. (catch 'exit
  19910. (while (< (setq n (1+ n)) (length s))
  19911. (setq c (aref s n))
  19912. (cond ((= c ?\ ) (setq i (1+ i)))
  19913. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19914. (t (throw 'exit t)))))
  19915. i))
  19916. (defun org-remove-tabs (s &optional width)
  19917. "Replace tabulators in S with spaces.
  19918. Assumes that s is a single line, starting in column 0."
  19919. (setq width (or width tab-width))
  19920. (while (string-match "\t" s)
  19921. (setq s (replace-match
  19922. (make-string
  19923. (- (* width (/ (+ (match-beginning 0) width) width))
  19924. (match-beginning 0)) ?\ )
  19925. t t s)))
  19926. s)
  19927. (defun org-fix-indentation (line ind)
  19928. "Fix indentation in LINE.
  19929. IND is a cons cell with target and minimum indentation.
  19930. If the current indentation in LINE is smaller than the minimum,
  19931. leave it alone. If it is larger than ind, set it to the target."
  19932. (let* ((l (org-remove-tabs line))
  19933. (i (org-get-indentation l))
  19934. (i1 (car ind)) (i2 (cdr ind)))
  19935. (when (>= i i2) (setq l (substring line i2)))
  19936. (if (> i1 0)
  19937. (concat (make-string i1 ?\ ) l)
  19938. l)))
  19939. (defun org-remove-indentation (code &optional n)
  19940. "Remove maximum common indentation in string CODE and return it.
  19941. N may optionally be the number of columns to remove. Return CODE
  19942. as-is if removal failed."
  19943. (with-temp-buffer
  19944. (insert code)
  19945. (if (org-do-remove-indentation n) (buffer-string) code)))
  19946. (defun org-do-remove-indentation (&optional n)
  19947. "Remove the maximum common indentation from the buffer.
  19948. When optional argument N is a positive integer, remove exactly
  19949. that much characters from indentation, if possible. Return nil
  19950. if it fails."
  19951. (catch :exit
  19952. (goto-char (point-min))
  19953. ;; Find maximum common indentation, if not specified.
  19954. (let ((n (or n
  19955. (let ((min-ind (point-max)))
  19956. (save-excursion
  19957. (while (re-search-forward "^[ \t]*\\S-" nil t)
  19958. (let ((ind (1- (current-column))))
  19959. (if (zerop ind) (throw :exit nil)
  19960. (setq min-ind (min min-ind ind))))))
  19961. min-ind))))
  19962. (if (zerop n) (throw :exit nil)
  19963. ;; Remove exactly N indentation, but give up if not possible.
  19964. (while (not (eobp))
  19965. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  19966. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  19967. ((< ind n) (throw :exit nil))
  19968. (t (indent-line-to (- ind n))))
  19969. (forward-line)))
  19970. ;; Signal success.
  19971. t))))
  19972. (defun org-fill-template (template alist)
  19973. "Find each %key of ALIST in TEMPLATE and replace it."
  19974. (let ((case-fold-search nil))
  19975. (dolist (entry (sort (copy-sequence alist)
  19976. (lambda (a b) (< (length (car a)) (length (car b))))))
  19977. (setq template
  19978. (replace-regexp-in-string
  19979. (concat "%" (regexp-quote (car entry)))
  19980. (or (cdr entry) "") template t t)))
  19981. template))
  19982. (defun org-base-buffer (buffer)
  19983. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  19984. (if (not buffer)
  19985. buffer
  19986. (or (buffer-base-buffer buffer)
  19987. buffer)))
  19988. (defun org-wrap (string &optional width lines)
  19989. "Wrap string to either a number of lines, or a width in characters.
  19990. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  19991. that costs. If there is a word longer than WIDTH, the text is actually
  19992. wrapped to the length of that word.
  19993. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  19994. many lines, whatever width that takes.
  19995. The return value is a list of lines, without newlines at the end."
  19996. (let* ((words (split-string string))
  19997. (maxword (apply 'max (mapcar 'org-string-width words)))
  19998. w ll)
  19999. (cond (width
  20000. (org-do-wrap words (max maxword width)))
  20001. (lines
  20002. (setq w maxword)
  20003. (setq ll (org-do-wrap words maxword))
  20004. (if (<= (length ll) lines)
  20005. ll
  20006. (setq ll words)
  20007. (while (> (length ll) lines)
  20008. (setq w (1+ w))
  20009. (setq ll (org-do-wrap words w)))
  20010. ll))
  20011. (t (error "Cannot wrap this")))))
  20012. (defun org-do-wrap (words width)
  20013. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20014. (let (lines line)
  20015. (while words
  20016. (setq line (pop words))
  20017. (while (and words (< (+ (length line) (length (car words))) width))
  20018. (setq line (concat line " " (pop words))))
  20019. (setq lines (push line lines)))
  20020. (nreverse lines)))
  20021. (defun org-quote-vert (s)
  20022. "Replace \"|\" with \"\\vert\"."
  20023. (while (string-match "|" s)
  20024. (setq s (replace-match "\\vert" t t s)))
  20025. s)
  20026. (defun org-uuidgen-p (s)
  20027. "Is S an ID created by UUIDGEN?"
  20028. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20029. (defun org-in-src-block-p (&optional inside)
  20030. "Whether point is in a code source block.
  20031. When INSIDE is non-nil, don't consider we are within a src block
  20032. when point is at #+BEGIN_SRC or #+END_SRC."
  20033. (let ((case-fold-search t))
  20034. (or (and (eq (get-char-property (point) 'src-block) t))
  20035. (and (not inside)
  20036. (save-match-data
  20037. (save-excursion
  20038. (beginning-of-line)
  20039. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20040. (defun org-context ()
  20041. "Return a list of contexts of the current cursor position.
  20042. If several contexts apply, all are returned.
  20043. Each context entry is a list with a symbol naming the context, and
  20044. two positions indicating start and end of the context. Possible
  20045. contexts are:
  20046. :headline anywhere in a headline
  20047. :headline-stars on the leading stars in a headline
  20048. :todo-keyword on a TODO keyword (including DONE) in a headline
  20049. :tags on the TAGS in a headline
  20050. :priority on the priority cookie in a headline
  20051. :item on the first line of a plain list item
  20052. :item-bullet on the bullet/number of a plain list item
  20053. :checkbox on the checkbox in a plain list item
  20054. :table in an Org table
  20055. :table-special on a special filed in a table
  20056. :table-table in a table.el table
  20057. :clocktable in a clocktable
  20058. :src-block in a source block
  20059. :link on a hyperlink
  20060. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20061. :target on a <<target>>
  20062. :radio-target on a <<<radio-target>>>
  20063. :latex-fragment on a LaTeX fragment
  20064. :latex-preview on a LaTeX fragment with overlaid preview image
  20065. This function expects the position to be visible because it uses font-lock
  20066. faces as a help to recognize the following contexts: :table-special, :link,
  20067. and :keyword."
  20068. (let* ((f (get-text-property (point) 'face))
  20069. (faces (if (listp f) f (list f)))
  20070. (case-fold-search t)
  20071. (p (point)) clist o)
  20072. ;; First the large context
  20073. (cond
  20074. ((org-at-heading-p t)
  20075. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20076. (when (progn
  20077. (beginning-of-line 1)
  20078. (looking-at org-todo-line-tags-regexp))
  20079. (push (org-point-in-group p 1 :headline-stars) clist)
  20080. (push (org-point-in-group p 2 :todo-keyword) clist)
  20081. (push (org-point-in-group p 4 :tags) clist))
  20082. (goto-char p)
  20083. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20084. (when (looking-at "\\[#[A-Z0-9]\\]")
  20085. (push (org-point-in-group p 0 :priority) clist)))
  20086. ((org-at-item-p)
  20087. (push (org-point-in-group p 2 :item-bullet) clist)
  20088. (push (list :item (point-at-bol)
  20089. (save-excursion (org-end-of-item) (point)))
  20090. clist)
  20091. (and (org-at-item-checkbox-p)
  20092. (push (org-point-in-group p 0 :checkbox) clist)))
  20093. ((org-at-table-p)
  20094. (push (list :table (org-table-begin) (org-table-end)) clist)
  20095. (when (memq 'org-formula faces)
  20096. (push (list :table-special
  20097. (previous-single-property-change p 'face)
  20098. (next-single-property-change p 'face)) clist)))
  20099. ((org-at-table-p 'any)
  20100. (push (list :table-table) clist)))
  20101. (goto-char p)
  20102. (let ((case-fold-search t))
  20103. ;; New the "medium" contexts: clocktables, source blocks
  20104. (cond ((org-in-clocktable-p)
  20105. (push (list :clocktable
  20106. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20107. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20108. (match-beginning 1))
  20109. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20110. (match-end 0))) clist))
  20111. ((org-in-src-block-p)
  20112. (push (list :src-block
  20113. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20114. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20115. (match-beginning 1))
  20116. (and (search-forward "#+END_SRC" nil t)
  20117. (match-beginning 0))) clist))))
  20118. (goto-char p)
  20119. ;; Now the small context
  20120. (cond
  20121. ((org-at-timestamp-p)
  20122. (push (org-point-in-group p 0 :timestamp) clist))
  20123. ((memq 'org-link faces)
  20124. (push (list :link
  20125. (previous-single-property-change p 'face)
  20126. (next-single-property-change p 'face)) clist))
  20127. ((memq 'org-special-keyword faces)
  20128. (push (list :keyword
  20129. (previous-single-property-change p 'face)
  20130. (next-single-property-change p 'face)) clist))
  20131. ((org-at-target-p)
  20132. (push (org-point-in-group p 0 :target) clist)
  20133. (goto-char (1- (match-beginning 0)))
  20134. (when (looking-at org-radio-target-regexp)
  20135. (push (org-point-in-group p 0 :radio-target) clist))
  20136. (goto-char p))
  20137. ((setq o (cl-some
  20138. (lambda (o)
  20139. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20140. o))
  20141. (overlays-at (point))))
  20142. (push (list :latex-fragment
  20143. (overlay-start o) (overlay-end o)) clist)
  20144. (push (list :latex-preview
  20145. (overlay-start o) (overlay-end o)) clist))
  20146. ((org-inside-LaTeX-fragment-p)
  20147. ;; FIXME: positions wrong.
  20148. (push (list :latex-fragment (point) (point)) clist)))
  20149. (setq clist (nreverse (delq nil clist)))
  20150. clist))
  20151. (defun org-in-regexp (regexp &optional nlines visually)
  20152. "Check if point is inside a match of REGEXP.
  20153. Normally only the current line is checked, but you can include
  20154. NLINES extra lines around point into the search. If VISUALLY is
  20155. set, require that the cursor is not after the match but really
  20156. on, so that the block visually is on the match.
  20157. Return nil or a cons cell (BEG . END) where BEG and END are,
  20158. respectively, the positions at the beginning and the end of the
  20159. match."
  20160. (catch :exit
  20161. (let ((pos (point))
  20162. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20163. (save-excursion
  20164. (beginning-of-line (- 1 (or nlines 0)))
  20165. (while (and (re-search-forward regexp eol t)
  20166. (<= (match-beginning 0) pos))
  20167. (let ((end (match-end 0)))
  20168. (when (or (> end pos) (and (= end pos) (not visually)))
  20169. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20170. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20171. "Non-nil when point is between matches of START-RE and END-RE.
  20172. Also return a non-nil value when point is on one of the matches.
  20173. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20174. buffer positions. Default values are the positions of headlines
  20175. surrounding the point.
  20176. The functions returns a cons cell whose car (resp. cdr) is the
  20177. position before START-RE (resp. after END-RE)."
  20178. (save-match-data
  20179. (let ((pos (point))
  20180. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20181. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20182. beg end)
  20183. (save-excursion
  20184. ;; Point is on a block when on START-RE or if START-RE can be
  20185. ;; found before it...
  20186. (and (or (org-in-regexp start-re)
  20187. (re-search-backward start-re limit-up t))
  20188. (setq beg (match-beginning 0))
  20189. ;; ... and END-RE after it...
  20190. (goto-char (match-end 0))
  20191. (re-search-forward end-re limit-down t)
  20192. (> (setq end (match-end 0)) pos)
  20193. ;; ... without another START-RE in-between.
  20194. (goto-char (match-beginning 0))
  20195. (not (re-search-backward start-re (1+ beg) t))
  20196. ;; Return value.
  20197. (cons beg end))))))
  20198. (defun org-in-block-p (names)
  20199. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20200. NAMES is a list of strings containing names of blocks.
  20201. Return first block name matched, or nil. Beware that in case of
  20202. nested blocks, the returned name may not belong to the closest
  20203. block from point."
  20204. (save-match-data
  20205. (catch 'exit
  20206. (let ((case-fold-search t)
  20207. (lim-up (save-excursion (outline-previous-heading)))
  20208. (lim-down (save-excursion (outline-next-heading))))
  20209. (dolist (name names)
  20210. (let ((n (regexp-quote name)))
  20211. (when (org-between-regexps-p
  20212. (concat "^[ \t]*#\\+begin_" n)
  20213. (concat "^[ \t]*#\\+end_" n)
  20214. lim-up lim-down)
  20215. (throw 'exit n)))))
  20216. nil)))
  20217. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20218. "Call `multi-occur' with buffers for all agenda files."
  20219. (interactive "sOrg-files matching: ")
  20220. (let* ((files (org-agenda-files))
  20221. (tnames (mapcar #'file-truename files))
  20222. (extra org-agenda-text-search-extra-files))
  20223. (when (eq (car extra) 'agenda-archives)
  20224. (setq extra (cdr extra))
  20225. (setq files (org-add-archive-files files)))
  20226. (dolist (f extra)
  20227. (unless (member (file-truename f) tnames)
  20228. (unless (member f files) (setq files (append files (list f))))
  20229. (setq tnames (append tnames (list (file-truename f))))))
  20230. (multi-occur
  20231. (mapcar (lambda (x)
  20232. (with-current-buffer
  20233. ;; FIXME: Why not just (find-file-noselect x)?
  20234. ;; Is it to avoid the "revert buffer" prompt?
  20235. (or (get-file-buffer x) (find-file-noselect x))
  20236. (widen)
  20237. (current-buffer)))
  20238. files)
  20239. regexp)))
  20240. (add-hook 'occur-mode-find-occurrence-hook
  20241. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20242. (defun org-occur-link-in-agenda-files ()
  20243. "Create a link and search for it in the agendas.
  20244. The link is not stored in `org-stored-links', it is just created
  20245. for the search purpose."
  20246. (interactive)
  20247. (let ((link (condition-case nil
  20248. (org-store-link nil)
  20249. (error "Unable to create a link to here"))))
  20250. (org-occur-in-agenda-files (regexp-quote link))))
  20251. (defun org-reverse-string (string)
  20252. "Return the reverse of STRING."
  20253. (apply 'string (reverse (string-to-list string))))
  20254. ;; defsubst org-uniquify must be defined before first use
  20255. (defun org-uniquify-alist (alist)
  20256. "Merge elements of ALIST with the same key.
  20257. For example, in this alist:
  20258. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20259. => \\='((a 1 3) (b 2))
  20260. merge (a 1) and (a 3) into (a 1 3).
  20261. The function returns the new ALIST."
  20262. (let (rtn)
  20263. (dolist (e alist rtn)
  20264. (let (n)
  20265. (if (not (assoc (car e) rtn))
  20266. (push e rtn)
  20267. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20268. (setq rtn (assq-delete-all (car e) rtn))
  20269. (push n rtn))))))
  20270. (defun org-delete-all (elts list)
  20271. "Remove all elements in ELTS from LIST.
  20272. Comparison is done with `equal'. It is a destructive operation
  20273. that may remove elements by altering the list structure."
  20274. (while elts
  20275. (setq list (delete (pop elts) list)))
  20276. list)
  20277. (defun org-back-over-empty-lines ()
  20278. "Move backwards over whitespace, to the beginning of the first empty line.
  20279. Returns the number of empty lines passed."
  20280. (let ((pos (point)))
  20281. (if (cdr (assq 'heading org-blank-before-new-entry))
  20282. (skip-chars-backward " \t\n\r")
  20283. (unless (eobp)
  20284. (forward-line -1)))
  20285. (beginning-of-line 2)
  20286. (goto-char (min (point) pos))
  20287. (count-lines (point) pos)))
  20288. (defun org-skip-whitespace ()
  20289. (skip-chars-forward " \t\n\r"))
  20290. (defun org-point-in-group (point group &optional context)
  20291. "Check if POINT is in match-group GROUP.
  20292. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20293. match. If the match group does not exist or point is not inside it,
  20294. return nil."
  20295. (and (match-beginning group)
  20296. (>= point (match-beginning group))
  20297. (<= point (match-end group))
  20298. (if context
  20299. (list context (match-beginning group) (match-end group))
  20300. t)))
  20301. (defun org-switch-to-buffer-other-window (&rest args)
  20302. "Switch to buffer in a second window on the current frame.
  20303. In particular, do not allow pop-up frames.
  20304. Returns the newly created buffer."
  20305. (org-no-popups
  20306. (apply 'switch-to-buffer-other-window args)))
  20307. (defun org-combine-plists (&rest plists)
  20308. "Create a single property list from all plists in PLISTS.
  20309. The process starts by copying the first list, and then setting properties
  20310. from the other lists. Settings in the last list are the most significant
  20311. ones and overrule settings in the other lists."
  20312. (let ((rtn (copy-sequence (pop plists)))
  20313. p v ls)
  20314. (while plists
  20315. (setq ls (pop plists))
  20316. (while ls
  20317. (setq p (pop ls) v (pop ls))
  20318. (setq rtn (plist-put rtn p v))))
  20319. rtn))
  20320. (defun org-replace-escapes (string table)
  20321. "Replace %-escapes in STRING with values in TABLE.
  20322. TABLE is an association list with keys like \"%a\" and string values.
  20323. The sequences in STRING may contain normal field width and padding information,
  20324. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20325. so values can contain further %-escapes if they are define later in TABLE."
  20326. (let ((tbl (copy-alist table))
  20327. (case-fold-search nil)
  20328. (pchg 0)
  20329. re rpl)
  20330. (dolist (e tbl)
  20331. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20332. (when (and (cdr e) (string-match re (cdr e)))
  20333. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20334. (safe "SREF"))
  20335. (add-text-properties 0 3 (list 'sref sref) safe)
  20336. (setcdr e (replace-match safe t t (cdr e)))))
  20337. (while (string-match re string)
  20338. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20339. (cdr e)))
  20340. (setq string (replace-match rpl t t string))))
  20341. (while (setq pchg (next-property-change pchg string))
  20342. (let ((sref (get-text-property pchg 'sref string)))
  20343. (when (and sref (string-match "SREF" string pchg))
  20344. (setq string (replace-match sref t t string)))))
  20345. string))
  20346. (defun org-find-base-buffer-visiting (file)
  20347. "Like `find-buffer-visiting' but always return the base buffer and
  20348. not an indirect buffer."
  20349. (let ((buf (or (get-file-buffer file)
  20350. (find-buffer-visiting file))))
  20351. (if buf
  20352. (or (buffer-base-buffer buf) buf)
  20353. nil)))
  20354. ;;; TODO: Only called once, from ox-odt which should probably use
  20355. ;;; org-export-inline-image-p or something.
  20356. (defun org-file-image-p (file)
  20357. "Return non-nil if FILE is an image."
  20358. (save-match-data
  20359. (string-match (image-file-name-regexp) file)))
  20360. (defun org-get-cursor-date (&optional with-time)
  20361. "Return the date at cursor in as a time.
  20362. This works in the calendar and in the agenda, anywhere else it just
  20363. returns the current time.
  20364. If WITH-TIME is non-nil, returns the time of the event at point (in
  20365. the agenda) or the current time of the day."
  20366. (let (date day defd tp hod mod)
  20367. (when with-time
  20368. (setq tp (get-text-property (point) 'time))
  20369. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20370. (setq hod (string-to-number (match-string 1 tp))
  20371. mod (string-to-number (match-string 2 tp))))
  20372. (or tp (let ((now (decode-time)))
  20373. (setq hod (nth 2 now)
  20374. mod (nth 1 now)))))
  20375. (cond
  20376. ((eq major-mode 'calendar-mode)
  20377. (setq date (calendar-cursor-to-date)
  20378. defd (encode-time 0 (or mod 0) (or hod 0)
  20379. (nth 1 date) (nth 0 date) (nth 2 date))))
  20380. ((eq major-mode 'org-agenda-mode)
  20381. (setq day (get-text-property (point) 'day))
  20382. (when day
  20383. (setq date (calendar-gregorian-from-absolute day)
  20384. defd (encode-time 0 (or mod 0) (or hod 0)
  20385. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20386. (or defd (current-time))))
  20387. (defun org-mark-subtree (&optional up)
  20388. "Mark the current subtree.
  20389. This puts point at the start of the current subtree, and mark at
  20390. the end. If a numeric prefix UP is given, move up into the
  20391. hierarchy of headlines by UP levels before marking the subtree."
  20392. (interactive "P")
  20393. (org-with-limited-levels
  20394. (cond ((org-at-heading-p) (beginning-of-line))
  20395. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20396. (t (outline-previous-visible-heading 1))))
  20397. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20398. (if (called-interactively-p 'any)
  20399. (call-interactively 'org-mark-element)
  20400. (org-mark-element)))
  20401. (defun org-file-newer-than-p (file time)
  20402. "Non-nil if FILE is newer than TIME.
  20403. FILE is a filename, as a string, TIME is a list of integers, as
  20404. returned by, e.g., `current-time'."
  20405. (and (file-exists-p file)
  20406. ;; Only compare times up to whole seconds as some file-systems
  20407. ;; (e.g. HFS+) do not retain any finer granularity. As
  20408. ;; a consequence, make sure we return non-nil when the two
  20409. ;; times are equal.
  20410. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20411. (cl-subseq time 0 2)))))
  20412. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20413. "Compile a SOURCE file using PROCESS.
  20414. PROCESS is either a function or a list of shell commands, as
  20415. strings. EXT is a file extension, without the leading dot, as
  20416. a string. It is used to check if the process actually succeeded.
  20417. PROCESS must create a file with the same base name and directory
  20418. as SOURCE, but ending with EXT. The function then returns its
  20419. filename. Otherwise, it raises an error. The error message can
  20420. then be refined by providing string ERR-MSG, which is appended to
  20421. the standard message.
  20422. If PROCESS is a function, it is called with a single argument:
  20423. the SOURCE file.
  20424. If it is a list of commands, each of them is called using
  20425. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20426. %O are replaced with, respectively, SOURCE base name, name, full
  20427. name, directory and absolute output file name. It is possible,
  20428. however, to use more place-holders by specifying them in optional
  20429. argument SPEC, as an alist following the pattern
  20430. (CHARACTER . REPLACEMENT-STRING).
  20431. When PROCESS is a list of commands, optional argument LOG-BUF can
  20432. be set to a buffer or a buffer name. `shell-command' then uses
  20433. it for output."
  20434. (let* ((base-name (file-name-base source))
  20435. (full-name (file-truename source))
  20436. (out-dir (or (file-name-directory source) "./"))
  20437. (output (expand-file-name (concat base-name "." ext) out-dir))
  20438. (time (current-time))
  20439. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20440. (save-window-excursion
  20441. (pcase process
  20442. ((pred functionp) (funcall process (shell-quote-argument source)))
  20443. ((pred consp)
  20444. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20445. (spec (append spec
  20446. `((?b . ,(shell-quote-argument base-name))
  20447. (?f . ,(shell-quote-argument source))
  20448. (?F . ,(shell-quote-argument full-name))
  20449. (?o . ,(shell-quote-argument out-dir))
  20450. (?O . ,(shell-quote-argument output))))))
  20451. (dolist (command process)
  20452. (shell-command (format-spec command spec) log-buf))
  20453. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20454. (_ (error "No valid command to process %S%s" source err-msg))))
  20455. ;; Check for process failure. Output file is expected to be
  20456. ;; located in the same directory as SOURCE.
  20457. (unless (org-file-newer-than-p output time)
  20458. (error (format "File %S wasn't produced%s" output err-msg)))
  20459. output))
  20460. ;;; Indentation
  20461. (defvar org-element-greater-elements)
  20462. (defun org--get-expected-indentation (element contentsp)
  20463. "Expected indentation column for current line, according to ELEMENT.
  20464. ELEMENT is an element containing point. CONTENTSP is non-nil
  20465. when indentation is to be computed according to contents of
  20466. ELEMENT."
  20467. (let ((type (org-element-type element))
  20468. (start (org-element-property :begin element))
  20469. (post-affiliated (org-element-property :post-affiliated element)))
  20470. (org-with-wide-buffer
  20471. (cond
  20472. (contentsp
  20473. (cl-case type
  20474. ((diary-sexp footnote-definition) 0)
  20475. ((headline inlinetask nil)
  20476. (if (not org-adapt-indentation) 0
  20477. (let ((level (org-current-level)))
  20478. (if level (1+ level) 0))))
  20479. ((item plain-list) (org-list-item-body-column post-affiliated))
  20480. (t
  20481. (goto-char start)
  20482. (org-get-indentation))))
  20483. ((memq type '(headline inlinetask nil))
  20484. (if (org-match-line "[ \t]*$")
  20485. (org--get-expected-indentation element t)
  20486. 0))
  20487. ((memq type '(diary-sexp footnote-definition)) 0)
  20488. ;; First paragraph of a footnote definition or an item.
  20489. ;; Indent like parent.
  20490. ((< (line-beginning-position) start)
  20491. (org--get-expected-indentation
  20492. (org-element-property :parent element) t))
  20493. ;; At first line: indent according to previous sibling, if any,
  20494. ;; ignoring footnote definitions and inline tasks, or parent's
  20495. ;; contents.
  20496. ((= (line-beginning-position) start)
  20497. (catch 'exit
  20498. (while t
  20499. (if (= (point-min) start) (throw 'exit 0)
  20500. (goto-char (1- start))
  20501. (let* ((previous (org-element-at-point))
  20502. (parent previous))
  20503. (while (and parent (<= (org-element-property :end parent) start))
  20504. (setq previous parent
  20505. parent (org-element-property :parent parent)))
  20506. (cond
  20507. ((not previous) (throw 'exit 0))
  20508. ((> (org-element-property :end previous) start)
  20509. (throw 'exit (org--get-expected-indentation previous t)))
  20510. ((memq (org-element-type previous)
  20511. '(footnote-definition inlinetask))
  20512. (setq start (org-element-property :begin previous)))
  20513. (t (goto-char (org-element-property :begin previous))
  20514. (throw 'exit
  20515. (if (bolp) (org-get-indentation)
  20516. ;; At first paragraph in an item or
  20517. ;; a footnote definition.
  20518. (org--get-expected-indentation
  20519. (org-element-property :parent previous) t))))))))))
  20520. ;; Otherwise, move to the first non-blank line above.
  20521. (t
  20522. (beginning-of-line)
  20523. (let ((pos (point)))
  20524. (skip-chars-backward " \r\t\n")
  20525. (cond
  20526. ;; Two blank lines end a footnote definition or a plain
  20527. ;; list. When we indent an empty line after them, the
  20528. ;; containing list or footnote definition is over, so it
  20529. ;; qualifies as a previous sibling. Therefore, we indent
  20530. ;; like its first line.
  20531. ((and (memq type '(footnote-definition plain-list))
  20532. (> (count-lines (point) pos) 2))
  20533. (goto-char start)
  20534. (org-get-indentation))
  20535. ;; Line above is the first one of a paragraph at the
  20536. ;; beginning of an item or a footnote definition. Indent
  20537. ;; like parent.
  20538. ((< (line-beginning-position) start)
  20539. (org--get-expected-indentation
  20540. (org-element-property :parent element) t))
  20541. ;; Line above is the beginning of an element, i.e., point
  20542. ;; was originally on the blank lines between element's start
  20543. ;; and contents.
  20544. ((= (line-beginning-position) post-affiliated)
  20545. (org--get-expected-indentation element t))
  20546. ;; POS is after contents in a greater element. Indent like
  20547. ;; the beginning of the element.
  20548. ((and (memq type org-element-greater-elements)
  20549. (let ((cend (org-element-property :contents-end element)))
  20550. (and cend (<= cend pos))))
  20551. ;; As a special case, if point is at the end of a footnote
  20552. ;; definition or an item, indent like the very last element
  20553. ;; within. If that last element is an item, indent like
  20554. ;; its contents.
  20555. (if (memq type '(footnote-definition item plain-list))
  20556. (let ((last (org-element-at-point)))
  20557. (goto-char pos)
  20558. (org--get-expected-indentation
  20559. last (eq (org-element-type last) 'item)))
  20560. (goto-char start)
  20561. (org-get-indentation)))
  20562. ;; In any other case, indent like the current line.
  20563. (t (org-get-indentation)))))))))
  20564. (defun org--align-node-property ()
  20565. "Align node property at point.
  20566. Alignment is done according to `org-property-format', which see."
  20567. (when (save-excursion
  20568. (beginning-of-line)
  20569. (looking-at org-property-re))
  20570. (replace-match
  20571. (concat (match-string 4)
  20572. (org-trim
  20573. (format org-property-format (match-string 1) (match-string 3))))
  20574. t t)))
  20575. (defun org-indent-line ()
  20576. "Indent line depending on context.
  20577. Indentation is done according to the following rules:
  20578. - Footnote definitions, diary sexps, headlines and inline tasks
  20579. have to start at column 0.
  20580. - On the very first line of an element, consider, in order, the
  20581. next rules until one matches:
  20582. 1. If there's a sibling element before, ignoring footnote
  20583. definitions and inline tasks, indent like its first line.
  20584. 2. If element has a parent, indent like its contents. More
  20585. precisely, if parent is an item, indent after the
  20586. description part, if any, or the bullet (see
  20587. `org-list-description-max-indent'). Else, indent like
  20588. parent's first line.
  20589. 3. Otherwise, indent relatively to current level, if
  20590. `org-adapt-indentation' is non-nil, or to left margin.
  20591. - On a blank line at the end of an element, indent according to
  20592. the type of the element. More precisely
  20593. 1. If element is a plain list, an item, or a footnote
  20594. definition, indent like the very last element within.
  20595. 2. If element is a paragraph, indent like its last non blank
  20596. line.
  20597. 3. Otherwise, indent like its very first line.
  20598. - In the code part of a source block, use language major mode
  20599. to indent current line if `org-src-tab-acts-natively' is
  20600. non-nil. If it is nil, do nothing.
  20601. - Otherwise, indent like the first non-blank line above.
  20602. The function doesn't indent an item as it could break the whole
  20603. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20604. `\\[org-shiftmetaright]'.
  20605. Also align node properties according to `org-property-format'."
  20606. (interactive)
  20607. (cond
  20608. (orgstruct-is-++
  20609. (let ((indent-line-function
  20610. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20611. (indent-according-to-mode)))
  20612. ((org-at-heading-p) 'noindent)
  20613. (t
  20614. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20615. (type (org-element-type element)))
  20616. (cond ((and (memq type '(plain-list item))
  20617. (= (line-beginning-position)
  20618. (org-element-property :post-affiliated element)))
  20619. 'noindent)
  20620. ((and (eq type 'latex-environment)
  20621. (>= (point) (org-element-property :post-affiliated element))
  20622. (< (point) (org-with-wide-buffer
  20623. (goto-char (org-element-property :end element))
  20624. (skip-chars-backward " \r\t\n")
  20625. (line-beginning-position 2))))
  20626. 'noindent)
  20627. ((and (eq type 'src-block)
  20628. org-src-tab-acts-natively
  20629. (> (line-beginning-position)
  20630. (org-element-property :post-affiliated element))
  20631. (< (line-beginning-position)
  20632. (org-with-wide-buffer
  20633. (goto-char (org-element-property :end element))
  20634. (skip-chars-backward " \r\t\n")
  20635. (line-beginning-position))))
  20636. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20637. (t
  20638. (let ((column (org--get-expected-indentation element nil)))
  20639. ;; Preserve current column.
  20640. (if (<= (current-column) (current-indentation))
  20641. (indent-line-to column)
  20642. (save-excursion (indent-line-to column))))
  20643. ;; Align node property. Also preserve current column.
  20644. (when (eq type 'node-property)
  20645. (let ((column (current-column)))
  20646. (org--align-node-property)
  20647. (org-move-to-column column)))))))))
  20648. (defun org-indent-region (start end)
  20649. "Indent each non-blank line in the region.
  20650. Called from a program, START and END specify the region to
  20651. indent. The function will not indent contents of example blocks,
  20652. verse blocks and export blocks as leading white spaces are
  20653. assumed to be significant there."
  20654. (interactive "r")
  20655. (save-excursion
  20656. (goto-char start)
  20657. (skip-chars-forward " \r\t\n")
  20658. (unless (eobp) (beginning-of-line))
  20659. (let ((indent-to
  20660. (lambda (ind pos)
  20661. ;; Set IND as indentation for all lines between point and
  20662. ;; POS. Blank lines are ignored. Leave point after POS
  20663. ;; once done.
  20664. (let ((limit (copy-marker pos)))
  20665. (while (< (point) limit)
  20666. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20667. (forward-line))
  20668. (set-marker limit nil))))
  20669. (end (copy-marker end)))
  20670. (while (< (point) end)
  20671. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20672. (let* ((element (org-element-at-point))
  20673. (type (org-element-type element))
  20674. (element-end (copy-marker (org-element-property :end element)))
  20675. (ind (org--get-expected-indentation element nil)))
  20676. (cond
  20677. ;; Element indented as a single block. Example blocks
  20678. ;; preserving indentation are a special case since the
  20679. ;; "contents" must not be indented whereas the block
  20680. ;; boundaries can.
  20681. ((or (memq type '(export-block latex-environment))
  20682. (and (eq type 'example-block)
  20683. (not
  20684. (or org-src-preserve-indentation
  20685. (org-element-property :preserve-indent element)))))
  20686. (let ((offset (- ind (org-get-indentation))))
  20687. (unless (zerop offset)
  20688. (indent-rigidly (org-element-property :begin element)
  20689. (org-element-property :end element)
  20690. offset)))
  20691. (goto-char element-end))
  20692. ;; Elements indented line wise. Be sure to exclude
  20693. ;; example blocks (preserving indentation) and source
  20694. ;; blocks from this category as they are treated
  20695. ;; specially later.
  20696. ((or (memq type '(paragraph table table-row))
  20697. (not (or (org-element-property :contents-begin element)
  20698. (memq type '(example-block src-block)))))
  20699. (when (eq type 'node-property)
  20700. (org--align-node-property)
  20701. (beginning-of-line))
  20702. (funcall indent-to ind (min element-end end)))
  20703. ;; Elements consisting of three parts: before the
  20704. ;; contents, the contents, and after the contents. The
  20705. ;; contents are treated specially, according to the
  20706. ;; element type, or not indented at all. Other parts are
  20707. ;; indented as a single block.
  20708. (t
  20709. (let* ((post (copy-marker
  20710. (org-element-property :post-affiliated element)))
  20711. (cbeg
  20712. (copy-marker
  20713. (cond
  20714. ((not (org-element-property :contents-begin element))
  20715. ;; Fake contents for source blocks.
  20716. (org-with-wide-buffer
  20717. (goto-char post)
  20718. (line-beginning-position 2)))
  20719. ((memq type '(footnote-definition item plain-list))
  20720. ;; Contents in these elements could start on
  20721. ;; the same line as the beginning of the
  20722. ;; element. Make sure we start indenting
  20723. ;; from the second line.
  20724. (org-with-wide-buffer
  20725. (goto-char post)
  20726. (end-of-line)
  20727. (skip-chars-forward " \r\t\n")
  20728. (if (eobp) (point) (line-beginning-position))))
  20729. (t (org-element-property :contents-begin element)))))
  20730. (cend (copy-marker
  20731. (or (org-element-property :contents-end element)
  20732. ;; Fake contents for source blocks.
  20733. (org-with-wide-buffer
  20734. (goto-char element-end)
  20735. (skip-chars-backward " \r\t\n")
  20736. (line-beginning-position)))
  20737. t)))
  20738. ;; Do not change items indentation individually as it
  20739. ;; might break the list as a whole. On the other
  20740. ;; hand, when at a plain list, indent it as a whole.
  20741. (cond ((eq type 'plain-list)
  20742. (let ((offset (- ind (org-get-indentation))))
  20743. (unless (zerop offset)
  20744. (indent-rigidly (org-element-property :begin element)
  20745. (org-element-property :end element)
  20746. offset))
  20747. (goto-char cbeg)))
  20748. ((eq type 'item) (goto-char cbeg))
  20749. (t (funcall indent-to ind (min cbeg end))))
  20750. (when (< (point) end)
  20751. (cl-case type
  20752. ((example-block verse-block))
  20753. (src-block
  20754. ;; In a source block, indent source code
  20755. ;; according to language major mode, but only if
  20756. ;; `org-src-tab-acts-natively' is non-nil.
  20757. (when (and (< (point) end) org-src-tab-acts-natively)
  20758. (ignore-errors
  20759. (org-babel-do-in-edit-buffer
  20760. (indent-region (point-min) (point-max))))))
  20761. (t (org-indent-region (point) (min cend end))))
  20762. (goto-char (min cend end))
  20763. (when (< (point) end)
  20764. (funcall indent-to ind (min element-end end))))
  20765. (set-marker post nil)
  20766. (set-marker cbeg nil)
  20767. (set-marker cend nil))))
  20768. (set-marker element-end nil))))
  20769. (set-marker end nil))))
  20770. (defun org-indent-drawer ()
  20771. "Indent the drawer at point."
  20772. (interactive)
  20773. (unless (save-excursion
  20774. (beginning-of-line)
  20775. (looking-at-p org-drawer-regexp))
  20776. (user-error "Not at a drawer"))
  20777. (let ((element (org-element-at-point)))
  20778. (unless (memq (org-element-type element) '(drawer property-drawer))
  20779. (user-error "Not at a drawer"))
  20780. (org-with-wide-buffer
  20781. (org-indent-region (org-element-property :begin element)
  20782. (org-element-property :end element))))
  20783. (message "Drawer at point indented"))
  20784. (defun org-indent-block ()
  20785. "Indent the block at point."
  20786. (interactive)
  20787. (unless (save-excursion
  20788. (beginning-of-line)
  20789. (let ((case-fold-search t))
  20790. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20791. (user-error "Not at a block"))
  20792. (let ((element (org-element-at-point)))
  20793. (unless (memq (org-element-type element)
  20794. '(comment-block center-block dynamic-block example-block
  20795. export-block quote-block special-block
  20796. src-block verse-block))
  20797. (user-error "Not at a block"))
  20798. (org-with-wide-buffer
  20799. (org-indent-region (org-element-property :begin element)
  20800. (org-element-property :end element))))
  20801. (message "Block at point indented"))
  20802. ;;; Filling
  20803. ;; We use our own fill-paragraph and auto-fill functions.
  20804. ;; `org-fill-paragraph' relies on adaptive filling and context
  20805. ;; checking. Appropriate `fill-prefix' is computed with
  20806. ;; `org-adaptive-fill-function'.
  20807. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20808. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20809. ;; `org-adaptive-fill-function' value. Internally,
  20810. ;; `org-comment-line-break-function' breaks the line.
  20811. ;; `org-setup-filling' installs filling and auto-filling related
  20812. ;; variables during `org-mode' initialization.
  20813. (defvar org-element-paragraph-separate) ; org-element.el
  20814. (defun org-setup-filling ()
  20815. (require 'org-element)
  20816. ;; Prevent auto-fill from inserting unwanted new items.
  20817. (when (boundp 'fill-nobreak-predicate)
  20818. (setq-local
  20819. fill-nobreak-predicate
  20820. (org-uniquify
  20821. (append fill-nobreak-predicate
  20822. '(org-fill-line-break-nobreak-p
  20823. org-fill-n-macro-as-item-nobreak-p
  20824. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20825. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20826. (setq-local paragraph-start paragraph-ending)
  20827. (setq-local paragraph-separate paragraph-ending))
  20828. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20829. (setq-local auto-fill-inhibit-regexp nil)
  20830. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20831. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20832. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20833. (defun org-fill-line-break-nobreak-p ()
  20834. "Non-nil when a new line at point would create an Org line break."
  20835. (save-excursion
  20836. (skip-chars-backward "[ \t]")
  20837. (skip-chars-backward "\\\\")
  20838. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20839. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20840. "Non-nil when a new line at point would split a timestamp."
  20841. (and (org-at-timestamp-p 'lax)
  20842. (not (looking-at org-ts-regexp-both))))
  20843. (defun org-fill-n-macro-as-item-nobreak-p ()
  20844. "Non-nil when a new line at point would create a new list."
  20845. ;; During export, a "n" macro followed by a dot or a closing
  20846. ;; parenthesis can end up being parsed as a new list item.
  20847. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20848. (declare-function message-in-body-p "message" ())
  20849. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20850. (defun org-adaptive-fill-function ()
  20851. "Compute a fill prefix for the current line.
  20852. Return fill prefix, as a string, or nil if current line isn't
  20853. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20854. matches in paragraphs or comments, use it."
  20855. (catch 'exit
  20856. (when (derived-mode-p 'message-mode)
  20857. (save-excursion
  20858. (beginning-of-line)
  20859. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20860. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20861. ((looking-at message-cite-prefix-regexp)
  20862. (throw 'exit (match-string-no-properties 0)))
  20863. ((looking-at org-outline-regexp)
  20864. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20865. (org-with-wide-buffer
  20866. (unless (org-at-heading-p)
  20867. (let* ((p (line-beginning-position))
  20868. (element (save-excursion
  20869. (beginning-of-line)
  20870. (org-element-at-point)))
  20871. (type (org-element-type element))
  20872. (post-affiliated (org-element-property :post-affiliated element)))
  20873. (unless (< p post-affiliated)
  20874. (cl-case type
  20875. (comment
  20876. (save-excursion
  20877. (beginning-of-line)
  20878. (looking-at "[ \t]*")
  20879. (concat (match-string 0) "# ")))
  20880. (footnote-definition "")
  20881. ((item plain-list)
  20882. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20883. (paragraph
  20884. ;; Fill prefix is usually the same as the current line,
  20885. ;; unless the paragraph is at the beginning of an item.
  20886. (let ((parent (org-element-property :parent element)))
  20887. (save-excursion
  20888. (beginning-of-line)
  20889. (cond ((eq (org-element-type parent) 'item)
  20890. (make-string (org-list-item-body-column
  20891. (org-element-property :begin parent))
  20892. ?\s))
  20893. ((and adaptive-fill-regexp
  20894. ;; Locally disable
  20895. ;; `adaptive-fill-function' to let
  20896. ;; `fill-context-prefix' handle
  20897. ;; `adaptive-fill-regexp' variable.
  20898. (let (adaptive-fill-function)
  20899. (fill-context-prefix
  20900. post-affiliated
  20901. (org-element-property :end element)))))
  20902. ((looking-at "[ \t]+") (match-string 0))
  20903. (t "")))))
  20904. (comment-block
  20905. ;; Only fill contents if P is within block boundaries.
  20906. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20907. (forward-line)
  20908. (point)))
  20909. (cend (save-excursion
  20910. (goto-char (org-element-property :end element))
  20911. (skip-chars-backward " \r\t\n")
  20912. (line-beginning-position))))
  20913. (when (and (>= p cbeg) (< p cend))
  20914. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20915. (match-string 0)
  20916. "")))))))))))
  20917. (declare-function message-goto-body "message" ())
  20918. (defvar message-cite-prefix-regexp) ; From message.el
  20919. (defun org-fill-element (&optional justify)
  20920. "Fill element at point, when applicable.
  20921. This function only applies to comment blocks, comments, example
  20922. blocks and paragraphs. Also, as a special case, re-align table
  20923. when point is at one.
  20924. If JUSTIFY is non-nil (interactively, with prefix argument),
  20925. justify as well. If `sentence-end-double-space' is non-nil, then
  20926. period followed by one space does not end a sentence, so don't
  20927. break a line there. The variable `fill-column' controls the
  20928. width for filling.
  20929. For convenience, when point is at a plain list, an item or
  20930. a footnote definition, try to fill the first paragraph within."
  20931. (with-syntax-table org-mode-transpose-word-syntax-table
  20932. ;; Move to end of line in order to get the first paragraph within
  20933. ;; a plain list or a footnote definition.
  20934. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20935. ;; First check if point is in a blank line at the beginning of
  20936. ;; the buffer. In that case, ignore filling.
  20937. (cl-case (org-element-type element)
  20938. ;; Use major mode filling function is src blocks.
  20939. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20940. ;; Align Org tables, leave table.el tables as-is.
  20941. (table-row (org-table-align) t)
  20942. (table
  20943. (when (eq (org-element-property :type element) 'org)
  20944. (save-excursion
  20945. (goto-char (org-element-property :post-affiliated element))
  20946. (org-table-align)))
  20947. t)
  20948. (paragraph
  20949. ;; Paragraphs may contain `line-break' type objects.
  20950. (let ((beg (max (point-min)
  20951. (org-element-property :contents-begin element)))
  20952. (end (min (point-max)
  20953. (org-element-property :contents-end element))))
  20954. ;; Do nothing if point is at an affiliated keyword.
  20955. (if (< (line-end-position) beg) t
  20956. (when (derived-mode-p 'message-mode)
  20957. ;; In `message-mode', do not fill following citation
  20958. ;; in current paragraph nor text before message body.
  20959. (let ((body-start (save-excursion (message-goto-body))))
  20960. (when body-start (setq beg (max body-start beg))))
  20961. (when (save-excursion
  20962. (re-search-forward
  20963. (concat "^" message-cite-prefix-regexp) end t))
  20964. (setq end (match-beginning 0))))
  20965. ;; Fill paragraph, taking line breaks into account.
  20966. (save-excursion
  20967. (goto-char beg)
  20968. (let ((cuts (list beg)))
  20969. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  20970. (when (eq 'line-break
  20971. (org-element-type
  20972. (save-excursion (backward-char)
  20973. (org-element-context))))
  20974. (push (point) cuts)))
  20975. (dolist (c (delq end cuts))
  20976. (fill-region-as-paragraph c end justify)
  20977. (setq end c))))
  20978. t)))
  20979. ;; Contents of `comment-block' type elements should be
  20980. ;; filled as plain text, but only if point is within block
  20981. ;; markers.
  20982. (comment-block
  20983. (let* ((case-fold-search t)
  20984. (beg (save-excursion
  20985. (goto-char (org-element-property :begin element))
  20986. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  20987. (forward-line)
  20988. (point)))
  20989. (end (save-excursion
  20990. (goto-char (org-element-property :end element))
  20991. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  20992. (line-beginning-position))))
  20993. (if (or (< (point) beg) (> (point) end)) t
  20994. (fill-region-as-paragraph
  20995. (save-excursion (end-of-line)
  20996. (re-search-backward "^[ \t]*$" beg 'move)
  20997. (line-beginning-position))
  20998. (save-excursion (beginning-of-line)
  20999. (re-search-forward "^[ \t]*$" end 'move)
  21000. (line-beginning-position))
  21001. justify))))
  21002. ;; Fill comments.
  21003. (comment
  21004. (let ((begin (org-element-property :post-affiliated element))
  21005. (end (org-element-property :end element)))
  21006. (when (and (>= (point) begin) (<= (point) end))
  21007. (let ((begin (save-excursion
  21008. (end-of-line)
  21009. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21010. (progn (forward-line) (point))
  21011. begin)))
  21012. (end (save-excursion
  21013. (end-of-line)
  21014. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21015. (1- (line-beginning-position))
  21016. (skip-chars-backward " \r\t\n")
  21017. (line-end-position)))))
  21018. ;; Do not fill comments when at a blank line.
  21019. (when (> end begin)
  21020. (let ((fill-prefix
  21021. (save-excursion
  21022. (beginning-of-line)
  21023. (looking-at "[ \t]*#")
  21024. (let ((comment-prefix (match-string 0)))
  21025. (goto-char (match-end 0))
  21026. (if (looking-at adaptive-fill-regexp)
  21027. (concat comment-prefix (match-string 0))
  21028. (concat comment-prefix " "))))))
  21029. (save-excursion
  21030. (fill-region-as-paragraph begin end justify))))))
  21031. t))
  21032. ;; Ignore every other element.
  21033. (otherwise t)))))
  21034. (defun org-fill-paragraph (&optional justify region)
  21035. "Fill element at point, when applicable.
  21036. This function only applies to comment blocks, comments, example
  21037. blocks and paragraphs. Also, as a special case, re-align table
  21038. when point is at one.
  21039. For convenience, when point is at a plain list, an item or
  21040. a footnote definition, try to fill the first paragraph within.
  21041. If JUSTIFY is non-nil (interactively, with prefix argument),
  21042. justify as well. If `sentence-end-double-space' is non-nil, then
  21043. period followed by one space does not end a sentence, so don't
  21044. break a line there. The variable `fill-column' controls the
  21045. width for filling.
  21046. The REGION argument is non-nil if called interactively; in that
  21047. case, if Transient Mark mode is enabled and the mark is active,
  21048. fill each of the elements in the active region, instead of just
  21049. filling the current element."
  21050. (interactive (progn
  21051. (barf-if-buffer-read-only)
  21052. (list (if current-prefix-arg 'full) t)))
  21053. (cond
  21054. ((and (derived-mode-p 'message-mode)
  21055. (or (not (message-in-body-p))
  21056. (save-excursion (move-beginning-of-line 1)
  21057. (looking-at message-cite-prefix-regexp))))
  21058. ;; First ensure filling is correct in message-mode.
  21059. (let ((fill-paragraph-function
  21060. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21061. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21062. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21063. (paragraph-separate
  21064. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21065. (fill-paragraph nil)))
  21066. ((and region transient-mark-mode mark-active
  21067. (not (eq (region-beginning) (region-end))))
  21068. (let ((origin (point-marker))
  21069. (start (region-beginning)))
  21070. (unwind-protect
  21071. (progn
  21072. (goto-char (region-end))
  21073. (while (> (point) start)
  21074. (org-backward-paragraph)
  21075. (org-fill-element justify)))
  21076. (goto-char origin)
  21077. (set-marker origin nil))))
  21078. (t (org-fill-element justify))))
  21079. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  21080. (defun org-auto-fill-function ()
  21081. "Auto-fill function."
  21082. ;; Check if auto-filling is meaningful.
  21083. (let ((fc (current-fill-column)))
  21084. (when (and fc (> (current-column) fc))
  21085. (let* ((fill-prefix (org-adaptive-fill-function))
  21086. ;; Enforce empty fill prefix, if required. Otherwise, it
  21087. ;; will be computed again.
  21088. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21089. (when fill-prefix (do-auto-fill))))))
  21090. (defun org-comment-line-break-function (&optional soft)
  21091. "Break line at point and indent, continuing comment if within one.
  21092. The inserted newline is marked hard if variable
  21093. `use-hard-newlines' is true, unless optional argument SOFT is
  21094. non-nil."
  21095. (if soft (insert-and-inherit ?\n) (newline 1))
  21096. (save-excursion (forward-char -1) (delete-horizontal-space))
  21097. (delete-horizontal-space)
  21098. (indent-to-left-margin)
  21099. (insert-before-markers-and-inherit fill-prefix))
  21100. ;;; Fixed Width Areas
  21101. (defun org-toggle-fixed-width ()
  21102. "Toggle fixed-width markup.
  21103. Add or remove fixed-width markup on current line, whenever it
  21104. makes sense. Return an error otherwise.
  21105. If a region is active and if it contains only fixed-width areas
  21106. or blank lines, remove all fixed-width markup in it. If the
  21107. region contains anything else, convert all non-fixed-width lines
  21108. to fixed-width ones.
  21109. Blank lines at the end of the region are ignored unless the
  21110. region only contains such lines."
  21111. (interactive)
  21112. (if (not (org-region-active-p))
  21113. ;; No region:
  21114. ;;
  21115. ;; Remove fixed width marker only in a fixed-with element.
  21116. ;;
  21117. ;; Add fixed width maker in paragraphs, in blank lines after
  21118. ;; elements or at the beginning of a headline or an inlinetask,
  21119. ;; and before any one-line elements (e.g., a clock).
  21120. (progn
  21121. (beginning-of-line)
  21122. (let* ((element (org-element-at-point))
  21123. (type (org-element-type element)))
  21124. (cond
  21125. ((and (eq type 'fixed-width)
  21126. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21127. (replace-match
  21128. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21129. ((and (memq type '(babel-call clock comment diary-sexp headline
  21130. horizontal-rule keyword paragraph
  21131. planning))
  21132. (<= (org-element-property :post-affiliated element) (point)))
  21133. (skip-chars-forward " \t")
  21134. (insert ": "))
  21135. ((and (looking-at-p "[ \t]*$")
  21136. (or (eq type 'inlinetask)
  21137. (save-excursion
  21138. (skip-chars-forward " \r\t\n")
  21139. (<= (org-element-property :end element) (point)))))
  21140. (delete-region (point) (line-end-position))
  21141. (org-indent-line)
  21142. (insert ": "))
  21143. (t (user-error "Cannot insert a fixed-width line here")))))
  21144. ;; Region active.
  21145. (let* ((begin (save-excursion
  21146. (goto-char (region-beginning))
  21147. (line-beginning-position)))
  21148. (end (copy-marker
  21149. (save-excursion
  21150. (goto-char (region-end))
  21151. (unless (eolp) (beginning-of-line))
  21152. (if (save-excursion (re-search-backward "\\S-" begin t))
  21153. (progn (skip-chars-backward " \r\t\n") (point))
  21154. (point)))))
  21155. (all-fixed-width-p
  21156. (catch 'not-all-p
  21157. (save-excursion
  21158. (goto-char begin)
  21159. (skip-chars-forward " \r\t\n")
  21160. (when (eobp) (throw 'not-all-p nil))
  21161. (while (< (point) end)
  21162. (let ((element (org-element-at-point)))
  21163. (if (eq (org-element-type element) 'fixed-width)
  21164. (goto-char (org-element-property :end element))
  21165. (throw 'not-all-p nil))))
  21166. t))))
  21167. (if all-fixed-width-p
  21168. (save-excursion
  21169. (goto-char begin)
  21170. (while (< (point) end)
  21171. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21172. (replace-match
  21173. "" nil nil nil
  21174. (if (= (line-end-position) (match-end 0)) 0 1)))
  21175. (forward-line)))
  21176. (let ((min-ind (point-max)))
  21177. ;; Find minimum indentation across all lines.
  21178. (save-excursion
  21179. (goto-char begin)
  21180. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21181. (setq min-ind 0)
  21182. (catch 'zerop
  21183. (while (< (point) end)
  21184. (unless (looking-at-p "[ \t]*$")
  21185. (let ((ind (org-get-indentation)))
  21186. (setq min-ind (min min-ind ind))
  21187. (when (zerop ind) (throw 'zerop t))))
  21188. (forward-line)))))
  21189. ;; Loop over all lines and add fixed-width markup everywhere
  21190. ;; but in fixed-width lines.
  21191. (save-excursion
  21192. (goto-char begin)
  21193. (while (< (point) end)
  21194. (cond
  21195. ((org-at-heading-p)
  21196. (insert ": ")
  21197. (forward-line)
  21198. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21199. (insert ":")
  21200. (forward-line)))
  21201. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21202. (let* ((element (org-element-at-point))
  21203. (element-end (org-element-property :end element)))
  21204. (if (eq (org-element-type element) 'fixed-width)
  21205. (progn (goto-char element-end)
  21206. (skip-chars-backward " \r\t\n")
  21207. (forward-line))
  21208. (let ((limit (min end element-end)))
  21209. (while (< (point) limit)
  21210. (org-move-to-column min-ind t)
  21211. (insert ": ")
  21212. (forward-line))))))
  21213. (t
  21214. (org-move-to-column min-ind t)
  21215. (insert ": ")
  21216. (forward-line)))))))
  21217. (set-marker end nil))))
  21218. ;;; Comments
  21219. ;; Org comments syntax is quite complex. It requires the entire line
  21220. ;; to be just a comment. Also, even with the right syntax at the
  21221. ;; beginning of line, some elements (e.g., verse-block or
  21222. ;; example-block) don't accept comments. Usual Emacs comment commands
  21223. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21224. ;; Org still relies on `comment-dwim', but cannot trust
  21225. ;; `comment-only-p'. So, `comment-region-function' and
  21226. ;; `uncomment-region-function' both point
  21227. ;; to`org-comment-or-uncomment-region'. Eventually,
  21228. ;; `org-insert-comment' takes care of insertion of comments at the
  21229. ;; beginning of line.
  21230. ;; `org-setup-comments-handling' install comments related variables
  21231. ;; during `org-mode' initialization.
  21232. (defun org-setup-comments-handling ()
  21233. (interactive)
  21234. (setq-local comment-use-syntax nil)
  21235. (setq-local comment-start "# ")
  21236. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21237. (setq-local comment-insert-comment-function 'org-insert-comment)
  21238. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21239. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21240. (defun org-insert-comment ()
  21241. "Insert an empty comment above current line.
  21242. If the line is empty, insert comment at its beginning. When
  21243. point is within a source block, comment according to the related
  21244. major mode."
  21245. (if (let ((element (org-element-at-point)))
  21246. (and (eq (org-element-type element) 'src-block)
  21247. (< (save-excursion
  21248. (goto-char (org-element-property :post-affiliated element))
  21249. (line-end-position))
  21250. (point))
  21251. (> (save-excursion
  21252. (goto-char (org-element-property :end element))
  21253. (skip-chars-backward " \r\t\n")
  21254. (line-beginning-position))
  21255. (point))))
  21256. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21257. (beginning-of-line)
  21258. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21259. (open-line 1))
  21260. (org-indent-line)
  21261. (insert "# ")))
  21262. (defvar comment-empty-lines) ; From newcomment.el.
  21263. (defun org-comment-or-uncomment-region (beg end &rest _)
  21264. "Comment or uncomment each non-blank line in the region.
  21265. Uncomment each non-blank line between BEG and END if it only
  21266. contains commented lines. Otherwise, comment them. If region is
  21267. strictly within a source block, use appropriate comment syntax."
  21268. (if (let ((element (org-element-at-point)))
  21269. (and (eq (org-element-type element) 'src-block)
  21270. (< (save-excursion
  21271. (goto-char (org-element-property :post-affiliated element))
  21272. (line-end-position))
  21273. beg)
  21274. (>= (save-excursion
  21275. (goto-char (org-element-property :end element))
  21276. (skip-chars-backward " \r\t\n")
  21277. (line-beginning-position))
  21278. end)))
  21279. ;; Translate region boundaries for the Org buffer to the source
  21280. ;; buffer.
  21281. (let ((offset (- end beg)))
  21282. (save-excursion
  21283. (goto-char beg)
  21284. (org-babel-do-in-edit-buffer
  21285. (comment-or-uncomment-region (point) (+ offset (point))))))
  21286. (save-restriction
  21287. ;; Restrict region
  21288. (narrow-to-region (save-excursion (goto-char beg)
  21289. (skip-chars-forward " \r\t\n" end)
  21290. (line-beginning-position))
  21291. (save-excursion (goto-char end)
  21292. (skip-chars-backward " \r\t\n" beg)
  21293. (line-end-position)))
  21294. (let ((uncommentp
  21295. ;; UNCOMMENTP is non-nil when every non blank line between
  21296. ;; BEG and END is a comment.
  21297. (save-excursion
  21298. (goto-char (point-min))
  21299. (while (and (not (eobp))
  21300. (let ((element (org-element-at-point)))
  21301. (and (eq (org-element-type element) 'comment)
  21302. (goto-char (min (point-max)
  21303. (org-element-property
  21304. :end element)))))))
  21305. (eobp))))
  21306. (if uncommentp
  21307. ;; Only blank lines and comments in region: uncomment it.
  21308. (save-excursion
  21309. (goto-char (point-min))
  21310. (while (not (eobp))
  21311. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21312. (replace-match "" nil nil nil 1))
  21313. (forward-line)))
  21314. ;; Comment each line in region.
  21315. (let ((min-indent (point-max)))
  21316. ;; First find the minimum indentation across all lines.
  21317. (save-excursion
  21318. (goto-char (point-min))
  21319. (while (and (not (eobp)) (not (zerop min-indent)))
  21320. (unless (looking-at "[ \t]*$")
  21321. (setq min-indent (min min-indent (current-indentation))))
  21322. (forward-line)))
  21323. ;; Then loop over all lines.
  21324. (save-excursion
  21325. (goto-char (point-min))
  21326. (while (not (eobp))
  21327. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21328. ;; Don't get fooled by invisible text (e.g. link path)
  21329. ;; when moving to column MIN-INDENT.
  21330. (let ((buffer-invisibility-spec nil))
  21331. (org-move-to-column min-indent t))
  21332. (insert comment-start))
  21333. (forward-line)))))))))
  21334. (defun org-comment-dwim (_arg)
  21335. "Call `comment-dwim' within a source edit buffer if needed."
  21336. (interactive "*P")
  21337. (if (org-in-src-block-p)
  21338. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21339. (call-interactively 'comment-dwim)))
  21340. ;;; Timestamps API
  21341. ;; This section contains tools to operate on timestamp objects, as
  21342. ;; returned by, e.g. `org-element-context'.
  21343. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21344. "Encode TIMESTAMP object into Emacs internal time.
  21345. Use end of date range or time range when END is non-nil."
  21346. (apply #'encode-time
  21347. (cons 0
  21348. (mapcar
  21349. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21350. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21351. '(:minute-start :hour-start :day-start :month-start
  21352. :year-start))))))
  21353. (defun org-timestamp-has-time-p (timestamp)
  21354. "Non-nil when TIMESTAMP has a time specified."
  21355. (org-element-property :hour-start timestamp))
  21356. (defun org-timestamp-format (timestamp format &optional end utc)
  21357. "Format a TIMESTAMP object into a string.
  21358. FORMAT is a format specifier to be passed to
  21359. `format-time-string'.
  21360. When optional argument END is non-nil, use end of date-range or
  21361. time-range, if possible.
  21362. When optional argument UTC is non-nil, time will be expressed as
  21363. Universal Time."
  21364. (format-time-string
  21365. format (org-timestamp--to-internal-time timestamp end)
  21366. (and utc t)))
  21367. (defun org-timestamp-split-range (timestamp &optional end)
  21368. "Extract a TIMESTAMP object from a date or time range.
  21369. END, when non-nil, means extract the end of the range.
  21370. Otherwise, extract its start.
  21371. Return a new timestamp object."
  21372. (let ((type (org-element-property :type timestamp)))
  21373. (if (memq type '(active inactive diary)) timestamp
  21374. (let ((split-ts (org-element-copy timestamp)))
  21375. ;; Set new type.
  21376. (org-element-put-property
  21377. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21378. ;; Copy start properties over end properties if END is
  21379. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21380. (let ((p-alist '((:minute-start . :minute-end)
  21381. (:hour-start . :hour-end)
  21382. (:day-start . :day-end)
  21383. (:month-start . :month-end)
  21384. (:year-start . :year-end))))
  21385. (dolist (p-cell p-alist)
  21386. (org-element-put-property
  21387. split-ts
  21388. (funcall (if end #'car #'cdr) p-cell)
  21389. (org-element-property
  21390. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21391. ;; Eventually refresh `:raw-value'.
  21392. (org-element-put-property split-ts :raw-value nil)
  21393. (org-element-put-property
  21394. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21395. (defun org-timestamp-translate (timestamp &optional boundary)
  21396. "Translate TIMESTAMP object to custom format.
  21397. Format string is defined in `org-time-stamp-custom-formats',
  21398. which see.
  21399. When optional argument BOUNDARY is non-nil, it is either the
  21400. symbol `start' or `end'. In this case, only translate the
  21401. starting or ending part of TIMESTAMP if it is a date or time
  21402. range. Otherwise, translate both parts.
  21403. Return timestamp as-is if `org-display-custom-times' is nil or if
  21404. it has a `diary' type."
  21405. (let ((type (org-element-property :type timestamp)))
  21406. (if (or (not org-display-custom-times) (eq type 'diary))
  21407. (org-element-interpret-data timestamp)
  21408. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21409. org-time-stamp-custom-formats)))
  21410. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21411. (concat (org-timestamp-format timestamp fmt)
  21412. "--"
  21413. (org-timestamp-format timestamp fmt t))
  21414. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21415. ;;; Other stuff.
  21416. (defvar reftex-docstruct-symbol)
  21417. (defvar org--rds)
  21418. (defun org-reftex-citation ()
  21419. "Use reftex-citation to insert a citation into the buffer.
  21420. This looks for a line like
  21421. #+BIBLIOGRAPHY: foo plain option:-d
  21422. and derives from it that foo.bib is the bibliography file relevant
  21423. for this document. It then installs the necessary environment for RefTeX
  21424. to work in this buffer and calls `reftex-citation' to insert a citation
  21425. into the buffer.
  21426. Export of such citations to both LaTeX and HTML is handled by the contributed
  21427. package ox-bibtex by Taru Karttunen."
  21428. (interactive)
  21429. (let ((reftex-docstruct-symbol 'org--rds)
  21430. org--rds bib)
  21431. (org-with-wide-buffer
  21432. (let ((case-fold-search t)
  21433. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21434. (if (not (save-excursion
  21435. (or (re-search-forward re nil t)
  21436. (re-search-backward re nil t))))
  21437. (user-error "No bibliography defined in file")
  21438. (setq bib (concat (match-string 1) ".bib")
  21439. org--rds (list (list 'bib bib))))))
  21440. (call-interactively 'reftex-citation)))
  21441. ;;;; Functions extending outline functionality
  21442. (defun org-beginning-of-line (&optional n)
  21443. "Go to the beginning of the current visible line.
  21444. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21445. tags on the first attempt, and only move to after the tags when
  21446. the cursor is already beyond the end of the headline.
  21447. With argument N not nil or 1, move forward N - 1 lines first."
  21448. (interactive "^p")
  21449. (let ((origin (point))
  21450. (special (pcase org-special-ctrl-a/e
  21451. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21452. deactivate-mark)
  21453. ;; First move to a visible line.
  21454. (if (bound-and-true-p visual-line-mode)
  21455. (beginning-of-visual-line n)
  21456. (move-beginning-of-line n)
  21457. ;; `move-beginning-of-line' may leave point after invisible
  21458. ;; characters if line starts with such of these (e.g., with
  21459. ;; a link at column 0). Really move to the beginning of the
  21460. ;; current visible line.
  21461. (beginning-of-line))
  21462. (cond
  21463. ;; No special behavior. Point is already at the beginning of
  21464. ;; a line, logical or visual.
  21465. ((not special))
  21466. ;; `beginning-of-visual-line' left point before logical beginning
  21467. ;; of line: point is at the beginning of a visual line. Bail
  21468. ;; out.
  21469. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21470. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21471. ;; At a headline, special position is before the title, but
  21472. ;; after any TODO keyword or priority cookie.
  21473. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21474. (line-end-position)))
  21475. (bol (point)))
  21476. (if (eq special 'reversed)
  21477. (when (and (= origin bol) (eq last-command this-command))
  21478. (goto-char refpos))
  21479. (when (or (> origin refpos) (= origin bol))
  21480. (goto-char refpos)))))
  21481. ((and (looking-at org-list-full-item-re)
  21482. (memq (org-element-type (save-match-data (org-element-at-point)))
  21483. '(item plain-list)))
  21484. ;; Set special position at first white space character after
  21485. ;; bullet, and check-box, if any.
  21486. (let ((after-bullet
  21487. (let ((box (match-end 3)))
  21488. (cond ((not box) (match-end 1))
  21489. ((eq (char-after box) ?\s) (1+ box))
  21490. (t box)))))
  21491. (if (eq special 'reversed)
  21492. (when (and (= (point) origin) (eq last-command this-command))
  21493. (goto-char after-bullet))
  21494. (when (or (> origin after-bullet) (= (point) origin))
  21495. (goto-char after-bullet)))))
  21496. ;; No special context. Point is already at beginning of line.
  21497. (t nil))))
  21498. (defun org-end-of-line (&optional n)
  21499. "Go to the end of the line, but before ellipsis, if any.
  21500. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21501. tags on the first attempt, and only move to after the tags when
  21502. the cursor is already beyond the end of the headline.
  21503. With argument N not nil or 1, move forward N - 1 lines first."
  21504. (interactive "^p")
  21505. (let ((origin (point))
  21506. (special (pcase org-special-ctrl-a/e
  21507. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21508. deactivate-mark)
  21509. ;; First move to a visible line.
  21510. (if (bound-and-true-p visual-line-mode)
  21511. (beginning-of-visual-line n)
  21512. (move-beginning-of-line n))
  21513. (cond
  21514. ;; At a headline, with tags.
  21515. ((and special
  21516. (save-excursion
  21517. (beginning-of-line)
  21518. (let ((case-fold-search nil))
  21519. (looking-at org-complex-heading-regexp)))
  21520. (match-end 5))
  21521. (let ((tags (save-excursion
  21522. (goto-char (match-beginning 5))
  21523. (skip-chars-backward " \t")
  21524. (point)))
  21525. (visual-end (and (bound-and-true-p visual-line-mode)
  21526. (save-excursion
  21527. (end-of-visual-line)
  21528. (point)))))
  21529. ;; If `end-of-visual-line' brings us before end of line or
  21530. ;; even tags, i.e., the headline spans over multiple visual
  21531. ;; lines, move there.
  21532. (cond ((and visual-end
  21533. (< visual-end tags)
  21534. (<= origin visual-end))
  21535. (goto-char visual-end))
  21536. ((eq special 'reversed)
  21537. (if (and (= origin (line-end-position))
  21538. (eq this-command last-command))
  21539. (goto-char tags)
  21540. (end-of-line)))
  21541. (t
  21542. (if (or (< origin tags) (= origin (line-end-position)))
  21543. (goto-char tags)
  21544. (end-of-line))))))
  21545. ((bound-and-true-p visual-line-mode)
  21546. (let ((bol (line-beginning-position)))
  21547. (end-of-visual-line)
  21548. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21549. ;; end of a line, backtrack and use `end-of-line' instead.
  21550. (when (/= bol (line-beginning-position))
  21551. (goto-char bol)
  21552. (end-of-line))))
  21553. (t (end-of-line)))))
  21554. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21555. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21556. (defun org-backward-sentence (&optional _arg)
  21557. "Go to beginning of sentence, or beginning of table field.
  21558. This will call `backward-sentence' or `org-table-beginning-of-field',
  21559. depending on context."
  21560. (interactive)
  21561. (let* ((element (org-element-at-point))
  21562. (contents-begin (org-element-property :contents-begin element))
  21563. (table (org-element-lineage element '(table) t)))
  21564. (if (and table
  21565. (> (point) contents-begin)
  21566. (<= (point) (org-element-property :contents-end table)))
  21567. (call-interactively #'org-table-beginning-of-field)
  21568. (save-restriction
  21569. (when (and contents-begin
  21570. (< (point-min) contents-begin)
  21571. (> (point) contents-begin))
  21572. (narrow-to-region contents-begin
  21573. (org-element-property :contents-end element)))
  21574. (call-interactively #'backward-sentence)))))
  21575. (defun org-forward-sentence (&optional _arg)
  21576. "Go to end of sentence, or end of table field.
  21577. This will call `forward-sentence' or `org-table-end-of-field',
  21578. depending on context."
  21579. (interactive)
  21580. (if (and (org-at-heading-p)
  21581. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  21582. (save-restriction
  21583. (narrow-to-region (line-beginning-position) (line-end-position))
  21584. (call-interactively #'forward-sentence))
  21585. (let* ((element (org-element-at-point))
  21586. (contents-end (org-element-property :contents-end element))
  21587. (table (org-element-lineage element '(table) t)))
  21588. (if (and table
  21589. (>= (point) (org-element-property :contents-begin table))
  21590. (< (point) contents-end))
  21591. (call-interactively #'org-table-end-of-field)
  21592. (save-restriction
  21593. (when (and contents-end
  21594. (> (point-max) contents-end)
  21595. ;; Skip blank lines between elements.
  21596. (< (org-element-property :end element)
  21597. (save-excursion (goto-char contents-end)
  21598. (skip-chars-forward " \r\t\n"))))
  21599. (narrow-to-region (org-element-property :contents-begin element)
  21600. contents-end))
  21601. (call-interactively #'forward-sentence))))))
  21602. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21603. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21604. (defun org-kill-line (&optional _arg)
  21605. "Kill line, to tags or end of line."
  21606. (interactive)
  21607. (cond
  21608. ((or (not org-special-ctrl-k)
  21609. (bolp)
  21610. (not (org-at-heading-p)))
  21611. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21612. org-ctrl-k-protect-subtree
  21613. (or (eq org-ctrl-k-protect-subtree 'error)
  21614. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21615. (user-error "C-k aborted as it would kill a hidden subtree"))
  21616. (call-interactively
  21617. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21618. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21619. (kill-region (point) (match-beginning 1))
  21620. (org-set-tags nil t))
  21621. (t (kill-region (point) (point-at-eol)))))
  21622. (define-key org-mode-map "\C-k" 'org-kill-line)
  21623. (defun org-yank (&optional arg)
  21624. "Yank. If the kill is a subtree, treat it specially.
  21625. This command will look at the current kill and check if is a single
  21626. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21627. cursor is at the beginning of a line or after the stars of a currently
  21628. empty headline, then the yank is handled specially. How exactly depends
  21629. on the value of the following variables.
  21630. `org-yank-folded-subtrees'
  21631. By default, this variable is non-nil, which results in
  21632. subtree(s) being folded after insertion, except if doing so
  21633. would swallow text after the yanked text.
  21634. `org-yank-adjusted-subtrees'
  21635. When non-nil (the default value is nil), the subtree will be
  21636. promoted or demoted in order to fit into the local outline tree
  21637. structure, which means that the level will be adjusted so that it
  21638. becomes the smaller one of the two *visible* surrounding headings.
  21639. Any prefix to this command will cause `yank' to be called directly with
  21640. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21641. will just
  21642. plainly yank the text as it is.
  21643. \[1] The test checks if the first non-white line is a heading
  21644. and if there are no other headings with fewer stars."
  21645. (interactive "P")
  21646. (org-yank-generic 'yank arg))
  21647. (defun org-yank-generic (command arg)
  21648. "Perform some yank-like command.
  21649. This function implements the behavior described in the `org-yank'
  21650. documentation. However, it has been generalized to work for any
  21651. interactive command with similar behavior."
  21652. ;; pretend to be command COMMAND
  21653. (setq this-command command)
  21654. (if arg
  21655. (call-interactively command)
  21656. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21657. (and (org-kill-is-subtree-p)
  21658. (or (bolp)
  21659. (and (looking-at "[ \t]*$")
  21660. (string-match
  21661. "\\`\\*+\\'"
  21662. (buffer-substring (point-at-bol) (point)))))))
  21663. swallowp)
  21664. (cond
  21665. ((and subtreep org-yank-folded-subtrees)
  21666. (let ((beg (point))
  21667. end)
  21668. (if (and subtreep org-yank-adjusted-subtrees)
  21669. (org-paste-subtree nil nil 'for-yank)
  21670. (call-interactively command))
  21671. (setq end (point))
  21672. (goto-char beg)
  21673. (when (and (bolp) subtreep
  21674. (not (setq swallowp
  21675. (org-yank-folding-would-swallow-text beg end))))
  21676. (org-with-limited-levels
  21677. (or (looking-at org-outline-regexp)
  21678. (re-search-forward org-outline-regexp-bol end t))
  21679. (while (and (< (point) end) (looking-at org-outline-regexp))
  21680. (outline-hide-subtree)
  21681. (org-cycle-show-empty-lines 'folded)
  21682. (condition-case nil
  21683. (outline-forward-same-level 1)
  21684. (error (goto-char end))))))
  21685. (when swallowp
  21686. (message
  21687. "Inserted text not folded because that would swallow text"))
  21688. (goto-char end)
  21689. (skip-chars-forward " \t\n\r")
  21690. (beginning-of-line 1)
  21691. (push-mark beg 'nomsg)))
  21692. ((and subtreep org-yank-adjusted-subtrees)
  21693. (let ((beg (point-at-bol)))
  21694. (org-paste-subtree nil nil 'for-yank)
  21695. (push-mark beg 'nomsg)))
  21696. (t
  21697. (call-interactively command))))))
  21698. (defun org-yank-folding-would-swallow-text (beg end)
  21699. "Would hide-subtree at BEG swallow any text after END?"
  21700. (let (level)
  21701. (org-with-limited-levels
  21702. (save-excursion
  21703. (goto-char beg)
  21704. (when (or (looking-at org-outline-regexp)
  21705. (re-search-forward org-outline-regexp-bol end t))
  21706. (setq level (org-outline-level)))
  21707. (goto-char end)
  21708. (skip-chars-forward " \t\r\n\v\f")
  21709. (not (or (eobp)
  21710. (and (bolp) (looking-at-p org-outline-regexp)
  21711. (<= (org-outline-level) level))))))))
  21712. (define-key org-mode-map "\C-y" 'org-yank)
  21713. (defun org-truely-invisible-p ()
  21714. "Check if point is at a character currently not visible.
  21715. This version does not only check the character property, but also
  21716. `visible-mode'."
  21717. (unless (bound-and-true-p visible-mode)
  21718. (org-invisible-p)))
  21719. (defun org-invisible-p2 ()
  21720. "Check if point is at a character currently not visible.
  21721. If the point is at EOL (and not at the beginning of a buffer too),
  21722. move it back by one char before doing this check."
  21723. (save-excursion
  21724. (when (and (eolp) (not (bobp)))
  21725. (backward-char 1))
  21726. (org-invisible-p)))
  21727. (defun org-back-to-heading (&optional invisible-ok)
  21728. "Call `outline-back-to-heading', but provide a better error message."
  21729. (condition-case nil
  21730. (outline-back-to-heading invisible-ok)
  21731. (error (error "Before first headline at position %d in buffer %s"
  21732. (point) (current-buffer)))))
  21733. (defun org-before-first-heading-p ()
  21734. "Before first heading?"
  21735. (save-excursion
  21736. (end-of-line)
  21737. (null (re-search-backward org-outline-regexp-bol nil t))))
  21738. (defun org-at-heading-p (&optional ignored)
  21739. (outline-on-heading-p t))
  21740. (defun org-in-commented-heading-p (&optional no-inheritance)
  21741. "Non-nil if point is under a commented heading.
  21742. This function also checks ancestors of the current headline,
  21743. unless optional argument NO-INHERITANCE is non-nil."
  21744. (cond
  21745. ((org-before-first-heading-p) nil)
  21746. ((let ((headline (nth 4 (org-heading-components))))
  21747. (and headline
  21748. (let ((case-fold-search nil))
  21749. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21750. headline)))))
  21751. (no-inheritance nil)
  21752. (t
  21753. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21754. (defun org-at-comment-p nil
  21755. "Is cursor in a commented line?"
  21756. (save-excursion
  21757. (save-match-data
  21758. (beginning-of-line)
  21759. (looking-at "^[ \t]*# "))))
  21760. (defun org-at-drawer-p nil
  21761. "Is cursor at a drawer keyword?"
  21762. (save-excursion
  21763. (move-beginning-of-line 1)
  21764. (looking-at org-drawer-regexp)))
  21765. (defun org-at-block-p nil
  21766. "Is cursor at a block keyword?"
  21767. (save-excursion
  21768. (move-beginning-of-line 1)
  21769. (looking-at org-block-regexp)))
  21770. (defun org-point-at-end-of-empty-headline ()
  21771. "If point is at the end of an empty headline, return t, else nil.
  21772. If the heading only contains a TODO keyword, it is still still considered
  21773. empty."
  21774. (let ((case-fold-search nil))
  21775. (and (looking-at "[ \t]*$")
  21776. org-todo-line-regexp
  21777. (save-excursion
  21778. (beginning-of-line)
  21779. (looking-at org-todo-line-regexp)
  21780. (string= (match-string 3) "")))))
  21781. (defun org-at-heading-or-item-p ()
  21782. (or (org-at-heading-p) (org-at-item-p)))
  21783. (defun org-at-target-p ()
  21784. (or (org-in-regexp org-radio-target-regexp)
  21785. (org-in-regexp org-target-regexp)))
  21786. ;; Compatibility alias with Org versions < 7.8.03
  21787. (defalias 'org-on-target-p 'org-at-target-p)
  21788. (defun org-up-heading-all (arg)
  21789. "Move to the heading line of which the present line is a subheading.
  21790. This function considers both visible and invisible heading lines.
  21791. With argument, move up ARG levels."
  21792. (outline-up-heading arg t))
  21793. (defun org-up-heading-safe ()
  21794. "Move to the heading line of which the present line is a subheading.
  21795. This version will not throw an error. It will return the level of the
  21796. headline found, or nil if no higher level is found.
  21797. Also, this function will be a lot faster than `outline-up-heading',
  21798. because it relies on stars being the outline starters. This can really
  21799. make a significant difference in outlines with very many siblings."
  21800. (when (ignore-errors (org-back-to-heading t))
  21801. (let ((level-up (1- (funcall outline-level))))
  21802. (and (> level-up 0)
  21803. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21804. (funcall outline-level)))))
  21805. (defun org-first-sibling-p ()
  21806. "Is this heading the first child of its parents?"
  21807. (interactive)
  21808. (let ((re org-outline-regexp-bol)
  21809. level l)
  21810. (unless (org-at-heading-p t)
  21811. (user-error "Not at a heading"))
  21812. (setq level (funcall outline-level))
  21813. (save-excursion
  21814. (if (not (re-search-backward re nil t))
  21815. t
  21816. (setq l (funcall outline-level))
  21817. (< l level)))))
  21818. (defun org-goto-sibling (&optional previous)
  21819. "Goto the next sibling, even if it is invisible.
  21820. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21821. when a sibling was found. When none is found, return nil and don't
  21822. move point."
  21823. (let ((fun (if previous 're-search-backward 're-search-forward))
  21824. (pos (point))
  21825. (re org-outline-regexp-bol)
  21826. level l)
  21827. (when (ignore-errors (org-back-to-heading t))
  21828. (setq level (funcall outline-level))
  21829. (catch 'exit
  21830. (or previous (forward-char 1))
  21831. (while (funcall fun re nil t)
  21832. (setq l (funcall outline-level))
  21833. (when (< l level) (goto-char pos) (throw 'exit nil))
  21834. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21835. (goto-char pos)
  21836. nil))))
  21837. (defun org-show-siblings ()
  21838. "Show all siblings of the current headline."
  21839. (save-excursion
  21840. (while (org-goto-sibling) (org-flag-heading nil)))
  21841. (save-excursion
  21842. (while (org-goto-sibling 'previous)
  21843. (org-flag-heading nil))))
  21844. (defun org-goto-first-child ()
  21845. "Goto the first child, even if it is invisible.
  21846. Return t when a child was found. Otherwise don't move point and
  21847. return nil."
  21848. (let (level (pos (point)) (re org-outline-regexp-bol))
  21849. (when (ignore-errors (org-back-to-heading t))
  21850. (setq level (outline-level))
  21851. (forward-char 1)
  21852. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21853. (progn (goto-char (match-beginning 0)) t)
  21854. (goto-char pos) nil))))
  21855. (defun org-show-hidden-entry ()
  21856. "Show an entry where even the heading is hidden."
  21857. (save-excursion
  21858. (org-show-entry)))
  21859. (defun org-flag-heading (flag &optional entry)
  21860. "Flag the current heading. FLAG non-nil means make invisible.
  21861. When ENTRY is non-nil, show the entire entry."
  21862. (save-excursion
  21863. (org-back-to-heading t)
  21864. ;; Check if we should show the entire entry
  21865. (if entry
  21866. (progn
  21867. (org-show-entry)
  21868. (save-excursion
  21869. (and (outline-next-heading)
  21870. (org-flag-heading nil))))
  21871. (outline-flag-region (max (point-min) (1- (point)))
  21872. (save-excursion (outline-end-of-heading) (point))
  21873. flag))))
  21874. (defun org-get-next-sibling ()
  21875. "Move to next heading of the same level, and return point.
  21876. If there is no such heading, return nil.
  21877. This is like outline-next-sibling, but invisible headings are ok."
  21878. (let ((level (funcall outline-level)))
  21879. (outline-next-heading)
  21880. (while (and (not (eobp)) (> (funcall outline-level) level))
  21881. (outline-next-heading))
  21882. (unless (or (eobp) (< (funcall outline-level) level))
  21883. (point))))
  21884. (defun org-get-last-sibling ()
  21885. "Move to previous heading of the same level, and return point.
  21886. If there is no such heading, return nil."
  21887. (let ((opoint (point))
  21888. (level (funcall outline-level)))
  21889. (outline-previous-heading)
  21890. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21891. (while (and (> (funcall outline-level) level)
  21892. (not (bobp)))
  21893. (outline-previous-heading))
  21894. (unless (< (funcall outline-level) level)
  21895. (point)))))
  21896. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21897. "Goto to the end of a subtree."
  21898. ;; This contains an exact copy of the original function, but it uses
  21899. ;; `org-back-to-heading', to make it work also in invisible
  21900. ;; trees. And is uses an invisible-ok argument.
  21901. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21902. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21903. ;; with many children and grandchildren etc, this can be much faster
  21904. ;; than the outline version.
  21905. (org-back-to-heading invisible-ok)
  21906. (let ((first t)
  21907. (level (funcall outline-level)))
  21908. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21909. ;; A true heading (not a plain list item), in Org
  21910. ;; This means we can easily find the end by looking
  21911. ;; only for the right number of stars. Using a regexp to do
  21912. ;; this is so much faster than using a Lisp loop.
  21913. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21914. (forward-char 1)
  21915. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21916. ;; something else, do it the slow way
  21917. (while (and (not (eobp))
  21918. (or first (> (funcall outline-level) level)))
  21919. (setq first nil)
  21920. (outline-next-heading)))
  21921. (unless to-heading
  21922. (when (memq (preceding-char) '(?\n ?\^M))
  21923. ;; Go to end of line before heading
  21924. (forward-char -1)
  21925. (when (memq (preceding-char) '(?\n ?\^M))
  21926. ;; leave blank line before heading
  21927. (forward-char -1)))))
  21928. (point))
  21929. (defun org-end-of-meta-data (&optional full)
  21930. "Skip planning line and properties drawer in current entry.
  21931. When optional argument FULL is non-nil, also skip empty lines,
  21932. clocking lines and regular drawers at the beginning of the
  21933. entry."
  21934. (org-back-to-heading t)
  21935. (forward-line)
  21936. (when (looking-at-p org-planning-line-re) (forward-line))
  21937. (when (looking-at org-property-drawer-re)
  21938. (goto-char (match-end 0))
  21939. (forward-line))
  21940. (when (and full (not (org-at-heading-p)))
  21941. (catch 'exit
  21942. (let ((end (save-excursion (outline-next-heading) (point)))
  21943. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21944. (while (not (eobp))
  21945. (cond ((looking-at-p org-drawer-regexp)
  21946. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21947. (forward-line)
  21948. (throw 'exit t)))
  21949. ((looking-at-p re) (forward-line))
  21950. (t (throw 'exit t))))))))
  21951. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21952. "Move forward to the ARG'th subheading at same level as this one.
  21953. Stop at the first and last subheadings of a superior heading.
  21954. Normally this only looks at visible headings, but when INVISIBLE-OK is
  21955. non-nil it will also look at invisible ones."
  21956. (interactive "p")
  21957. (let ((backward? (and arg (< arg 0))))
  21958. (if (org-before-first-heading-p)
  21959. (if backward? (goto-char (point-min)) (outline-next-heading))
  21960. (org-back-to-heading invisible-ok)
  21961. (unless backward? (end-of-line)) ;do not match current headline
  21962. (let ((level (- (match-end 0) (match-beginning 0) 1))
  21963. (f (if backward? #'re-search-backward #'re-search-forward))
  21964. (count (if arg (abs arg) 1))
  21965. (result (point)))
  21966. (while (and (> count 0)
  21967. (funcall f org-outline-regexp-bol nil 'move))
  21968. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  21969. (cond ((< l level) (setq count 0))
  21970. ((and (= l level)
  21971. (or invisible-ok
  21972. (not (org-invisible-p
  21973. (line-beginning-position)))))
  21974. (cl-decf count)
  21975. (when (= l level) (setq result (point)))))))
  21976. (goto-char result))
  21977. (beginning-of-line))))
  21978. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  21979. "Move backward to the ARG'th subheading at same level as this one.
  21980. Stop at the first and last subheadings of a superior heading."
  21981. (interactive "p")
  21982. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  21983. (defun org-next-visible-heading (arg)
  21984. "Move to the next visible heading.
  21985. This function wraps `outline-next-visible-heading' with
  21986. `org-with-limited-levels' in order to skip over inline tasks and
  21987. respect customization of `org-odd-levels-only'."
  21988. (interactive "p")
  21989. (org-with-limited-levels
  21990. (outline-next-visible-heading arg)))
  21991. (defun org-previous-visible-heading (arg)
  21992. "Move to the previous visible heading.
  21993. This function wraps `outline-previous-visible-heading' with
  21994. `org-with-limited-levels' in order to skip over inline tasks and
  21995. respect customization of `org-odd-levels-only'."
  21996. (interactive "p")
  21997. (org-with-limited-levels
  21998. (outline-previous-visible-heading arg)))
  21999. (defun org-next-block (arg &optional backward block-regexp)
  22000. "Jump to the next block.
  22001. With a prefix argument ARG, jump forward ARG many blocks.
  22002. When BACKWARD is non-nil, jump to the previous block.
  22003. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22004. Match data is set according to this regexp when the function
  22005. returns.
  22006. Return point at beginning of the opening line of found block.
  22007. Throw an error if no block is found."
  22008. (interactive "p")
  22009. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22010. (case-fold-search t)
  22011. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22012. (count (or arg 1))
  22013. (origin (point))
  22014. last-element)
  22015. (if backward (beginning-of-line) (end-of-line))
  22016. (while (and (> count 0) (funcall search-fn re nil t))
  22017. (let ((element (save-excursion
  22018. (goto-char (match-beginning 0))
  22019. (save-match-data (org-element-at-point)))))
  22020. (when (and (memq (org-element-type element)
  22021. '(center-block comment-block dynamic-block
  22022. example-block export-block quote-block
  22023. special-block src-block verse-block))
  22024. (<= (match-beginning 0)
  22025. (org-element-property :post-affiliated element)))
  22026. (setq last-element element)
  22027. (cl-decf count))))
  22028. (if (= count 0)
  22029. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22030. (save-match-data (org-show-context)))
  22031. (goto-char origin)
  22032. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22033. (defun org-previous-block (arg &optional block-regexp)
  22034. "Jump to the previous block.
  22035. With a prefix argument ARG, jump backward ARG many source blocks.
  22036. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22037. (interactive "p")
  22038. (org-next-block arg t block-regexp))
  22039. (defun org-forward-paragraph ()
  22040. "Move forward to beginning of next paragraph or equivalent.
  22041. The function moves point to the beginning of the next visible
  22042. structural element, which can be a paragraph, a table, a list
  22043. item, etc. It also provides some special moves for convenience:
  22044. - On an affiliated keyword, jump to the beginning of the
  22045. relative element.
  22046. - On an item or a footnote definition, move to the second
  22047. element inside, if any.
  22048. - On a table or a property drawer, jump after it.
  22049. - On a verse or source block, stop after blank lines."
  22050. (interactive)
  22051. (unless (eobp)
  22052. (let* ((deactivate-mark nil)
  22053. (element (org-element-at-point))
  22054. (type (org-element-type element))
  22055. (post-affiliated (org-element-property :post-affiliated element))
  22056. (contents-begin (org-element-property :contents-begin element))
  22057. (contents-end (org-element-property :contents-end element))
  22058. (end (let ((end (org-element-property :end element)) (parent element))
  22059. (while (and (setq parent (org-element-property :parent parent))
  22060. (= (org-element-property :contents-end parent) end))
  22061. (setq end (org-element-property :end parent)))
  22062. end)))
  22063. (cond ((not element)
  22064. (skip-chars-forward " \r\t\n")
  22065. (or (eobp) (beginning-of-line)))
  22066. ;; On affiliated keywords, move to element's beginning.
  22067. ((< (point) post-affiliated)
  22068. (goto-char post-affiliated))
  22069. ;; At a table row, move to the end of the table. Similarly,
  22070. ;; at a node property, move to the end of the property
  22071. ;; drawer.
  22072. ((memq type '(node-property table-row))
  22073. (goto-char (org-element-property
  22074. :end (org-element-property :parent element))))
  22075. ((memq type '(property-drawer table)) (goto-char end))
  22076. ;; Consider blank lines as separators in verse and source
  22077. ;; blocks to ease editing.
  22078. ((memq type '(src-block verse-block))
  22079. (when (eq type 'src-block)
  22080. (setq contents-end
  22081. (save-excursion (goto-char end)
  22082. (skip-chars-backward " \r\t\n")
  22083. (line-beginning-position))))
  22084. (beginning-of-line)
  22085. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22086. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22087. (goto-char end)
  22088. (skip-chars-forward " \r\t\n")
  22089. (if (= (point) contents-end) (goto-char end)
  22090. (beginning-of-line))))
  22091. ;; With no contents, just skip element.
  22092. ((not contents-begin) (goto-char end))
  22093. ;; If contents are invisible, skip the element altogether.
  22094. ((org-invisible-p (line-end-position))
  22095. (cl-case type
  22096. (headline
  22097. (org-with-limited-levels (outline-next-visible-heading 1)))
  22098. ;; At a plain list, make sure we move to the next item
  22099. ;; instead of skipping the whole list.
  22100. (plain-list (forward-char)
  22101. (org-forward-paragraph))
  22102. (otherwise (goto-char end))))
  22103. ((>= (point) contents-end) (goto-char end))
  22104. ((>= (point) contents-begin)
  22105. ;; This can only happen on paragraphs and plain lists.
  22106. (cl-case type
  22107. (paragraph (goto-char end))
  22108. ;; At a plain list, try to move to second element in
  22109. ;; first item, if possible.
  22110. (plain-list (end-of-line)
  22111. (org-forward-paragraph))))
  22112. ;; When contents start on the middle of a line (e.g. in
  22113. ;; items and footnote definitions), try to reach first
  22114. ;; element starting after current line.
  22115. ((> (line-end-position) contents-begin)
  22116. (end-of-line)
  22117. (org-forward-paragraph))
  22118. (t (goto-char contents-begin))))))
  22119. (defun org-backward-paragraph ()
  22120. "Move backward to start of previous paragraph or equivalent.
  22121. The function moves point to the beginning of the current
  22122. structural element, which can be a paragraph, a table, a list
  22123. item, etc., or to the beginning of the previous visible one if
  22124. point is already there. It also provides some special moves for
  22125. convenience:
  22126. - On an affiliated keyword, jump to the first one.
  22127. - On a table or a property drawer, move to its beginning.
  22128. - On a verse or source block, stop before blank lines."
  22129. (interactive)
  22130. (unless (bobp)
  22131. (let* ((deactivate-mark nil)
  22132. (element (org-element-at-point))
  22133. (type (org-element-type element))
  22134. (contents-begin (org-element-property :contents-begin element))
  22135. (contents-end (org-element-property :contents-end element))
  22136. (post-affiliated (org-element-property :post-affiliated element))
  22137. (begin (org-element-property :begin element)))
  22138. (cond
  22139. ((not element) (goto-char (point-min)))
  22140. ((= (point) begin)
  22141. (backward-char)
  22142. (org-backward-paragraph))
  22143. ((<= (point) post-affiliated) (goto-char begin))
  22144. ((memq type '(node-property table-row))
  22145. (goto-char (org-element-property
  22146. :post-affiliated (org-element-property :parent element))))
  22147. ((memq type '(property-drawer table)) (goto-char begin))
  22148. ((memq type '(src-block verse-block))
  22149. (when (eq type 'src-block)
  22150. (setq contents-begin
  22151. (save-excursion (goto-char begin) (forward-line) (point))))
  22152. (if (= (point) contents-begin) (goto-char post-affiliated)
  22153. ;; Inside a verse block, see blank lines as paragraph
  22154. ;; separators.
  22155. (let ((origin (point)))
  22156. (skip-chars-backward " \r\t\n" contents-begin)
  22157. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22158. (skip-chars-forward " \r\t\n" origin)
  22159. (if (= (point) origin) (goto-char contents-begin)
  22160. (beginning-of-line))))))
  22161. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22162. ((eq type 'paragraph)
  22163. (goto-char contents-begin)
  22164. ;; When at first paragraph in an item or a footnote definition,
  22165. ;; move directly to beginning of line.
  22166. (let ((parent-contents
  22167. (org-element-property
  22168. :contents-begin (org-element-property :parent element))))
  22169. (when (and parent-contents (= parent-contents contents-begin))
  22170. (beginning-of-line))))
  22171. ;; At the end of a greater element, move to the beginning of the
  22172. ;; last element within.
  22173. ((>= (point) contents-end)
  22174. (goto-char (1- contents-end))
  22175. (org-backward-paragraph))
  22176. (t (goto-char (or post-affiliated begin))))
  22177. ;; Ensure we never leave point invisible.
  22178. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  22179. (defun org-forward-element ()
  22180. "Move forward by one element.
  22181. Move to the next element at the same level, when possible."
  22182. (interactive)
  22183. (cond ((eobp) (user-error "Cannot move further down"))
  22184. ((org-with-limited-levels (org-at-heading-p))
  22185. (let ((origin (point)))
  22186. (goto-char (org-end-of-subtree nil t))
  22187. (unless (org-with-limited-levels (org-at-heading-p))
  22188. (goto-char origin)
  22189. (user-error "Cannot move further down"))))
  22190. (t
  22191. (let* ((elem (org-element-at-point))
  22192. (end (org-element-property :end elem))
  22193. (parent (org-element-property :parent elem)))
  22194. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22195. (goto-char (org-element-property :end parent)))
  22196. ((integer-or-marker-p end) (goto-char end))
  22197. (t (message "No element at point")))))))
  22198. (defun org-backward-element ()
  22199. "Move backward by one element.
  22200. Move to the previous element at the same level, when possible."
  22201. (interactive)
  22202. (cond ((bobp) (user-error "Cannot move further up"))
  22203. ((org-with-limited-levels (org-at-heading-p))
  22204. ;; At a headline, move to the previous one, if any, or stay
  22205. ;; here.
  22206. (let ((origin (point)))
  22207. (org-with-limited-levels (org-backward-heading-same-level 1))
  22208. ;; When current headline has no sibling above, move to its
  22209. ;; parent.
  22210. (when (= (point) origin)
  22211. (or (org-with-limited-levels (org-up-heading-safe))
  22212. (progn (goto-char origin)
  22213. (user-error "Cannot move further up"))))))
  22214. (t
  22215. (let* ((elem (org-element-at-point))
  22216. (beg (org-element-property :begin elem)))
  22217. (cond
  22218. ;; Move to beginning of current element if point isn't
  22219. ;; there already.
  22220. ((null beg) (message "No element at point"))
  22221. ((/= (point) beg) (goto-char beg))
  22222. (t (goto-char beg)
  22223. (skip-chars-backward " \r\t\n")
  22224. (unless (bobp)
  22225. (let ((prev (org-element-at-point)))
  22226. (goto-char (org-element-property :begin prev))
  22227. (while (and (setq prev (org-element-property :parent prev))
  22228. (<= (org-element-property :end prev) beg))
  22229. (goto-char (org-element-property :begin prev)))))))))))
  22230. (defun org-up-element ()
  22231. "Move to upper element."
  22232. (interactive)
  22233. (if (org-with-limited-levels (org-at-heading-p))
  22234. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22235. (let* ((elem (org-element-at-point))
  22236. (parent (org-element-property :parent elem)))
  22237. (if parent (goto-char (org-element-property :begin parent))
  22238. (if (org-with-limited-levels (org-before-first-heading-p))
  22239. (user-error "No surrounding element")
  22240. (org-with-limited-levels (org-back-to-heading)))))))
  22241. (defun org-down-element ()
  22242. "Move to inner element."
  22243. (interactive)
  22244. (let ((element (org-element-at-point)))
  22245. (cond
  22246. ((memq (org-element-type element) '(plain-list table))
  22247. (goto-char (org-element-property :contents-begin element))
  22248. (forward-char))
  22249. ((memq (org-element-type element) org-element-greater-elements)
  22250. ;; If contents are hidden, first disclose them.
  22251. (when (org-invisible-p (line-end-position)) (org-cycle))
  22252. (goto-char (or (org-element-property :contents-begin element)
  22253. (user-error "No content for this element"))))
  22254. (t (user-error "No inner element")))))
  22255. (defun org-drag-element-backward ()
  22256. "Move backward element at point."
  22257. (interactive)
  22258. (let ((elem (or (org-element-at-point)
  22259. (user-error "No element at point"))))
  22260. (if (eq (org-element-type elem) 'headline)
  22261. ;; Preserve point when moving a whole tree, even if point was
  22262. ;; on blank lines below the headline.
  22263. (let ((offset (skip-chars-backward " \t\n")))
  22264. (unwind-protect (org-move-subtree-up)
  22265. (forward-char (- offset))))
  22266. (let ((prev-elem
  22267. (save-excursion
  22268. (goto-char (org-element-property :begin elem))
  22269. (skip-chars-backward " \r\t\n")
  22270. (unless (bobp)
  22271. (let* ((beg (org-element-property :begin elem))
  22272. (prev (org-element-at-point))
  22273. (up prev))
  22274. (while (and (setq up (org-element-property :parent up))
  22275. (<= (org-element-property :end up) beg))
  22276. (setq prev up))
  22277. prev)))))
  22278. ;; Error out if no previous element or previous element is
  22279. ;; a parent of the current one.
  22280. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22281. (user-error "Cannot drag element backward")
  22282. (let ((pos (point)))
  22283. (org-element-swap-A-B prev-elem elem)
  22284. (goto-char (+ (org-element-property :begin prev-elem)
  22285. (- pos (org-element-property :begin elem))))))))))
  22286. (defun org-drag-element-forward ()
  22287. "Move forward element at point."
  22288. (interactive)
  22289. (let* ((pos (point))
  22290. (elem (or (org-element-at-point)
  22291. (user-error "No element at point"))))
  22292. (when (= (point-max) (org-element-property :end elem))
  22293. (user-error "Cannot drag element forward"))
  22294. (goto-char (org-element-property :end elem))
  22295. (let ((next-elem (org-element-at-point)))
  22296. (when (or (org-element-nested-p elem next-elem)
  22297. (and (eq (org-element-type next-elem) 'headline)
  22298. (not (eq (org-element-type elem) 'headline))))
  22299. (goto-char pos)
  22300. (user-error "Cannot drag element forward"))
  22301. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22302. ;; body's length (without final blanks) and by the length of
  22303. ;; blanks between ELEM and NEXT-ELEM.
  22304. (let ((size-next (- (save-excursion
  22305. (goto-char (org-element-property :end next-elem))
  22306. (skip-chars-backward " \r\t\n")
  22307. (forward-line)
  22308. ;; Small correction if buffer doesn't end
  22309. ;; with a newline character.
  22310. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22311. (org-element-property :begin next-elem)))
  22312. (size-blank (- (org-element-property :end elem)
  22313. (save-excursion
  22314. (goto-char (org-element-property :end elem))
  22315. (skip-chars-backward " \r\t\n")
  22316. (forward-line)
  22317. (point)))))
  22318. (org-element-swap-A-B elem next-elem)
  22319. (goto-char (+ pos size-next size-blank))))))
  22320. (defun org-drag-line-forward (arg)
  22321. "Drag the line at point ARG lines forward."
  22322. (interactive "p")
  22323. (dotimes (_ (abs arg))
  22324. (let ((c (current-column)))
  22325. (if (< 0 arg)
  22326. (progn
  22327. (beginning-of-line 2)
  22328. (transpose-lines 1)
  22329. (beginning-of-line 0))
  22330. (transpose-lines 1)
  22331. (beginning-of-line -1))
  22332. (org-move-to-column c))))
  22333. (defun org-drag-line-backward (arg)
  22334. "Drag the line at point ARG lines backward."
  22335. (interactive "p")
  22336. (org-drag-line-forward (- arg)))
  22337. (defun org-mark-element ()
  22338. "Put point at beginning of this element, mark at end.
  22339. Interactively, if this command is repeated or (in Transient Mark
  22340. mode) if the mark is active, it marks the next element after the
  22341. ones already marked."
  22342. (interactive)
  22343. (let (deactivate-mark)
  22344. (if (and (called-interactively-p 'any)
  22345. (or (and (eq last-command this-command) (mark t))
  22346. (and transient-mark-mode mark-active)))
  22347. (set-mark
  22348. (save-excursion
  22349. (goto-char (mark))
  22350. (goto-char (org-element-property :end (org-element-at-point)))))
  22351. (let ((element (org-element-at-point)))
  22352. (end-of-line)
  22353. (push-mark (org-element-property :end element) t t)
  22354. (goto-char (org-element-property :begin element))))))
  22355. (defun org-narrow-to-element ()
  22356. "Narrow buffer to current element."
  22357. (interactive)
  22358. (let ((elem (org-element-at-point)))
  22359. (cond
  22360. ((eq (car elem) 'headline)
  22361. (narrow-to-region
  22362. (org-element-property :begin elem)
  22363. (org-element-property :end elem)))
  22364. ((memq (car elem) org-element-greater-elements)
  22365. (narrow-to-region
  22366. (org-element-property :contents-begin elem)
  22367. (org-element-property :contents-end elem)))
  22368. (t
  22369. (narrow-to-region
  22370. (org-element-property :begin elem)
  22371. (org-element-property :end elem))))))
  22372. (defun org-transpose-element ()
  22373. "Transpose current and previous elements, keeping blank lines between.
  22374. Point is moved after both elements."
  22375. (interactive)
  22376. (org-skip-whitespace)
  22377. (let ((end (org-element-property :end (org-element-at-point))))
  22378. (org-drag-element-backward)
  22379. (goto-char end)))
  22380. (defun org-unindent-buffer ()
  22381. "Un-indent the visible part of the buffer.
  22382. Relative indentation (between items, inside blocks, etc.) isn't
  22383. modified."
  22384. (interactive)
  22385. (unless (eq major-mode 'org-mode)
  22386. (user-error "Cannot un-indent a buffer not in Org mode"))
  22387. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22388. (unindent-tree
  22389. (lambda (contents)
  22390. (dolist (element (reverse contents))
  22391. (if (memq (org-element-type element) '(headline section))
  22392. (funcall unindent-tree (org-element-contents element))
  22393. (save-excursion
  22394. (save-restriction
  22395. (narrow-to-region
  22396. (org-element-property :begin element)
  22397. (org-element-property :end element))
  22398. (org-do-remove-indentation))))))))
  22399. (funcall unindent-tree (org-element-contents parse-tree))))
  22400. (defun org-show-children (&optional level)
  22401. "Show all direct subheadings of this heading.
  22402. Prefix arg LEVEL is how many levels below the current level
  22403. should be shown. Default is enough to cause the following
  22404. heading to appear."
  22405. (interactive "p")
  22406. ;; If `orgstruct-mode' is active, use the slower version.
  22407. (if orgstruct-mode (call-interactively #'outline-show-children)
  22408. (save-excursion
  22409. (org-back-to-heading t)
  22410. (let* ((current-level (funcall outline-level))
  22411. (max-level (org-get-valid-level
  22412. current-level
  22413. (if level (prefix-numeric-value level) 1)))
  22414. (end (save-excursion (org-end-of-subtree t t)))
  22415. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22416. (past-first-child nil)
  22417. ;; Make sure to skip inlinetasks.
  22418. (re (format regexp-fmt
  22419. current-level
  22420. (cond
  22421. ((not (featurep 'org-inlinetask)) "")
  22422. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22423. 3))
  22424. (t (1- org-inlinetask-min-level))))))
  22425. ;; Display parent heading.
  22426. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22427. (forward-line)
  22428. ;; Display children. First child may be deeper than expected
  22429. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22430. ;; MAX-LEVEL accordingly.
  22431. (while (re-search-forward re end t)
  22432. (unless past-first-child
  22433. (setq re (format regexp-fmt
  22434. current-level
  22435. (max (funcall outline-level) max-level)))
  22436. (setq past-first-child t))
  22437. (outline-flag-region
  22438. (line-end-position 0) (line-end-position) nil))))))
  22439. (defun org-show-subtree ()
  22440. "Show everything after this heading at deeper levels."
  22441. (interactive)
  22442. (outline-flag-region
  22443. (point)
  22444. (save-excursion
  22445. (org-end-of-subtree t t))
  22446. nil))
  22447. (defun org-show-entry ()
  22448. "Show the body directly following this heading.
  22449. Show the heading too, if it is currently invisible."
  22450. (interactive)
  22451. (save-excursion
  22452. (ignore-errors
  22453. (org-back-to-heading t)
  22454. (outline-flag-region
  22455. (max (point-min) (1- (point)))
  22456. (save-excursion
  22457. (if (re-search-forward
  22458. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22459. (match-beginning 1)
  22460. (point-max)))
  22461. nil)
  22462. (org-cycle-hide-drawers 'children))))
  22463. (defun org-make-options-regexp (kwds &optional extra)
  22464. "Make a regular expression for keyword lines.
  22465. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22466. when non-nil, is a regexp matching keywords names."
  22467. (concat "^[ \t]*#\\+\\("
  22468. (regexp-opt kwds)
  22469. (and extra (concat (and kwds "\\|") extra))
  22470. "\\):[ \t]*\\(.*\\)"))
  22471. ;;;; Integration with and fixes for other packages
  22472. ;;; Imenu support
  22473. (defvar-local org-imenu-markers nil
  22474. "All markers currently used by Imenu.")
  22475. (defun org-imenu-new-marker (&optional pos)
  22476. "Return a new marker for use by Imenu, and remember the marker."
  22477. (let ((m (make-marker)))
  22478. (move-marker m (or pos (point)))
  22479. (push m org-imenu-markers)
  22480. m))
  22481. (defun org-imenu-get-tree ()
  22482. "Produce the index for Imenu."
  22483. (dolist (x org-imenu-markers) (move-marker x nil))
  22484. (setq org-imenu-markers nil)
  22485. (let* ((case-fold-search nil)
  22486. (n org-imenu-depth)
  22487. (re (concat "^" (org-get-limited-outline-regexp)))
  22488. (subs (make-vector (1+ n) nil))
  22489. (last-level 0)
  22490. m level head0 head)
  22491. (org-with-wide-buffer
  22492. (goto-char (point-max))
  22493. (while (re-search-backward re nil t)
  22494. (setq level (org-reduced-level (funcall outline-level)))
  22495. (when (and (<= level n)
  22496. (looking-at org-complex-heading-regexp)
  22497. (setq head0 (match-string-no-properties 4)))
  22498. (setq head (org-link-display-format head0)
  22499. m (org-imenu-new-marker))
  22500. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22501. (if (>= level last-level)
  22502. (push (cons head m) (aref subs level))
  22503. (push (cons head (aref subs (1+ level))) (aref subs level))
  22504. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22505. (setq last-level level))))
  22506. (aref subs 1)))
  22507. (eval-after-load "imenu"
  22508. '(progn
  22509. (add-hook 'imenu-after-jump-hook
  22510. (lambda ()
  22511. (when (derived-mode-p 'org-mode)
  22512. (org-show-context 'org-goto))))))
  22513. (defun org-link-display-format (s)
  22514. "Replace links in string S with their description.
  22515. If there is no description, use the link target."
  22516. (save-match-data
  22517. (replace-regexp-in-string
  22518. org-bracket-link-analytic-regexp
  22519. (lambda (m)
  22520. (if (match-end 5) (match-string 5 m)
  22521. (concat (match-string 1 m) (match-string 3 m))))
  22522. s nil t)))
  22523. (defun org-toggle-link-display ()
  22524. "Toggle the literal or descriptive display of links."
  22525. (interactive)
  22526. (if org-descriptive-links
  22527. (progn (org-remove-from-invisibility-spec '(org-link))
  22528. (org-restart-font-lock)
  22529. (setq org-descriptive-links nil))
  22530. (progn (add-to-invisibility-spec '(org-link))
  22531. (org-restart-font-lock)
  22532. (setq org-descriptive-links t))))
  22533. ;; Speedbar support
  22534. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22535. "Overlay marking the agenda restriction line in speedbar.")
  22536. (overlay-put org-speedbar-restriction-lock-overlay
  22537. 'face 'org-agenda-restriction-lock)
  22538. (overlay-put org-speedbar-restriction-lock-overlay
  22539. 'help-echo "Agendas are currently limited to this item.")
  22540. (delete-overlay org-speedbar-restriction-lock-overlay)
  22541. (defun org-speedbar-set-agenda-restriction ()
  22542. "Restrict future agenda commands to the location at point in speedbar.
  22543. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22544. (interactive)
  22545. (require 'org-agenda)
  22546. (let (p m tp np dir txt)
  22547. (cond
  22548. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22549. 'org-imenu t))
  22550. (setq m (get-text-property p 'org-imenu-marker))
  22551. (with-current-buffer (marker-buffer m)
  22552. (goto-char m)
  22553. (org-agenda-set-restriction-lock 'subtree)))
  22554. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22555. 'speedbar-function 'speedbar-find-file))
  22556. (setq tp (previous-single-property-change
  22557. (1+ p) 'speedbar-function)
  22558. np (next-single-property-change
  22559. tp 'speedbar-function)
  22560. dir (speedbar-line-directory)
  22561. txt (buffer-substring-no-properties (or tp (point-min))
  22562. (or np (point-max))))
  22563. (with-current-buffer (find-file-noselect
  22564. (let ((default-directory dir))
  22565. (expand-file-name txt)))
  22566. (unless (derived-mode-p 'org-mode)
  22567. (user-error "Cannot restrict to non-Org mode file"))
  22568. (org-agenda-set-restriction-lock 'file)))
  22569. (t (user-error "Don't know how to restrict Org mode agenda")))
  22570. (move-overlay org-speedbar-restriction-lock-overlay
  22571. (point-at-bol) (point-at-eol))
  22572. (setq current-prefix-arg nil)
  22573. (org-agenda-maybe-redo)))
  22574. (defvar speedbar-file-key-map)
  22575. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22576. (eval-after-load "speedbar"
  22577. '(progn
  22578. (speedbar-add-supported-extension ".org")
  22579. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22580. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22581. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22582. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22583. (add-hook 'speedbar-visiting-tag-hook
  22584. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22585. ;;; Fixes and Hacks for problems with other packages
  22586. (defun org--flyspell-object-check-p (element)
  22587. "Non-nil when Flyspell can check object at point.
  22588. ELEMENT is the element at point."
  22589. (let ((object (save-excursion
  22590. (when (looking-at-p "\\>") (backward-char))
  22591. (org-element-context element))))
  22592. (cl-case (org-element-type object)
  22593. ;; Prevent checks in links due to keybinding conflict with
  22594. ;; Flyspell.
  22595. ((code entity export-snippet inline-babel-call
  22596. inline-src-block line-break latex-fragment link macro
  22597. statistics-cookie target timestamp verbatim)
  22598. nil)
  22599. (footnote-reference
  22600. ;; Only in inline footnotes, within the definition.
  22601. (and (eq (org-element-property :type object) 'inline)
  22602. (< (save-excursion
  22603. (goto-char (org-element-property :begin object))
  22604. (search-forward ":" nil t 2))
  22605. (point))))
  22606. (otherwise t))))
  22607. (defun org-mode-flyspell-verify ()
  22608. "Function used for `flyspell-generic-check-word-predicate'."
  22609. (if (org-at-heading-p)
  22610. ;; At a headline or an inlinetask, check title only. This is
  22611. ;; faster than relying on `org-element-at-point'.
  22612. (and (save-excursion (beginning-of-line)
  22613. (and (let ((case-fold-search t))
  22614. (not (looking-at-p "\\*+ END[ \t]*$")))
  22615. (let ((case-fold-search nil))
  22616. (looking-at org-complex-heading-regexp))))
  22617. (match-beginning 4)
  22618. (>= (point) (match-beginning 4))
  22619. (or (not (match-beginning 5))
  22620. (< (point) (match-beginning 5))))
  22621. (let* ((element (org-element-at-point))
  22622. (post-affiliated (org-element-property :post-affiliated element)))
  22623. (cond
  22624. ;; Ignore checks in all affiliated keywords but captions.
  22625. ((< (point) post-affiliated)
  22626. (and (save-excursion
  22627. (beginning-of-line)
  22628. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22629. (> (point) (match-end 0))
  22630. (org--flyspell-object-check-p element)))
  22631. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22632. ((let ((log (org-log-into-drawer)))
  22633. (and log
  22634. (let ((drawer (org-element-lineage element '(drawer))))
  22635. (and drawer
  22636. (eq (compare-strings
  22637. log nil nil
  22638. (org-element-property :drawer-name drawer) nil nil t)
  22639. t)))))
  22640. nil)
  22641. (t
  22642. (cl-case (org-element-type element)
  22643. ((comment quote-section) t)
  22644. (comment-block
  22645. ;; Allow checks between block markers, not on them.
  22646. (and (> (line-beginning-position) post-affiliated)
  22647. (save-excursion
  22648. (end-of-line)
  22649. (skip-chars-forward " \r\t\n")
  22650. (< (point) (org-element-property :end element)))))
  22651. ;; Arbitrary list of keywords where checks are meaningful.
  22652. ;; Make sure point is on the value part of the element.
  22653. (keyword
  22654. (and (member (org-element-property :key element)
  22655. '("DESCRIPTION" "TITLE"))
  22656. (save-excursion
  22657. (search-backward ":" (line-beginning-position) t))))
  22658. ;; Check is globally allowed in paragraphs verse blocks and
  22659. ;; table rows (after affiliated keywords) but some objects
  22660. ;; must not be affected.
  22661. ((paragraph table-row verse-block)
  22662. (let ((cbeg (org-element-property :contents-begin element))
  22663. (cend (org-element-property :contents-end element)))
  22664. (and cbeg (>= (point) cbeg) (< (point) cend)
  22665. (org--flyspell-object-check-p element))))))))))
  22666. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22667. (defun org-remove-flyspell-overlays-in (beg end)
  22668. "Remove flyspell overlays in region."
  22669. (and (bound-and-true-p flyspell-mode)
  22670. (fboundp 'flyspell-delete-region-overlays)
  22671. (flyspell-delete-region-overlays beg end)))
  22672. (defvar flyspell-delayed-commands)
  22673. (eval-after-load "flyspell"
  22674. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22675. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22676. (eval-after-load "bookmark"
  22677. '(if (boundp 'bookmark-after-jump-hook)
  22678. ;; We can use the hook
  22679. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22680. ;; Hook not available, use advice
  22681. (defadvice bookmark-jump (after org-make-visible activate)
  22682. "Make the position visible."
  22683. (org-bookmark-jump-unhide))))
  22684. ;; Make sure saveplace shows the location if it was hidden
  22685. (eval-after-load "saveplace"
  22686. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22687. "Make the position visible."
  22688. (org-bookmark-jump-unhide)))
  22689. ;; Make sure ecb shows the location if it was hidden
  22690. (eval-after-load "ecb"
  22691. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22692. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22693. (when (derived-mode-p 'org-mode)
  22694. (org-show-context))))
  22695. (defun org-bookmark-jump-unhide ()
  22696. "Unhide the current position, to show the bookmark location."
  22697. (and (derived-mode-p 'org-mode)
  22698. (or (org-invisible-p)
  22699. (save-excursion (goto-char (max (point-min) (1- (point))))
  22700. (org-invisible-p)))
  22701. (org-show-context 'bookmark-jump)))
  22702. (defun org-mark-jump-unhide ()
  22703. "Make the point visible with `org-show-context' after jumping to the mark."
  22704. (when (and (derived-mode-p 'org-mode)
  22705. (org-invisible-p))
  22706. (org-show-context 'mark-goto)))
  22707. (eval-after-load "simple"
  22708. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22709. "Make the point visible with `org-show-context'."
  22710. (org-mark-jump-unhide)))
  22711. (eval-after-load "simple"
  22712. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22713. "Make the point visible with `org-show-context'."
  22714. (org-mark-jump-unhide)))
  22715. (eval-after-load "simple"
  22716. '(defadvice pop-global-mark (after org-make-visible activate)
  22717. "Make the point visible with `org-show-context'."
  22718. (org-mark-jump-unhide)))
  22719. ;; Make session.el ignore our circular variable
  22720. (defvar session-globals-exclude)
  22721. (eval-after-load "session"
  22722. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22723. ;;;; Finish up
  22724. (provide 'org)
  22725. (run-hooks 'org-load-hook)
  22726. ;;; org.el ends here