org.el 953 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183
  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-2016 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org-mode 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 contain
  29. ;; information about projects as plain text. Org-mode is implemented on
  30. ;; top of outline-mode, which makes it possible to keep the content of
  31. ;; large files well structured. Visibility cycling and structure editing
  32. ;; help to work with the tree. Tables are easily created with a built-in
  33. ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
  34. ;; and scheduling. It dynamically compiles entries into an agenda that
  35. ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
  36. ;; Plain text URL-like links connect to websites, emails, Usenet
  37. ;; messages, BBDB entries, and any files related to the projects. For
  38. ;; printing and sharing of notes, an Org-mode file can be exported as a
  39. ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
  40. ;; iCalendar file. It can also serve as a publishing tool for a set of
  41. ;; linked webpages.
  42. ;;
  43. ;; Installation and Activation
  44. ;; ---------------------------
  45. ;; See the corresponding sections in the manual at
  46. ;;
  47. ;; http://orgmode.org/org.html#Installation
  48. ;;
  49. ;; Documentation
  50. ;; -------------
  51. ;; The documentation of Org mode can be found in the TeXInfo file. The
  52. ;; distribution also contains a PDF version of it. At the homepage of
  53. ;; Org mode, you can read the same text online as HTML. There is also an
  54. ;; excellent reference card made by Philip Rooke. This card can be found
  55. ;; in the doc/ directory.
  56. ;;
  57. ;; A list of recent changes can be found at
  58. ;; http://orgmode.org/Changes.html
  59. ;;
  60. ;;; Code:
  61. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  62. (defvar-local org-table-formula-constants-local nil
  63. "Local version of `org-table-formula-constants'.")
  64. ;;;; Require other packages
  65. (require 'cl-lib)
  66. (eval-when-compile (require 'gnus-sum))
  67. (require 'calendar)
  68. (require 'find-func)
  69. (require 'format-spec)
  70. (or (equal this-command 'eval-buffer)
  71. (condition-case nil
  72. (load (concat (file-name-directory load-file-name)
  73. "org-loaddefs.el")
  74. nil t t t)
  75. (error
  76. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  77. (sit-for 3)
  78. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  79. (sit-for 3))))
  80. (require 'org-macs)
  81. (require 'org-compat)
  82. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  83. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  84. ;;
  85. ;; In Org buffers, the value of `outline-regexp' is that of
  86. ;; `org-outline-regexp'. The only function still directly relying on
  87. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  88. ;; job when `orgstruct-mode' is active.
  89. (defvar org-outline-regexp "\\*+ "
  90. "Regexp to match Org headlines.")
  91. (defvar org-outline-regexp-bol "^\\*+ "
  92. "Regexp to match Org headlines.
  93. This is similar to `org-outline-regexp' but additionally makes
  94. sure that we are at the beginning of the line.")
  95. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  96. "Matches a headline, putting stars and text into groups.
  97. Stars are put in group 1 and the trimmed body in group 2.")
  98. (declare-function calendar-check-holidays "holidays" (date))
  99. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  100. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  101. (declare-function org-add-archive-files "org-archive" (files))
  102. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  103. (declare-function org-agenda-list "org-agenda"
  104. (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocktable-shift "org-clock" (dir n))
  118. (declare-function org-element-at-point "org-element" ())
  119. (declare-function org-element-cache-refresh "org-element" (pos))
  120. (declare-function org-element-cache-reset "org-element" (&optional all))
  121. (declare-function org-element-contents "org-element" (element))
  122. (declare-function org-element-context "org-element" (&optional element))
  123. (declare-function org-element-copy "org-element" (datum))
  124. (declare-function org-element-interpret-data "org-element" (data))
  125. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  126. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  127. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  128. (declare-function org-element-property "org-element" (property element))
  129. (declare-function org-element-put-property "org-element" (element property value))
  130. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  131. (declare-function org-element-type "org-element" (element))
  132. (declare-function org-element-update-syntax "org-element" ())
  133. (declare-function org-id-find-id-file "org-id" (id))
  134. (declare-function org-id-get-create "org-id" (&optional force))
  135. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  136. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  137. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  138. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  139. (declare-function org-table-align "org-table" ())
  140. (declare-function org-table-begin "org-table" (&optional table-type))
  141. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  142. (declare-function org-table-blank-field "org-table" ())
  143. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  144. (declare-function org-table-edit-field "org-table" (arg))
  145. (declare-function org-table-end "org-table" (&optional table-type))
  146. (declare-function org-table-end-of-field "org-table" (&optional n))
  147. (declare-function org-table-insert-row "org-table" (&optional arg))
  148. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  149. (declare-function org-table-maybe-eval-formula "org-table" ())
  150. (declare-function org-table-maybe-recalculate-line "org-table" ())
  151. (declare-function org-table-next-row "org-table" ())
  152. (declare-function org-table-paste-rectangle "org-table" ())
  153. (declare-function org-table-wrap-region "org-table" (arg))
  154. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  155. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  156. (declare-function orgtbl-mode "org-table" (&optional arg))
  157. (defsubst org-uniquify (list)
  158. "Non-destructively remove duplicate elements from LIST."
  159. (let ((res (copy-sequence list))) (delete-dups res)))
  160. (defsubst org-get-at-bol (property)
  161. "Get text property PROPERTY at the beginning of line."
  162. (get-text-property (point-at-bol) property))
  163. (defsubst org-trim (s &optional keep-lead)
  164. "Remove whitespace at the beginning and the end of string S.
  165. When optional argument KEEP-LEAD is non-nil, removing blank lines
  166. at the beginning of the string does not affect leading indentation."
  167. (replace-regexp-in-string
  168. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  169. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  170. ;; load languages based on value of `org-babel-load-languages'
  171. (defvar org-babel-load-languages)
  172. ;;;###autoload
  173. (defun org-babel-do-load-languages (sym value)
  174. "Load the languages defined in `org-babel-load-languages'."
  175. (set-default sym value)
  176. (dolist (pair org-babel-load-languages)
  177. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  178. (if active
  179. (require (intern (concat "ob-" lang)))
  180. (funcall 'fmakunbound
  181. (intern (concat "org-babel-execute:" lang)))
  182. (funcall 'fmakunbound
  183. (intern (concat "org-babel-expand-body:" lang)))))))
  184. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  185. ;;;###autoload
  186. (defun org-babel-load-file (file &optional compile)
  187. "Load Emacs Lisp source code blocks in the Org-mode FILE.
  188. This function exports the source code using `org-babel-tangle'
  189. and then loads the resulting file using `load-file'. With prefix
  190. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  191. file to byte-code before it is loaded."
  192. (interactive "fFile to load: \nP")
  193. (let* ((age (lambda (file)
  194. (float-time
  195. (time-subtract (current-time)
  196. (nth 5 (or (file-attributes (file-truename file))
  197. (file-attributes file)))))))
  198. (base-name (file-name-sans-extension file))
  199. (exported-file (concat base-name ".el")))
  200. ;; tangle if the org-mode file is newer than the elisp file
  201. (unless (and (file-exists-p exported-file)
  202. (> (funcall age file) (funcall age exported-file)))
  203. ;; Tangle-file traversal returns reversed list of tangled files
  204. ;; and we want to evaluate the first target.
  205. (setq exported-file
  206. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  207. (message "%s %s"
  208. (if compile
  209. (progn (byte-compile-file exported-file 'load)
  210. "Compiled and loaded")
  211. (progn (load-file exported-file) "Loaded"))
  212. exported-file)))
  213. (defcustom org-babel-load-languages '((emacs-lisp . t))
  214. "Languages which can be evaluated in Org-mode buffers.
  215. This list can be used to load support for any of the languages
  216. below, note that each language will depend on a different set of
  217. system executables and/or Emacs modes. When a language is
  218. \"loaded\", then code blocks in that language can be evaluated
  219. with `org-babel-execute-src-block' bound by default to C-c
  220. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  221. be set to remove code block evaluation from the C-c C-c
  222. keybinding. By default only Emacs Lisp (which has no
  223. requirements) is loaded."
  224. :group 'org-babel
  225. :set 'org-babel-do-load-languages
  226. :version "24.1"
  227. :type '(alist :tag "Babel Languages"
  228. :key-type
  229. (choice
  230. (const :tag "Awk" awk)
  231. (const :tag "C" C)
  232. (const :tag "R" R)
  233. (const :tag "Asymptote" asymptote)
  234. (const :tag "Calc" calc)
  235. (const :tag "Clojure" clojure)
  236. (const :tag "CSS" css)
  237. (const :tag "Ditaa" ditaa)
  238. (const :tag "Dot" dot)
  239. (const :tag "Emacs Lisp" emacs-lisp)
  240. (const :tag "Forth" forth)
  241. (const :tag "Fortran" fortran)
  242. (const :tag "Gnuplot" gnuplot)
  243. (const :tag "Haskell" haskell)
  244. (const :tag "IO" io)
  245. (const :tag "J" J)
  246. (const :tag "Java" java)
  247. (const :tag "Javascript" js)
  248. (const :tag "LaTeX" latex)
  249. (const :tag "Ledger" ledger)
  250. (const :tag "Lilypond" lilypond)
  251. (const :tag "Lisp" lisp)
  252. (const :tag "Makefile" makefile)
  253. (const :tag "Maxima" maxima)
  254. (const :tag "Matlab" matlab)
  255. (const :tag "Mscgen" mscgen)
  256. (const :tag "Ocaml" ocaml)
  257. (const :tag "Octave" octave)
  258. (const :tag "Org" org)
  259. (const :tag "Perl" perl)
  260. (const :tag "Pico Lisp" picolisp)
  261. (const :tag "PlantUML" plantuml)
  262. (const :tag "Python" python)
  263. (const :tag "Ruby" ruby)
  264. (const :tag "Sass" sass)
  265. (const :tag "Scala" scala)
  266. (const :tag "Scheme" scheme)
  267. (const :tag "Screen" screen)
  268. (const :tag "Shell Script" shell)
  269. (const :tag "Shen" shen)
  270. (const :tag "Sql" sql)
  271. (const :tag "Sqlite" sqlite)
  272. (const :tag "Stan" stan)
  273. (const :tag "ebnf2ps" ebnf2ps))
  274. :value-type (boolean :tag "Activate" :value t)))
  275. ;;;; Customization variables
  276. (defcustom org-clone-delete-id nil
  277. "Remove ID property of clones of a subtree.
  278. When non-nil, clones of a subtree don't inherit the ID property.
  279. Otherwise they inherit the ID property with a new unique
  280. identifier."
  281. :type 'boolean
  282. :version "24.1"
  283. :group 'org-id)
  284. ;;; Version
  285. (org-check-version)
  286. ;;;###autoload
  287. (defun org-version (&optional here full message)
  288. "Show the org-mode version.
  289. Interactively, or when MESSAGE is non-nil, show it in echo area.
  290. With prefix argument, or when HERE is non-nil, insert it at point.
  291. In non-interactive uses, a reduced version string is output unless
  292. FULL is given."
  293. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  294. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  295. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  296. (load-suffixes (list ".el"))
  297. (org-install-dir
  298. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  299. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  300. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  301. (let* ((load-suffixes save-load-suffixes)
  302. (release (org-release))
  303. (git-version (org-git-version))
  304. (version (format "Org-mode version %s (%s @ %s)"
  305. release
  306. git-version
  307. (if org-install-dir
  308. (if (string= org-dir org-install-dir)
  309. org-install-dir
  310. (concat "mixed installation! "
  311. org-install-dir
  312. " and "
  313. org-dir))
  314. "org-loaddefs.el can not be found!")))
  315. (version1 (if full version release)))
  316. (when here (insert version1))
  317. (when message (message "%s" version1))
  318. version1)))
  319. (defconst org-version (org-version))
  320. ;;; Syntax Constants
  321. ;;;; Block
  322. (defconst org-block-regexp
  323. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  324. "Regular expression for hiding blocks.")
  325. (defconst org-dblock-start-re
  326. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  327. "Matches the start line of a dynamic block, with parameters.")
  328. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  329. "Matches the end of a dynamic block.")
  330. ;;;; Clock and Planning
  331. (defconst org-clock-string "CLOCK:"
  332. "String used as prefix for timestamps clocking work hours on an item.")
  333. (defvar org-closed-string "CLOSED:"
  334. "String used as the prefix for timestamps logging closing a TODO entry.")
  335. (defvar org-deadline-string "DEADLINE:"
  336. "String to mark deadline entries.
  337. A deadline is this string, followed by a time stamp. Should be a word,
  338. terminated by a colon. You can insert a schedule keyword and
  339. a timestamp with \\[org-deadline].")
  340. (defvar org-scheduled-string "SCHEDULED:"
  341. "String to mark scheduled TODO entries.
  342. A schedule is this string, followed by a time stamp. Should be a word,
  343. terminated by a colon. You can insert a schedule keyword and
  344. a timestamp with \\[org-schedule].")
  345. (defconst org-ds-keyword-length
  346. (+ 2
  347. (apply #'max
  348. (mapcar #'length
  349. (list org-deadline-string org-scheduled-string
  350. org-clock-string org-closed-string))))
  351. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  352. (defconst org-planning-line-re
  353. (concat "^[ \t]*"
  354. (regexp-opt
  355. (list org-closed-string org-deadline-string org-scheduled-string)
  356. t))
  357. "Matches a line with planning info.
  358. Matched keyword is in group 1.")
  359. (defconst org-clock-line-re
  360. (concat "^[ \t]*" org-clock-string)
  361. "Matches a line with clock info.")
  362. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  363. "Matches the DEADLINE keyword.")
  364. (defconst org-deadline-time-regexp
  365. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  366. "Matches the DEADLINE keyword together with a time stamp.")
  367. (defconst org-deadline-time-hour-regexp
  368. (concat "\\<" org-deadline-string
  369. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  370. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  371. (defconst org-deadline-line-regexp
  372. (concat "\\<\\(" org-deadline-string "\\).*")
  373. "Matches the DEADLINE keyword and the rest of the line.")
  374. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  375. "Matches the SCHEDULED keyword.")
  376. (defconst org-scheduled-time-regexp
  377. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  378. "Matches the SCHEDULED keyword together with a time stamp.")
  379. (defconst org-scheduled-time-hour-regexp
  380. (concat "\\<" org-scheduled-string
  381. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  382. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  383. (defconst org-closed-time-regexp
  384. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  385. "Matches the CLOSED keyword together with a time stamp.")
  386. (defconst org-keyword-time-regexp
  387. (concat "\\<"
  388. (regexp-opt
  389. (list org-scheduled-string org-deadline-string org-closed-string
  390. org-clock-string)
  391. t)
  392. " *[[<]\\([^]>]+\\)[]>]")
  393. "Matches any of the 4 keywords, together with the time stamp.")
  394. (defconst org-keyword-time-not-clock-regexp
  395. (concat
  396. "\\<"
  397. (regexp-opt
  398. (list org-scheduled-string org-deadline-string org-closed-string) t)
  399. " *[[<]\\([^]>]+\\)[]>]")
  400. "Matches any of the 3 keywords, together with the time stamp.")
  401. (defconst org-maybe-keyword-time-regexp
  402. (concat "\\(\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string
  405. org-clock-string)
  406. t)
  407. "\\)?"
  408. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  409. "\\|"
  410. "<%%([^\r\n>]*>\\)")
  411. "Matches a timestamp, possibly preceded by a keyword.")
  412. (defconst org-all-time-keywords
  413. (mapcar (lambda (w) (substring w 0 -1))
  414. (list org-scheduled-string org-deadline-string
  415. org-clock-string org-closed-string))
  416. "List of time keywords.")
  417. ;;;; Drawer
  418. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  419. "Matches first or last line of a hidden block.
  420. Group 1 contains drawer's name or \"END\".")
  421. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  422. "Regular expression matching the first line of a property drawer.")
  423. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  424. "Regular expression matching the last line of a property drawer.")
  425. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  426. "Regular expression matching the first line of a clock drawer.")
  427. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  428. "Regular expression matching the last line of a clock drawer.")
  429. (defconst org-property-drawer-re
  430. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  431. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  432. "[ \t]*:END:[ \t]*$")
  433. "Matches an entire property drawer.")
  434. (defconst org-clock-drawer-re
  435. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  436. org-clock-drawer-end-re "\\)\n?")
  437. "Matches an entire clock drawer.")
  438. ;;;; Headline
  439. (defconst org-heading-keyword-regexp-format
  440. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  441. "Printf format for a regexp matching a headline with some keyword.
  442. This regexp will match the headline of any node which has the
  443. exact keyword that is put into the format. The keyword isn't in
  444. any group by default, but the stars and the body are.")
  445. (defconst org-heading-keyword-maybe-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline, possibly with some keyword.
  448. This regexp can match any headline with the specified keyword, or
  449. without a keyword. The keyword isn't in any group by default,
  450. but the stars and the body are.")
  451. (defconst org-archive-tag "ARCHIVE"
  452. "The tag that marks a subtree as archived.
  453. An archived subtree does not open during visibility cycling, and does
  454. not contribute to the agenda listings.")
  455. (defconst org-comment-string "COMMENT"
  456. "Entries starting with this keyword will never be exported.
  457. An entry can be toggled between COMMENT and normal with
  458. \\[org-toggle-comment].")
  459. ;;;; LaTeX Environments and Fragments
  460. (defconst org-latex-regexps
  461. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  462. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  463. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  464. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  465. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  466. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  467. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  468. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  469. "Regular expressions for matching embedded LaTeX.")
  470. ;;;; Node Property
  471. (defconst org-effort-property "Effort"
  472. "The property that is being used to keep track of effort estimates.
  473. Effort estimates given in this property need to have the format H:MM.")
  474. ;;;; Table
  475. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  476. "Detect an org-type or table-type table.")
  477. (defconst org-table-line-regexp "^[ \t]*|"
  478. "Detect an org-type table line.")
  479. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  480. "Detect an org-type table line.")
  481. (defconst org-table-hline-regexp "^[ \t]*|-"
  482. "Detect an org-type table hline.")
  483. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  484. "Detect a table-type table hline.")
  485. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  486. "Detect the first line outside a table when searching from within it.
  487. This works for both table types.")
  488. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  489. "Detect a #+TBLFM line.")
  490. ;;;; Timestamp
  491. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  492. "Regular expression for fast time stamp matching.")
  493. (defconst org-ts-regexp-inactive
  494. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  495. "Regular expression for fast inactive time stamp matching.")
  496. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  497. "Regular expression for fast time stamp matching.")
  498. (defconst org-ts-regexp0
  499. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  500. "Regular expression matching time strings for analysis.
  501. This one does not require the space after the date, so it can be used
  502. on a string that terminates immediately after the date.")
  503. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  504. "Regular expression matching time strings for analysis.")
  505. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  506. "Regular expression matching time stamps, with groups.")
  507. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  508. "Regular expression matching time stamps (also [..]), with groups.")
  509. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  510. "Regular expression matching a time stamp range.")
  511. (defconst org-tr-regexp-both
  512. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  513. "Regular expression matching a time stamp range.")
  514. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  515. org-ts-regexp "\\)?")
  516. "Regular expression matching a time stamp or time stamp range.")
  517. (defconst org-tsr-regexp-both
  518. (concat org-ts-regexp-both "\\(--?-?"
  519. org-ts-regexp-both "\\)?")
  520. "Regular expression matching a time stamp or time stamp range.
  521. The time stamps may be either active or inactive.")
  522. (defconst org-repeat-re
  523. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  524. "Regular expression for specifying repeated events.
  525. After a match, group 1 contains the repeat expression.")
  526. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  527. "Formats for `format-time-string' which are used for time stamps.")
  528. ;;; The custom variables
  529. (defgroup org nil
  530. "Outline-based notes management and organizer."
  531. :tag "Org"
  532. :group 'outlines
  533. :group 'calendar)
  534. (defcustom org-mode-hook nil
  535. "Mode hook for Org-mode, run after the mode was turned on."
  536. :group 'org
  537. :type 'hook)
  538. (defcustom org-load-hook nil
  539. "Hook that is run after org.el has been loaded."
  540. :group 'org
  541. :type 'hook)
  542. (defcustom org-log-buffer-setup-hook nil
  543. "Hook that is run after an Org log buffer is created."
  544. :group 'org
  545. :version "24.1"
  546. :type 'hook)
  547. (defvar org-modules) ; defined below
  548. (defvar org-modules-loaded nil
  549. "Have the modules been loaded already?")
  550. (defun org-load-modules-maybe (&optional force)
  551. "Load all extensions listed in `org-modules'."
  552. (when (or force (not org-modules-loaded))
  553. (dolist (ext org-modules)
  554. (condition-case nil (require ext)
  555. (error (message "Problems while trying to load feature `%s'" ext))))
  556. (setq org-modules-loaded t)))
  557. (defun org-set-modules (var value)
  558. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  559. (set var value)
  560. (when (featurep 'org)
  561. (org-load-modules-maybe 'force)
  562. (org-element-cache-reset 'all)))
  563. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  564. "Modules that should always be loaded together with org.el.
  565. If a description starts with <C>, the file is not part of Emacs
  566. and loading it will require that you have downloaded and properly
  567. installed the Org mode distribution.
  568. You can also use this system to load external packages (i.e. neither Org
  569. core modules, nor modules from the CONTRIB directory). Just add symbols
  570. to the end of the list. If the package is called org-xyz.el, then you need
  571. to add the symbol `xyz', and the package must have a call to:
  572. (provide \\='org-xyz)
  573. For export specific modules, see also `org-export-backends'."
  574. :group 'org
  575. :set 'org-set-modules
  576. :version "24.4"
  577. :package-version '(Org . "8.0")
  578. :type
  579. '(set :greedy t
  580. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  581. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  582. (const :tag " crypt: Encryption of subtrees" org-crypt)
  583. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  584. (const :tag " docview: Links to doc-view buffers" org-docview)
  585. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  586. (const :tag " habit: Track your consistency with habits" org-habit)
  587. (const :tag " id: Global IDs for identifying entries" org-id)
  588. (const :tag " info: Links to Info nodes" org-info)
  589. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  590. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  591. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  592. (const :tag " mouse: Additional mouse support" org-mouse)
  593. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  594. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  595. (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
  596. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  597. (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
  598. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  599. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  600. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  601. (const :tag "C collector: Collect properties into tables" org-collector)
  602. (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  603. (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
  604. (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
  605. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  606. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  607. (const :tag "C eval: Include command output as text" org-eval)
  608. (const :tag "C eww: Store link to url of eww" org-eww)
  609. (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
  610. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  611. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  612. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  613. (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
  614. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  615. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  616. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  617. (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
  618. (const :tag "C man: Support for links to manpages in Org-mode" org-man)
  619. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  620. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  621. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  622. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  623. (const :tag "C registry: A registry for Org-mode links" org-registry)
  624. (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
  625. (const :tag "C secretary: Team management with org-mode" org-secretary)
  626. (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
  627. (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
  628. (const :tag "C track: Keep up with Org-mode development" org-track)
  629. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  630. (const :tag "C vm: Links to VM folders/messages" org-vm)
  631. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  632. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  633. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  634. (defvar org-export-registered-backends) ; From ox.el.
  635. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  636. (declare-function org-export-backend-name "ox" (backend) t)
  637. (defcustom org-export-backends '(ascii html icalendar latex odt)
  638. "List of export back-ends that should be always available.
  639. If a description starts with <C>, the file is not part of Emacs
  640. and loading it will require that you have downloaded and properly
  641. installed the Org mode distribution.
  642. Unlike to `org-modules', libraries in this list will not be
  643. loaded along with Org, but only once the export framework is
  644. needed.
  645. This variable needs to be set before org.el is loaded. If you
  646. need to make a change while Emacs is running, use the customize
  647. interface or run the following code, where VAL stands for the new
  648. value of the variable, after updating it:
  649. (progn
  650. (setq org-export-registered-backends
  651. (cl-remove-if-not
  652. (lambda (backend)
  653. (let ((name (org-export-backend-name backend)))
  654. (or (memq name val)
  655. (catch \\='parentp
  656. (dolist (b val)
  657. (and (org-export-derived-backend-p b name)
  658. (throw \\='parentp t)))))))
  659. org-export-registered-backends))
  660. (let ((new-list (mapcar #\\='org-export-backend-name
  661. org-export-registered-backends)))
  662. (dolist (backend val)
  663. (cond
  664. ((not (load (format \"ox-%s\" backend) t t))
  665. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  666. backend))
  667. ((not (memq backend new-list)) (push backend new-list))))
  668. (set-default \\='org-export-backends new-list)))
  669. Adding a back-end to this list will also pull the back-end it
  670. depends on, if any."
  671. :group 'org
  672. :group 'org-export
  673. :version "25.1"
  674. :package-version '(Org . "9.0")
  675. :initialize 'custom-initialize-set
  676. :set (lambda (var val)
  677. (if (not (featurep 'ox)) (set-default var val)
  678. ;; Any back-end not required anymore (not present in VAL and not
  679. ;; a parent of any back-end in the new value) is removed from the
  680. ;; list of registered back-ends.
  681. (setq org-export-registered-backends
  682. (cl-remove-if-not
  683. (lambda (backend)
  684. (let ((name (org-export-backend-name backend)))
  685. (or (memq name val)
  686. (catch 'parentp
  687. (dolist (b val)
  688. (and (org-export-derived-backend-p b name)
  689. (throw 'parentp t)))))))
  690. org-export-registered-backends))
  691. ;; Now build NEW-LIST of both new back-ends and required
  692. ;; parents.
  693. (let ((new-list (mapcar #'org-export-backend-name
  694. org-export-registered-backends)))
  695. (dolist (backend val)
  696. (cond
  697. ((not (load (format "ox-%s" backend) t t))
  698. (message "Problems while trying to load export back-end `%s'"
  699. backend))
  700. ((not (memq backend new-list)) (push backend new-list))))
  701. ;; Set VAR to that list with fixed dependencies.
  702. (set-default var new-list))))
  703. :type '(set :greedy t
  704. (const :tag " ascii Export buffer to ASCII format" ascii)
  705. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  706. (const :tag " html Export buffer to HTML format" html)
  707. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  708. (const :tag " latex Export buffer to LaTeX format" latex)
  709. (const :tag " man Export buffer to MAN format" man)
  710. (const :tag " md Export buffer to Markdown format" md)
  711. (const :tag " odt Export buffer to ODT format" odt)
  712. (const :tag " org Export buffer to Org format" org)
  713. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  714. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  715. (const :tag "C deck Export buffer to deck.js presentations" deck)
  716. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  717. (const :tag "C groff Export buffer to Groff format" groff)
  718. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  719. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  720. (const :tag "C s5 Export buffer to s5 presentations" s5)
  721. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  722. (eval-after-load 'ox
  723. '(dolist (backend org-export-backends)
  724. (condition-case nil (require (intern (format "ox-%s" backend)))
  725. (error (message "Problems while trying to load export back-end `%s'"
  726. backend)))))
  727. (defcustom org-support-shift-select nil
  728. "Non-nil means make shift-cursor commands select text when possible.
  729. \\<org-mode-map>\
  730. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  731. start selecting a region, or enlarge regions started in this way.
  732. In Org-mode, in special contexts, these same keys are used for
  733. other purposes, important enough to compete with shift selection.
  734. Org tries to balance these needs by supporting `shift-select-mode'
  735. outside these special contexts, under control of this variable.
  736. The default of this variable is nil, to avoid confusing behavior. Shifted
  737. cursor keys will then execute Org commands in the following contexts:
  738. - on a headline, changing TODO state (left/right) and priority (up/down)
  739. - on a time stamp, changing the time
  740. - in a plain list item, changing the bullet type
  741. - in a property definition line, switching between allowed values
  742. - in the BEGIN line of a clock table (changing the time block).
  743. Outside these contexts, the commands will throw an error.
  744. When this variable is t and the cursor is not in a special
  745. context, Org-mode will support shift-selection for making and
  746. enlarging regions. To make this more effective, the bullet
  747. cycling will no longer happen anywhere in an item line, but only
  748. if the cursor is exactly on the bullet.
  749. If you set this variable to the symbol `always', then the keys
  750. will not be special in headlines, property lines, and item lines,
  751. to make shift selection work there as well. If this is what you
  752. want, you can use the following alternative commands:
  753. `\\[org-todo]' and `\\[org-priority]' \
  754. to change TODO state and priority,
  755. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  756. can be used to switch TODO sets,
  757. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  758. and properties can be edited by hand or in column view.
  759. However, when the cursor is on a timestamp, shift-cursor commands
  760. will still edit the time stamp - this is just too good to give up."
  761. :group 'org
  762. :type '(choice
  763. (const :tag "Never" nil)
  764. (const :tag "When outside special context" t)
  765. (const :tag "Everywhere except timestamps" always)))
  766. (defcustom org-loop-over-headlines-in-active-region nil
  767. "Shall some commands act upon headlines in the active region?
  768. When set to t, some commands will be performed in all headlines
  769. within the active region.
  770. When set to `start-level', some commands will be performed in all
  771. headlines within the active region, provided that these headlines
  772. are of the same level than the first one.
  773. When set to a string, those commands will be performed on the
  774. matching headlines within the active region. Such string must be
  775. a tags/property/todo match as it is used in the agenda tags view.
  776. The list of commands is: `org-schedule', `org-deadline',
  777. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  778. `org-archive-to-archive-sibling'. The archiving commands skip
  779. already archived entries."
  780. :type '(choice (const :tag "Don't loop" nil)
  781. (const :tag "All headlines in active region" t)
  782. (const :tag "In active region, headlines at the same level than the first one" start-level)
  783. (string :tag "Tags/Property/Todo matcher"))
  784. :version "24.1"
  785. :group 'org-todo
  786. :group 'org-archive)
  787. (defgroup org-startup nil
  788. "Options concerning startup of Org-mode."
  789. :tag "Org Startup"
  790. :group 'org)
  791. (defcustom org-startup-folded t
  792. "Non-nil means entering Org-mode will switch to OVERVIEW.
  793. This can also be configured on a per-file basis by adding one of
  794. the following lines anywhere in the buffer:
  795. #+STARTUP: fold (or `overview', this is equivalent)
  796. #+STARTUP: nofold (or `showall', this is equivalent)
  797. #+STARTUP: content
  798. #+STARTUP: showeverything
  799. By default, this option is ignored when Org opens agenda files
  800. for the first time. If you want the agenda to honor the startup
  801. option, set `org-agenda-inhibit-startup' to nil."
  802. :group 'org-startup
  803. :type '(choice
  804. (const :tag "nofold: show all" nil)
  805. (const :tag "fold: overview" t)
  806. (const :tag "content: all headlines" content)
  807. (const :tag "show everything, even drawers" showeverything)))
  808. (defcustom org-startup-truncated t
  809. "Non-nil means entering Org-mode will set `truncate-lines'.
  810. This is useful since some lines containing links can be very long and
  811. uninteresting. Also tables look terrible when wrapped.
  812. The variable `org-startup-truncated' allows to configure
  813. truncation for Org mode different to the other modes that use the
  814. variable `truncate-lines' and as a shortcut instead of putting
  815. the variable `truncate-lines' into the `org-mode-hook'. If one
  816. wants to configure truncation for Org mode not statically but
  817. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  818. the variable `truncate-lines' has to be used because in such a
  819. case it is too late to set the variable `org-startup-truncated'."
  820. :group 'org-startup
  821. :type 'boolean)
  822. (defcustom org-startup-indented nil
  823. "Non-nil means turn on `org-indent-mode' on startup.
  824. This can also be configured on a per-file basis by adding one of
  825. the following lines anywhere in the buffer:
  826. #+STARTUP: indent
  827. #+STARTUP: noindent"
  828. :group 'org-structure
  829. :type '(choice
  830. (const :tag "Not" nil)
  831. (const :tag "Globally (slow on startup in large files)" t)))
  832. (defcustom org-use-sub-superscripts t
  833. "Non-nil means interpret \"_\" and \"^\" for display.
  834. If you want to control how Org exports those characters, see
  835. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  836. used to be an alias for `org-export-with-sub-superscripts' in
  837. Org <8.0, it is not anymore.
  838. When this option is turned on, you can use TeX-like syntax for
  839. sub- and superscripts within the buffer. Several characters after
  840. \"_\" or \"^\" will be considered as a single item - so grouping
  841. with {} is normally not needed. For example, the following things
  842. will be parsed as single sub- or superscripts:
  843. 10^24 or 10^tau several digits will be considered 1 item.
  844. 10^-12 or 10^-tau a leading sign with digits or a word
  845. x^2-y^3 will be read as x^2 - y^3, because items are
  846. terminated by almost any nonword/nondigit char.
  847. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  848. Still, ambiguity is possible. So when in doubt, use {} to enclose
  849. the sub/superscript. If you set this variable to the symbol `{}',
  850. the braces are *required* in order to trigger interpretations as
  851. sub/superscript. This can be helpful in documents that need \"_\"
  852. frequently in plain text."
  853. :group 'org-startup
  854. :version "24.4"
  855. :package-version '(Org . "8.0")
  856. :type '(choice
  857. (const :tag "Always interpret" t)
  858. (const :tag "Only with braces" {})
  859. (const :tag "Never interpret" nil)))
  860. (defcustom org-startup-with-beamer-mode nil
  861. "Non-nil means turn on `org-beamer-mode' on startup.
  862. This can also be configured on a per-file basis by adding one of
  863. the following lines anywhere in the buffer:
  864. #+STARTUP: beamer"
  865. :group 'org-startup
  866. :version "24.1"
  867. :type 'boolean)
  868. (defcustom org-startup-align-all-tables nil
  869. "Non-nil means align all tables when visiting a file.
  870. This is useful when the column width in tables is forced with <N> cookies
  871. in table fields. Such tables will look correct only after the first re-align.
  872. This can also be configured on a per-file basis by adding one of
  873. the following lines anywhere in the buffer:
  874. #+STARTUP: align
  875. #+STARTUP: noalign"
  876. :group 'org-startup
  877. :type 'boolean)
  878. (defcustom org-startup-with-inline-images nil
  879. "Non-nil means show inline images when loading a new Org file.
  880. This can also be configured on a per-file basis by adding one of
  881. the following lines anywhere in the buffer:
  882. #+STARTUP: inlineimages
  883. #+STARTUP: noinlineimages"
  884. :group 'org-startup
  885. :version "24.1"
  886. :type 'boolean)
  887. (defcustom org-startup-with-latex-preview nil
  888. "Non-nil means preview LaTeX fragments when loading a new Org file.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: latexpreview
  892. #+STARTUP: nolatexpreview"
  893. :group 'org-startup
  894. :version "24.4"
  895. :package-version '(Org . "8.0")
  896. :type 'boolean)
  897. (defcustom org-insert-mode-line-in-empty-file nil
  898. "Non-nil means insert the first line setting Org-mode in empty files.
  899. When the function `org-mode' is called interactively in an empty file, this
  900. normally means that the file name does not automatically trigger Org-mode.
  901. To ensure that the file will always be in Org-mode in the future, a
  902. line enforcing Org-mode will be inserted into the buffer, if this option
  903. has been set."
  904. :group 'org-startup
  905. :type 'boolean)
  906. (defcustom org-replace-disputed-keys nil
  907. "Non-nil means use alternative key bindings for some keys.
  908. Org-mode uses S-<cursor> keys for changing timestamps and priorities.
  909. These keys are also used by other packages like shift-selection-mode'
  910. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  911. If you want to use Org-mode together with one of these other modes,
  912. or more generally if you would like to move some Org-mode commands to
  913. other keys, set this variable and configure the keys with the variable
  914. `org-disputed-keys'.
  915. This option is only relevant at load-time of Org-mode, and must be set
  916. *before* org.el is loaded. Changing it requires a restart of Emacs to
  917. become effective."
  918. :group 'org-startup
  919. :type 'boolean)
  920. (defcustom org-use-extra-keys nil
  921. "Non-nil means use extra key sequence definitions for certain commands.
  922. This happens automatically if `window-system' is nil. This
  923. variable lets you do the same manually. You must set it before
  924. loading Org."
  925. :group 'org-startup
  926. :type 'boolean)
  927. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  928. (defcustom org-disputed-keys
  929. '(([(shift up)] . [(meta p)])
  930. ([(shift down)] . [(meta n)])
  931. ([(shift left)] . [(meta -)])
  932. ([(shift right)] . [(meta +)])
  933. ([(control shift right)] . [(meta shift +)])
  934. ([(control shift left)] . [(meta shift -)]))
  935. "Keys for which Org-mode and other modes compete.
  936. This is an alist, cars are the default keys, second element specifies
  937. the alternative to use when `org-replace-disputed-keys' is t.
  938. Keys can be specified in any syntax supported by `define-key'.
  939. The value of this option takes effect only at Org-mode's startup,
  940. therefore you'll have to restart Emacs to apply it after changing."
  941. :group 'org-startup
  942. :type 'alist)
  943. (defun org-key (key)
  944. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  945. Or return the original if not disputed."
  946. (when org-replace-disputed-keys
  947. (let* ((nkey (key-description key))
  948. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  949. org-disputed-keys)))
  950. (setq key (if x (cdr x) key))))
  951. key)
  952. (defun org-defkey (keymap key def)
  953. "Define a key, possibly translated, as returned by `org-key'."
  954. (define-key keymap (org-key key) def))
  955. (defcustom org-ellipsis nil
  956. "The ellipsis to use in the Org-mode outline.
  957. When nil, just use the standard three dots.
  958. When a string, use that string instead.
  959. When a face, use the standard 3 dots, but with the specified face.
  960. The change affects only Org-mode (which will then use its own display table).
  961. Changing this requires executing \\[org-mode] in a buffer to become
  962. effective."
  963. :group 'org-startup
  964. :type '(choice (const :tag "Default" nil)
  965. (face :tag "Face" :value org-warning)
  966. (string :tag "String" :value "...#")))
  967. (defvar org-display-table nil
  968. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  969. (defgroup org-keywords nil
  970. "Keywords in Org-mode."
  971. :tag "Org Keywords"
  972. :group 'org)
  973. (defcustom org-closed-keep-when-no-todo nil
  974. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  975. :group 'org-todo
  976. :group 'org-keywords
  977. :version "24.4"
  978. :package-version '(Org . "8.0")
  979. :type 'boolean)
  980. (defgroup org-structure nil
  981. "Options concerning the general structure of Org-mode files."
  982. :tag "Org Structure"
  983. :group 'org)
  984. (defgroup org-reveal-location nil
  985. "Options about how to make context of a location visible."
  986. :tag "Org Reveal Location"
  987. :group 'org-structure)
  988. (defcustom org-show-context-detail '((agenda . local)
  989. (bookmark-jump . lineage)
  990. (isearch . lineage)
  991. (default . ancestors))
  992. "Alist between context and visibility span when revealing a location.
  993. \\<org-mode-map>Some actions may move point into invisible
  994. locations. As a consequence, Org always expose a neighborhood
  995. around point. How much is shown depends on the initial action,
  996. or context. Valid contexts are
  997. agenda when exposing an entry from the agenda
  998. org-goto when using the command `org-goto' (\\[org-goto])
  999. occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
  1000. tags-tree when constructing a sparse tree based on tags matches
  1001. link-search when exposing search matches associated with a link
  1002. mark-goto when exposing the jump goal of a mark
  1003. bookmark-jump when exposing a bookmark location
  1004. isearch when exiting from an incremental search
  1005. default default for all contexts not set explicitly
  1006. Allowed visibility spans are
  1007. minimal show current headline; if point is not on headline,
  1008. also show entry
  1009. local show current headline, entry and next headline
  1010. ancestors show current headline and its direct ancestors; if
  1011. point is not on headline, also show entry
  1012. lineage show current headline, its direct ancestors and all
  1013. their children; if point is not on headline, also show
  1014. entry and first child
  1015. tree show current headline, its direct ancestors and all
  1016. their children; if point is not on headline, also show
  1017. entry and all children
  1018. canonical show current headline, its direct ancestors along with
  1019. their entries and children; if point is not located on
  1020. the headline, also show current entry and all children
  1021. As special cases, a nil or t value means show all contexts in
  1022. `minimal' or `canonical' view, respectively.
  1023. Some views can make displayed information very compact, but also
  1024. make it harder to edit the location of the match. In such
  1025. a case, use the command `org-reveal' (\\[org-reveal]) to show
  1026. more context."
  1027. :group 'org-reveal-location
  1028. :version "25.2"
  1029. :package-version '(Org . "9.0")
  1030. :type '(choice
  1031. (const :tag "Canonical" t)
  1032. (const :tag "Minimal" nil)
  1033. (repeat :greedy t :tag "Individual contexts"
  1034. (cons
  1035. (choice :tag "Context"
  1036. (const agenda)
  1037. (const org-goto)
  1038. (const occur-tree)
  1039. (const tags-tree)
  1040. (const link-search)
  1041. (const mark-goto)
  1042. (const bookmark-jump)
  1043. (const isearch)
  1044. (const default))
  1045. (choice :tag "Detail level"
  1046. (const minimal)
  1047. (const local)
  1048. (const ancestors)
  1049. (const lineage)
  1050. (const tree)
  1051. (const canonical))))))
  1052. (defcustom org-indirect-buffer-display 'other-window
  1053. "How should indirect tree buffers be displayed?
  1054. This applies to indirect buffers created with the commands
  1055. \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
  1056. Valid values are:
  1057. current-window Display in the current window
  1058. other-window Just display in another window.
  1059. dedicated-frame Create one new frame, and re-use it each time.
  1060. new-frame Make a new frame each time. Note that in this case
  1061. previously-made indirect buffers are kept, and you need to
  1062. kill these buffers yourself."
  1063. :group 'org-structure
  1064. :group 'org-agenda-windows
  1065. :type '(choice
  1066. (const :tag "In current window" current-window)
  1067. (const :tag "In current frame, other window" other-window)
  1068. (const :tag "Each time a new frame" new-frame)
  1069. (const :tag "One dedicated frame" dedicated-frame)))
  1070. (defcustom org-use-speed-commands nil
  1071. "Non-nil means activate single letter commands at beginning of a headline.
  1072. This may also be a function to test for appropriate locations where speed
  1073. commands should be active.
  1074. For example, to activate speed commands when the point is on any
  1075. star at the beginning of the headline, you can do this:
  1076. (setq org-use-speed-commands
  1077. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1078. :group 'org-structure
  1079. :type '(choice
  1080. (const :tag "Never" nil)
  1081. (const :tag "At beginning of headline stars" t)
  1082. (function)))
  1083. (defcustom org-speed-commands-user nil
  1084. "Alist of additional speed commands.
  1085. This list will be checked before `org-speed-commands-default'
  1086. when the variable `org-use-speed-commands' is non-nil
  1087. and when the cursor is at the beginning of a headline.
  1088. The car if each entry is a string with a single letter, which must
  1089. be assigned to `self-insert-command' in the global map.
  1090. The cdr is either a command to be called interactively, a function
  1091. to be called, or a form to be evaluated.
  1092. An entry that is just a list with a single string will be interpreted
  1093. as a descriptive headline that will be added when listing the speed
  1094. commands in the Help buffer using the `?' speed command."
  1095. :group 'org-structure
  1096. :type '(repeat :value ("k" . ignore)
  1097. (choice :value ("k" . ignore)
  1098. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1099. (cons :tag "Letter and Command"
  1100. (string :tag "Command letter")
  1101. (choice
  1102. (function)
  1103. (sexp))))))
  1104. (defcustom org-bookmark-names-plist
  1105. '(:last-capture "org-capture-last-stored"
  1106. :last-refile "org-refile-last-stored"
  1107. :last-capture-marker "org-capture-last-stored-marker")
  1108. "Names for bookmarks automatically set by some Org commands.
  1109. This can provide strings as names for a number of bookmarks Org sets
  1110. automatically. The following keys are currently implemented:
  1111. :last-capture
  1112. :last-capture-marker
  1113. :last-refile
  1114. When a key does not show up in the property list, the corresponding bookmark
  1115. is not set."
  1116. :group 'org-structure
  1117. :type 'plist)
  1118. (defgroup org-cycle nil
  1119. "Options concerning visibility cycling in Org-mode."
  1120. :tag "Org Cycle"
  1121. :group 'org-structure)
  1122. (defcustom org-cycle-skip-children-state-if-no-children t
  1123. "Non-nil means skip CHILDREN state in entries that don't have any."
  1124. :group 'org-cycle
  1125. :type 'boolean)
  1126. (defcustom org-cycle-max-level nil
  1127. "Maximum level which should still be subject to visibility cycling.
  1128. Levels higher than this will, for cycling, be treated as text, not a headline.
  1129. When `org-odd-levels-only' is set, a value of N in this variable actually
  1130. means 2N-1 stars as the limiting headline.
  1131. When nil, cycle all levels.
  1132. Note that the limiting level of cycling is also influenced by
  1133. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1134. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1135. than its value."
  1136. :group 'org-cycle
  1137. :type '(choice
  1138. (const :tag "No limit" nil)
  1139. (integer :tag "Maximum level")))
  1140. (defcustom org-hide-block-startup nil
  1141. "Non-nil means entering Org-mode will fold all blocks.
  1142. This can also be set in on a per-file basis with
  1143. #+STARTUP: hideblocks
  1144. #+STARTUP: showblocks"
  1145. :group 'org-startup
  1146. :group 'org-cycle
  1147. :type 'boolean)
  1148. (defcustom org-cycle-global-at-bob nil
  1149. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1150. This makes it possible to do global cycling without having to use S-TAB or
  1151. \\[universal-argument] TAB. For this special case to work, the first line
  1152. of the buffer must not be a headline -- it may be empty or some other text.
  1153. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1154. sure the cursor stays at the beginning of the buffer. When this option is
  1155. nil, don't do anything special at the beginning of the buffer."
  1156. :group 'org-cycle
  1157. :type 'boolean)
  1158. (defcustom org-cycle-level-after-item/entry-creation t
  1159. "Non-nil means cycle entry level or item indentation in new empty entries.
  1160. When the cursor is at the end of an empty headline, i.e., with only stars
  1161. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1162. and then all possible ancestor states, before returning to the original state.
  1163. This makes data entry extremely fast: M-RET to create a new headline,
  1164. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1165. When the cursor is at the end of an empty plain list item, one TAB will
  1166. make it a subitem, two or more tabs will back up to make this an item
  1167. higher up in the item hierarchy."
  1168. :group 'org-cycle
  1169. :type 'boolean)
  1170. (defcustom org-cycle-emulate-tab t
  1171. "Where should `org-cycle' emulate TAB.
  1172. nil Never
  1173. white Only in completely white lines
  1174. whitestart Only at the beginning of lines, before the first non-white char
  1175. t Everywhere except in headlines
  1176. exc-hl-bol Everywhere except at the start of a headline
  1177. If TAB is used in a place where it does not emulate TAB, the current subtree
  1178. visibility is cycled."
  1179. :group 'org-cycle
  1180. :type '(choice (const :tag "Never" nil)
  1181. (const :tag "Only in completely white lines" white)
  1182. (const :tag "Before first char in a line" whitestart)
  1183. (const :tag "Everywhere except in headlines" t)
  1184. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1185. (defcustom org-cycle-separator-lines 2
  1186. "Number of empty lines needed to keep an empty line between collapsed trees.
  1187. If you leave an empty line between the end of a subtree and the following
  1188. headline, this empty line is hidden when the subtree is folded.
  1189. Org-mode will leave (exactly) one empty line visible if the number of
  1190. empty lines is equal or larger to the number given in this variable.
  1191. So the default 2 means at least 2 empty lines after the end of a subtree
  1192. are needed to produce free space between a collapsed subtree and the
  1193. following headline.
  1194. If the number is negative, and the number of empty lines is at least -N,
  1195. all empty lines are shown.
  1196. Special case: when 0, never leave empty lines in collapsed view."
  1197. :group 'org-cycle
  1198. :type 'integer)
  1199. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1200. (defcustom org-pre-cycle-hook nil
  1201. "Hook that is run before visibility cycling is happening.
  1202. The function(s) in this hook must accept a single argument which indicates
  1203. the new state that will be set right after running this hook. The
  1204. argument is a symbol. Before a global state change, it can have the values
  1205. `overview', `content', or `all'. Before a local state change, it can have
  1206. the values `folded', `children', or `subtree'."
  1207. :group 'org-cycle
  1208. :type 'hook)
  1209. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1210. org-cycle-hide-drawers
  1211. org-cycle-show-empty-lines
  1212. org-optimize-window-after-visibility-change)
  1213. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1214. The function(s) in this hook must accept a single argument which indicates
  1215. the new state that was set by the most recent `org-cycle' command. The
  1216. argument is a symbol. After a global state change, it can have the values
  1217. `overview', `contents', or `all'. After a local state change, it can have
  1218. the values `folded', `children', or `subtree'."
  1219. :group 'org-cycle
  1220. :type 'hook
  1221. :version "25.1"
  1222. :package-version '(Org . "8.3"))
  1223. (defgroup org-edit-structure nil
  1224. "Options concerning structure editing in Org-mode."
  1225. :tag "Org Edit Structure"
  1226. :group 'org-structure)
  1227. (defcustom org-odd-levels-only nil
  1228. "Non-nil means skip even levels and only use odd levels for the outline.
  1229. This has the effect that two stars are being added/taken away in
  1230. promotion/demotion commands. It also influences how levels are
  1231. handled by the exporters.
  1232. Changing it requires restart of `font-lock-mode' to become effective
  1233. for fontification also in regions already fontified.
  1234. You may also set this on a per-file basis by adding one of the following
  1235. lines to the buffer:
  1236. #+STARTUP: odd
  1237. #+STARTUP: oddeven"
  1238. :group 'org-edit-structure
  1239. :group 'org-appearance
  1240. :type 'boolean)
  1241. (defcustom org-adapt-indentation t
  1242. "Non-nil means adapt indentation to outline node level.
  1243. When this variable is set, Org assumes that you write outlines by
  1244. indenting text in each node to align with the headline (after the
  1245. stars). The following issues are influenced by this variable:
  1246. - The indentation is increased by one space in a demotion
  1247. command, and decreased by one in a promotion command. However,
  1248. in the latter case, if shifting some line in the entry body
  1249. would alter document structure (e.g., insert a new headline),
  1250. indentation is not changed at all.
  1251. - Property drawers and planning information is inserted indented
  1252. when this variable is set. When nil, they will not be indented.
  1253. - TAB indents a line relative to current level. The lines below
  1254. a headline will be indented when this variable is set.
  1255. Note that this is all about true indentation, by adding and
  1256. removing space characters. See also `org-indent.el' which does
  1257. level-dependent indentation in a virtual way, i.e. at display
  1258. time in Emacs."
  1259. :group 'org-edit-structure
  1260. :type 'boolean)
  1261. (defcustom org-special-ctrl-a/e nil
  1262. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1263. When t, `C-a' will bring back the cursor to the beginning of the
  1264. headline text, i.e. after the stars and after a possible TODO
  1265. keyword. In an item, this will be the position after bullet and
  1266. check-box, if any. When the cursor is already at that position,
  1267. another `C-a' will bring it to the beginning of the line.
  1268. `C-e' will jump to the end of the headline, ignoring the presence
  1269. of tags in the headline. A second `C-e' will then jump to the
  1270. true end of the line, after any tags. This also means that, when
  1271. this variable is non-nil, `C-e' also will never jump beyond the
  1272. end of the heading of a folded section, i.e. not after the
  1273. ellipses.
  1274. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1275. normally, going to the true line boundary first. Only a directly
  1276. following, identical keypress will bring the cursor to the
  1277. special positions.
  1278. This may also be a cons cell where the behavior for `C-a' and
  1279. `C-e' is set separately."
  1280. :group 'org-edit-structure
  1281. :type '(choice
  1282. (const :tag "off" nil)
  1283. (const :tag "on: after stars/bullet and before tags first" t)
  1284. (const :tag "reversed: true line boundary first" reversed)
  1285. (cons :tag "Set C-a and C-e separately"
  1286. (choice :tag "Special C-a"
  1287. (const :tag "off" nil)
  1288. (const :tag "on: after stars/bullet first" t)
  1289. (const :tag "reversed: before stars/bullet first" reversed))
  1290. (choice :tag "Special C-e"
  1291. (const :tag "off" nil)
  1292. (const :tag "on: before tags first" t)
  1293. (const :tag "reversed: after tags first" reversed)))))
  1294. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1295. (defcustom org-special-ctrl-k nil
  1296. "Non-nil means `C-k' will behave specially in headlines.
  1297. When nil, `C-k' will call the default `kill-line' command.
  1298. When t, the following will happen while the cursor is in the headline:
  1299. - When the cursor is at the beginning of a headline, kill the entire
  1300. line and possible the folded subtree below the line.
  1301. - When in the middle of the headline text, kill the headline up to the tags.
  1302. - When after the headline text, kill the tags."
  1303. :group 'org-edit-structure
  1304. :type 'boolean)
  1305. (defcustom org-ctrl-k-protect-subtree nil
  1306. "Non-nil means, do not delete a hidden subtree with C-k.
  1307. When set to the symbol `error', simply throw an error when C-k is
  1308. used to kill (part-of) a headline that has hidden text behind it.
  1309. Any other non-nil value will result in a query to the user, if it is
  1310. OK to kill that hidden subtree. When nil, kill without remorse."
  1311. :group 'org-edit-structure
  1312. :version "24.1"
  1313. :type '(choice
  1314. (const :tag "Do not protect hidden subtrees" nil)
  1315. (const :tag "Protect hidden subtrees with a security query" t)
  1316. (const :tag "Never kill a hidden subtree with C-k" error)))
  1317. (defcustom org-special-ctrl-o t
  1318. "Non-nil means, make `C-o' insert a row in tables."
  1319. :group 'org-edit-structure
  1320. :type 'boolean)
  1321. (defcustom org-catch-invisible-edits nil
  1322. "Check if in invisible region before inserting or deleting a character.
  1323. Valid values are:
  1324. nil Do not check, so just do invisible edits.
  1325. error Throw an error and do nothing.
  1326. show Make point visible, and do the requested edit.
  1327. show-and-error Make point visible, then throw an error and abort the edit.
  1328. smart Make point visible, and do insertion/deletion if it is
  1329. adjacent to visible text and the change feels predictable.
  1330. Never delete a previously invisible character or add in the
  1331. middle or right after an invisible region. Basically, this
  1332. allows insertion and backward-delete right before ellipses.
  1333. FIXME: maybe in this case we should not even show?"
  1334. :group 'org-edit-structure
  1335. :version "24.1"
  1336. :type '(choice
  1337. (const :tag "Do not check" nil)
  1338. (const :tag "Throw error when trying to edit" error)
  1339. (const :tag "Unhide, but do not do the edit" show-and-error)
  1340. (const :tag "Show invisible part and do the edit" show)
  1341. (const :tag "Be smart and do the right thing" smart)))
  1342. (defcustom org-yank-folded-subtrees t
  1343. "Non-nil means when yanking subtrees, fold them.
  1344. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1345. it starts with a heading and all other headings in it are either children
  1346. or siblings, then fold all the subtrees. However, do this only if no
  1347. text after the yank would be swallowed into a folded tree by this action."
  1348. :group 'org-edit-structure
  1349. :type 'boolean)
  1350. (defcustom org-yank-adjusted-subtrees nil
  1351. "Non-nil means when yanking subtrees, adjust the level.
  1352. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1353. this function for details."
  1354. :group 'org-edit-structure
  1355. :type 'boolean)
  1356. (defcustom org-M-RET-may-split-line '((default . t))
  1357. "Non-nil means M-RET will split the line at the cursor position.
  1358. When nil, it will go to the end of the line before making a
  1359. new line.
  1360. You may also set this option in a different way for different
  1361. contexts. Valid contexts are:
  1362. headline when creating a new headline
  1363. item when creating a new item
  1364. table in a table field
  1365. default the value to be used for all contexts not explicitly
  1366. customized"
  1367. :group 'org-structure
  1368. :group 'org-table
  1369. :type '(choice
  1370. (const :tag "Always" t)
  1371. (const :tag "Never" nil)
  1372. (repeat :greedy t :tag "Individual contexts"
  1373. (cons
  1374. (choice :tag "Context"
  1375. (const headline)
  1376. (const item)
  1377. (const table)
  1378. (const default))
  1379. (boolean)))))
  1380. (defcustom org-insert-heading-respect-content nil
  1381. "Non-nil means insert new headings after the current subtree.
  1382. When nil, the new heading is created directly after the current line.
  1383. The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
  1384. this variable on for the duration of the command."
  1385. :group 'org-structure
  1386. :type 'boolean)
  1387. (defcustom org-blank-before-new-entry '((heading . auto)
  1388. (plain-list-item . auto))
  1389. "Should `org-insert-heading' leave a blank line before new heading/item?
  1390. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1391. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1392. which case Org will look at the surrounding headings/items and try to
  1393. make an intelligent decision whether to insert a blank line or not."
  1394. :group 'org-edit-structure
  1395. :type '(list
  1396. (cons (const heading)
  1397. (choice (const :tag "Never" nil)
  1398. (const :tag "Always" t)
  1399. (const :tag "Auto" auto)))
  1400. (cons (const plain-list-item)
  1401. (choice (const :tag "Never" nil)
  1402. (const :tag "Always" t)
  1403. (const :tag "Auto" auto)))))
  1404. (defcustom org-insert-heading-hook nil
  1405. "Hook being run after inserting a new heading."
  1406. :group 'org-edit-structure
  1407. :type 'hook)
  1408. (defcustom org-enable-fixed-width-editor t
  1409. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1410. This currently only means they are never auto-wrapped.
  1411. When nil, such lines will be treated like ordinary lines."
  1412. :group 'org-edit-structure
  1413. :type 'boolean)
  1414. (defcustom org-goto-auto-isearch t
  1415. "Non-nil means typing characters in `org-goto' starts incremental search.
  1416. When nil, you can use these keybindings to navigate the buffer:
  1417. q Quit the org-goto interface
  1418. n Go to the next visible heading
  1419. p Go to the previous visible heading
  1420. f Go one heading forward on same level
  1421. b Go one heading backward on same level
  1422. u Go one heading up"
  1423. :group 'org-edit-structure
  1424. :type 'boolean)
  1425. (defgroup org-sparse-trees nil
  1426. "Options concerning sparse trees in Org-mode."
  1427. :tag "Org Sparse Trees"
  1428. :group 'org-structure)
  1429. (defcustom org-highlight-sparse-tree-matches t
  1430. "Non-nil means highlight all matches that define a sparse tree.
  1431. The highlights will automatically disappear the next time the buffer is
  1432. changed by an edit command."
  1433. :group 'org-sparse-trees
  1434. :type 'boolean)
  1435. (defcustom org-remove-highlights-with-change t
  1436. "Non-nil means any change to the buffer will remove temporary highlights.
  1437. \\<org-mode-map>\
  1438. Such highlights are created by `org-occur' and `org-clock-display'.
  1439. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1440. to get rid of the highlights.
  1441. The highlights created by `org-toggle-latex-fragment' always need
  1442. `\\[org-toggle-latex-fragment]' to be removed."
  1443. :group 'org-sparse-trees
  1444. :group 'org-time
  1445. :type 'boolean)
  1446. (defcustom org-occur-case-fold-search t
  1447. "Non-nil means `org-occur' should be case-insensitive.
  1448. If set to `smart' the search will be case-insensitive only if it
  1449. doesn't specify any upper case character."
  1450. :group 'org-sparse-trees
  1451. :version "25.1"
  1452. :type '(choice
  1453. (const :tag "Case-sensitive" nil)
  1454. (const :tag "Case-insensitive" t)
  1455. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1456. (defcustom org-occur-hook '(org-first-headline-recenter)
  1457. "Hook that is run after `org-occur' has constructed a sparse tree.
  1458. This can be used to recenter the window to show as much of the structure
  1459. as possible."
  1460. :group 'org-sparse-trees
  1461. :type 'hook)
  1462. (defgroup org-imenu-and-speedbar nil
  1463. "Options concerning imenu and speedbar in Org-mode."
  1464. :tag "Org Imenu and Speedbar"
  1465. :group 'org-structure)
  1466. (defcustom org-imenu-depth 2
  1467. "The maximum level for Imenu access to Org-mode headlines.
  1468. This also applied for speedbar access."
  1469. :group 'org-imenu-and-speedbar
  1470. :type 'integer)
  1471. (defgroup org-table nil
  1472. "Options concerning tables in Org-mode."
  1473. :tag "Org Table"
  1474. :group 'org)
  1475. (defcustom org-enable-table-editor 'optimized
  1476. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1477. When nil, such lines will be treated like ordinary lines.
  1478. When equal to the symbol `optimized', the table editor will be optimized to
  1479. do the following:
  1480. - Automatic overwrite mode in front of whitespace in table fields.
  1481. This makes the structure of the table stay in tact as long as the edited
  1482. field does not exceed the column width.
  1483. - Minimize the number of realigns. Normally, the table is aligned each time
  1484. TAB or RET are pressed to move to another field. With optimization this
  1485. happens only if changes to a field might have changed the column width.
  1486. Optimization requires replacing the functions `self-insert-command',
  1487. `delete-char', and `backward-delete-char' in Org-mode buffers, with a
  1488. slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
  1489. very good at guessing when a re-align will be necessary, but you can always
  1490. force one with \\[org-ctrl-c-ctrl-c].
  1491. If you would like to use the optimized version in Org-mode, but the
  1492. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1493. This variable can be used to turn on and off the table editor during a session,
  1494. but in order to toggle optimization, a restart is required.
  1495. See also the variable `org-table-auto-blank-field'."
  1496. :group 'org-table
  1497. :type '(choice
  1498. (const :tag "off" nil)
  1499. (const :tag "on" t)
  1500. (const :tag "on, optimized" optimized)))
  1501. (defcustom org-self-insert-cluster-for-undo nil
  1502. "Non-nil means cluster self-insert commands for undo when possible.
  1503. If this is set, then, like in the Emacs command loop, 20 consecutive
  1504. characters will be undone together.
  1505. This is configurable, because there is some impact on typing performance."
  1506. :group 'org-table
  1507. :type 'boolean)
  1508. (defcustom org-table-tab-recognizes-table.el t
  1509. "Non-nil means TAB will automatically notice a table.el table.
  1510. When it sees such a table, it moves point into it and - if necessary -
  1511. calls `table-recognize-table'."
  1512. :group 'org-table-editing
  1513. :type 'boolean)
  1514. (defgroup org-link nil
  1515. "Options concerning links in Org-mode."
  1516. :tag "Org Link"
  1517. :group 'org)
  1518. (defvar-local org-link-abbrev-alist-local nil
  1519. "Buffer-local version of `org-link-abbrev-alist', which see.
  1520. The value of this is taken from the #+LINK lines.")
  1521. (defcustom org-link-abbrev-alist nil
  1522. "Alist of link abbreviations.
  1523. The car of each element is a string, to be replaced at the start of a link.
  1524. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1525. links in Org-mode buffers can have an optional tag after a double colon, e.g.
  1526. [[linkkey:tag][description]]
  1527. The `linkkey' must be a word word, starting with a letter, followed
  1528. by letters, numbers, `-' or `_'.
  1529. If REPLACE is a string, the tag will simply be appended to create the link.
  1530. If the string contains \"%s\", the tag will be inserted there. If the string
  1531. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1532. at that point (see the function `url-hexify-string'). If the string contains
  1533. the specifier \"%(my-function)\", then the custom function `my-function' will
  1534. be invoked: this function takes the tag as its only argument and must return
  1535. a string.
  1536. REPLACE may also be a function that will be called with the tag as the
  1537. only argument to create the link, which should be returned as a string.
  1538. See the manual for examples."
  1539. :group 'org-link
  1540. :type '(repeat
  1541. (cons
  1542. (string :tag "Protocol")
  1543. (choice
  1544. (string :tag "Format")
  1545. (function)))))
  1546. (defcustom org-descriptive-links t
  1547. "Non-nil means Org will display descriptive links.
  1548. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1549. \"Org Website\", hiding the link itself and just displaying its
  1550. description. When set to nil, Org will display the full links
  1551. literally.
  1552. You can interactively set the value of this variable by calling
  1553. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1554. :group 'org-link
  1555. :type 'boolean)
  1556. (defcustom org-link-file-path-type 'adaptive
  1557. "How the path name in file links should be stored.
  1558. Valid values are:
  1559. relative Relative to the current directory, i.e. the directory of the file
  1560. into which the link is being inserted.
  1561. absolute Absolute path, if possible with ~ for home directory.
  1562. noabbrev Absolute path, no abbreviation of home directory.
  1563. adaptive Use relative path for files in the current directory and sub-
  1564. directories of it. For other files, use an absolute path."
  1565. :group 'org-link
  1566. :type '(choice
  1567. (const relative)
  1568. (const absolute)
  1569. (const noabbrev)
  1570. (const adaptive)))
  1571. (defvaralias 'org-activate-links 'org-highlight-links)
  1572. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1573. "Types of links that should be highlighted in Org-mode files.
  1574. This is a list of symbols, each one of them leading to the
  1575. highlighting of a certain link type.
  1576. You can still open links that are not highlighted.
  1577. In principle, it does not hurt to turn on highlighting for all
  1578. link types. There may be a small gain when turning off unused
  1579. link types. The types are:
  1580. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1581. angle Links in angular brackets that may contain whitespace like
  1582. <bbdb:Carsten Dominik>.
  1583. plain Plain links in normal text, no whitespace, like http://google.com.
  1584. radio Text that is matched by a radio target, see manual for details.
  1585. tag Tag settings in a headline (link to tag search).
  1586. date Time stamps (link to calendar).
  1587. footnote Footnote labels.
  1588. If you set this variable during an Emacs session, use `org-mode-restart'
  1589. in the Org buffer so that the change takes effect."
  1590. :group 'org-link
  1591. :group 'org-appearance
  1592. :type '(set :greedy t
  1593. (const :tag "Double bracket links" bracket)
  1594. (const :tag "Angular bracket links" angle)
  1595. (const :tag "Plain text links" plain)
  1596. (const :tag "Radio target matches" radio)
  1597. (const :tag "Tags" tag)
  1598. (const :tag "Timestamps" date)
  1599. (const :tag "Footnotes" footnote)))
  1600. (defcustom org-make-link-description-function nil
  1601. "Function to use for generating link descriptions from links.
  1602. When nil, the link location will be used. This function must take
  1603. two parameters: the first one is the link, the second one is the
  1604. description generated by `org-insert-link'. The function should
  1605. return the description to use."
  1606. :group 'org-link
  1607. :type '(choice (const nil) (function)))
  1608. (defgroup org-link-store nil
  1609. "Options concerning storing links in Org-mode."
  1610. :tag "Org Store Link"
  1611. :group 'org-link)
  1612. (defcustom org-url-hexify-p t
  1613. "When non-nil, hexify URL when creating a link."
  1614. :type 'boolean
  1615. :version "24.3"
  1616. :group 'org-link-store)
  1617. (defcustom org-email-link-description-format "Email %c: %.30s"
  1618. "Format of the description part of a link to an email or usenet message.
  1619. The following %-escapes will be replaced by corresponding information:
  1620. %F full \"From\" field
  1621. %f name, taken from \"From\" field, address if no name
  1622. %T full \"To\" field
  1623. %t first name in \"To\" field, address if no name
  1624. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1625. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1626. %s subject
  1627. %d date
  1628. %m message-id.
  1629. You may use normal field width specification between the % and the letter.
  1630. This is for example useful to limit the length of the subject.
  1631. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1632. :group 'org-link-store
  1633. :type 'string)
  1634. (defcustom org-from-is-user-regexp
  1635. (let (r1 r2)
  1636. (when (and user-mail-address (not (string= user-mail-address "")))
  1637. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1638. (when (and user-full-name (not (string= user-full-name "")))
  1639. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1640. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1641. "Regexp matched against the \"From:\" header of an email or usenet message.
  1642. It should match if the message is from the user him/herself."
  1643. :group 'org-link-store
  1644. :type 'regexp)
  1645. (defcustom org-context-in-file-links t
  1646. "Non-nil means file links from `org-store-link' contain context.
  1647. A search string will be added to the file name with :: as separator and
  1648. used to find the context when the link is activated by the command
  1649. `org-open-at-point'. When this option is t, the entire active region
  1650. will be placed in the search string of the file link. If set to a
  1651. positive integer, only the first n lines of context will be stored.
  1652. Using a prefix arg to the command \\[org-store-link] (`org-store-link')
  1653. negates this setting for the duration of the command."
  1654. :group 'org-link-store
  1655. :type '(choice boolean integer))
  1656. (defcustom org-keep-stored-link-after-insertion nil
  1657. "Non-nil means keep link in list for entire session.
  1658. The command `org-store-link' adds a link pointing to the current
  1659. location to an internal list. These links accumulate during a session.
  1660. The command `org-insert-link' can be used to insert links into any
  1661. Org-mode file (offering completion for all stored links). When this
  1662. option is nil, every link which has been inserted once using \\[org-insert-link]
  1663. will be removed from the list, to make completing the unused links
  1664. more efficient."
  1665. :group 'org-link-store
  1666. :type 'boolean)
  1667. (defgroup org-link-follow nil
  1668. "Options concerning following links in Org-mode."
  1669. :tag "Org Follow Link"
  1670. :group 'org-link)
  1671. (defcustom org-link-translation-function nil
  1672. "Function to translate links with different syntax to Org syntax.
  1673. This can be used to translate links created for example by the Planner
  1674. or emacs-wiki packages to Org syntax.
  1675. The function must accept two parameters, a TYPE containing the link
  1676. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1677. which is everything after the link protocol. It should return a cons
  1678. with possibly modified values of type and path.
  1679. Org contains a function for this, so if you set this variable to
  1680. `org-translate-link-from-planner', you should be able follow many
  1681. links created by planner."
  1682. :group 'org-link-follow
  1683. :type '(choice (const nil) (function)))
  1684. (defcustom org-follow-link-hook nil
  1685. "Hook that is run after a link has been followed."
  1686. :group 'org-link-follow
  1687. :type 'hook)
  1688. (defcustom org-tab-follows-link nil
  1689. "Non-nil means on links TAB will follow the link.
  1690. Needs to be set before org.el is loaded.
  1691. This really should not be used, it does not make sense, and the
  1692. implementation is bad."
  1693. :group 'org-link-follow
  1694. :type 'boolean)
  1695. (defcustom org-return-follows-link nil
  1696. "Non-nil means on links RET will follow the link.
  1697. In tables, the special behavior of RET has precedence."
  1698. :group 'org-link-follow
  1699. :type 'boolean)
  1700. (defcustom org-mouse-1-follows-link
  1701. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1702. "Non-nil means mouse-1 on a link will follow the link.
  1703. A longer mouse click will still set point. Needs to be set
  1704. before org.el is loaded."
  1705. :group 'org-link-follow
  1706. :version "24.4"
  1707. :package-version '(Org . "8.3")
  1708. :type '(choice
  1709. (const :tag "A double click follows the link" double)
  1710. (const :tag "Unconditionally follow the link with mouse-1" t)
  1711. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1712. (defcustom org-mark-ring-length 4
  1713. "Number of different positions to be recorded in the ring.
  1714. Changing this requires a restart of Emacs to work correctly."
  1715. :group 'org-link-follow
  1716. :type 'integer)
  1717. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1718. "Non-nil means internal links in Org files must exactly match a headline.
  1719. When nil, the link search tries to match a phrase with all words
  1720. in the search text."
  1721. :group 'org-link-follow
  1722. :version "24.1"
  1723. :type '(choice
  1724. (const :tag "Use fuzzy text search" nil)
  1725. (const :tag "Match only exact headline" t)
  1726. (const :tag "Match exact headline or query to create it"
  1727. query-to-create)))
  1728. (defcustom org-link-frame-setup
  1729. '((vm . vm-visit-folder-other-frame)
  1730. (vm-imap . vm-visit-imap-folder-other-frame)
  1731. (gnus . org-gnus-no-new-news)
  1732. (file . find-file-other-window)
  1733. (wl . wl-other-frame))
  1734. "Setup the frame configuration for following links.
  1735. When following a link with Emacs, it may often be useful to display
  1736. this link in another window or frame. This variable can be used to
  1737. set this up for the different types of links.
  1738. For VM, use any of
  1739. `vm-visit-folder'
  1740. `vm-visit-folder-other-window'
  1741. `vm-visit-folder-other-frame'
  1742. For Gnus, use any of
  1743. `gnus'
  1744. `gnus-other-frame'
  1745. `org-gnus-no-new-news'
  1746. For FILE, use any of
  1747. `find-file'
  1748. `find-file-other-window'
  1749. `find-file-other-frame'
  1750. For Wanderlust use any of
  1751. `wl'
  1752. `wl-other-frame'
  1753. For the calendar, use the variable `calendar-setup'.
  1754. For BBDB, it is currently only possible to display the matches in
  1755. another window."
  1756. :group 'org-link-follow
  1757. :type '(list
  1758. (cons (const vm)
  1759. (choice
  1760. (const vm-visit-folder)
  1761. (const vm-visit-folder-other-window)
  1762. (const vm-visit-folder-other-frame)))
  1763. (cons (const vm-imap)
  1764. (choice
  1765. (const vm-visit-imap-folder)
  1766. (const vm-visit-imap-folder-other-window)
  1767. (const vm-visit-imap-folder-other-frame)))
  1768. (cons (const gnus)
  1769. (choice
  1770. (const gnus)
  1771. (const gnus-other-frame)
  1772. (const org-gnus-no-new-news)))
  1773. (cons (const file)
  1774. (choice
  1775. (const find-file)
  1776. (const find-file-other-window)
  1777. (const find-file-other-frame)))
  1778. (cons (const wl)
  1779. (choice
  1780. (const wl)
  1781. (const wl-other-frame)))))
  1782. (defcustom org-display-internal-link-with-indirect-buffer nil
  1783. "Non-nil means use indirect buffer to display infile links.
  1784. Activating internal links (from one location in a file to another location
  1785. in the same file) normally just jumps to the location. When the link is
  1786. activated with a \\[universal-argument] prefix (or with mouse-3), the link \
  1787. is displayed in
  1788. another window. When this option is set, the other window actually displays
  1789. an indirect buffer clone of the current buffer, to avoid any visibility
  1790. changes to the current buffer."
  1791. :group 'org-link-follow
  1792. :type 'boolean)
  1793. (defcustom org-open-non-existing-files nil
  1794. "Non-nil means `org-open-file' will open non-existing files.
  1795. When nil, an error will be generated.
  1796. This variable applies only to external applications because they
  1797. might choke on non-existing files. If the link is to a file that
  1798. will be opened in Emacs, the variable is ignored."
  1799. :group 'org-link-follow
  1800. :type 'boolean)
  1801. (defcustom org-open-directory-means-index-dot-org nil
  1802. "Non-nil means a link to a directory really means to index.org.
  1803. When nil, following a directory link will run dired or open a finder/explorer
  1804. window on that directory."
  1805. :group 'org-link-follow
  1806. :type 'boolean)
  1807. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1808. "Non-nil means ask for confirmation before executing shell links.
  1809. Shell links can be dangerous: just think about a link
  1810. [[shell:rm -rf ~/*][Google Search]]
  1811. This link would show up in your Org-mode document as \"Google Search\",
  1812. but really it would remove your entire home directory.
  1813. Therefore we advise against setting this variable to nil.
  1814. Just change it to `y-or-n-p' if you want to confirm with a
  1815. single keystroke rather than having to type \"yes\"."
  1816. :group 'org-link-follow
  1817. :type '(choice
  1818. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1819. (const :tag "with y-or-n (faster)" y-or-n-p)
  1820. (const :tag "no confirmation (dangerous)" nil)))
  1821. (put 'org-confirm-shell-link-function
  1822. 'safe-local-variable
  1823. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1824. (defcustom org-confirm-shell-link-not-regexp ""
  1825. "A regexp to skip confirmation for shell links."
  1826. :group 'org-link-follow
  1827. :version "24.1"
  1828. :type 'regexp)
  1829. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1830. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1831. Elisp links can be dangerous: just think about a link
  1832. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1833. This link would show up in your Org-mode document as \"Google Search\",
  1834. but really it would remove your entire home directory.
  1835. Therefore we advise against setting this variable to nil.
  1836. Just change it to `y-or-n-p' if you want to confirm with a
  1837. single keystroke rather than having to type \"yes\"."
  1838. :group 'org-link-follow
  1839. :type '(choice
  1840. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1841. (const :tag "with y-or-n (faster)" y-or-n-p)
  1842. (const :tag "no confirmation (dangerous)" nil)))
  1843. (put 'org-confirm-shell-link-function
  1844. 'safe-local-variable
  1845. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1846. (defcustom org-confirm-elisp-link-not-regexp ""
  1847. "A regexp to skip confirmation for Elisp links."
  1848. :group 'org-link-follow
  1849. :version "24.1"
  1850. :type 'regexp)
  1851. (defconst org-file-apps-defaults-gnu
  1852. '((remote . emacs)
  1853. (system . mailcap)
  1854. (t . mailcap))
  1855. "Default file applications on a UNIX or GNU/Linux system.
  1856. See `org-file-apps'.")
  1857. (defconst org-file-apps-defaults-macosx
  1858. '((remote . emacs)
  1859. (system . "open %s")
  1860. ("ps.gz" . "gv %s")
  1861. ("eps.gz" . "gv %s")
  1862. ("dvi" . "xdvi %s")
  1863. ("fig" . "xfig %s")
  1864. (t . "open %s"))
  1865. "Default file applications on a MacOS X system.
  1866. The system \"open\" is known as a default, but we use X11 applications
  1867. for some files for which the OS does not have a good default.
  1868. See `org-file-apps'.")
  1869. (defconst org-file-apps-defaults-windowsnt
  1870. (list '(remote . emacs)
  1871. (cons 'system (lambda (file _path)
  1872. (with-no-warnings (w32-shell-execute "open" file))))
  1873. (cons t (lambda (file _path)
  1874. (with-no-warnings (w32-shell-execute "open" file)))))
  1875. "Default file applications on a Windows NT system.
  1876. The system \"open\" is used for most files.
  1877. See `org-file-apps'.")
  1878. (defcustom org-file-apps
  1879. '((auto-mode . emacs)
  1880. ("\\.mm\\'" . default)
  1881. ("\\.x?html?\\'" . default)
  1882. ("\\.pdf\\'" . default))
  1883. "External applications for opening `file:path' items in a document.
  1884. \\<org-mode-map>\
  1885. Org mode uses system defaults for different file types, but
  1886. you can use this variable to set the application for a given file
  1887. extension. The entries in this list are cons cells where the car identifies
  1888. files and the cdr the corresponding command. Possible values for the
  1889. file identifier are
  1890. \"string\" A string as a file identifier can be interpreted in different
  1891. ways, depending on its contents:
  1892. - Alphanumeric characters only:
  1893. Match links with this file extension.
  1894. Example: (\"pdf\" . \"evince %s\")
  1895. to open PDFs with evince.
  1896. - Regular expression: Match links where the
  1897. filename matches the regexp. If you want to
  1898. use groups here, use shy groups.
  1899. Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
  1900. \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
  1901. to open *.html and *.xhtml with firefox.
  1902. - Regular expression which contains (non-shy) groups:
  1903. Match links where the whole link, including \"::\", and
  1904. anything after that, matches the regexp.
  1905. In a custom command string, %1, %2, etc. are replaced with
  1906. the parts of the link that were matched by the groups.
  1907. For backwards compatibility, if a command string is given
  1908. that does not use any of the group matches, this case is
  1909. handled identically to the second one (i.e. match against
  1910. file name only).
  1911. In a custom function, you can access the group matches with
  1912. \(match-string n link).
  1913. Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
  1914. to open [[file:document.pdf::5]] with evince at page 5.
  1915. `directory' Matches a directory
  1916. `remote' Matches a remote file, accessible through tramp or efs.
  1917. Remote files most likely should be visited through Emacs
  1918. because external applications cannot handle such paths.
  1919. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1920. so all files Emacs knows how to handle. Using this with
  1921. command `emacs' will open most files in Emacs. Beware that this
  1922. will also open html files inside Emacs, unless you add
  1923. \(\"html\" . default) to the list as well.
  1924. `system' The system command to open files, like `open' on Windows
  1925. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1926. that will be selected if you call \\[org-open-at-point] with a double
  1927. \\[universal-argument] \\[universal-argument] prefix.
  1928. t Default for files not matched by any of the other options.
  1929. Possible values for the command are:
  1930. `emacs' The file will be visited by the current Emacs process.
  1931. `default' Use the default application for this file type, which is the
  1932. association for t in the list, most likely in the system-specific
  1933. part. This can be used to overrule an unwanted setting in the
  1934. system-specific variable.
  1935. `system' Use the system command for opening files, like \"open\".
  1936. This command is specified by the entry whose car is `system'.
  1937. Most likely, the system-specific version of this variable
  1938. does define this command, but you can overrule/replace it
  1939. here.
  1940. `mailcap' Use command specified in the mailcaps.
  1941. string A command to be executed by a shell; %s will be replaced
  1942. by the path to the file.
  1943. function A Lisp function, which will be called with two arguments:
  1944. the file path and the original link string, without the
  1945. \"file:\" prefix.
  1946. For more examples, see the system specific constants
  1947. `org-file-apps-defaults-macosx'
  1948. `org-file-apps-defaults-windowsnt'
  1949. `org-file-apps-defaults-gnu'."
  1950. :group 'org-link-follow
  1951. :type '(repeat
  1952. (cons (choice :value ""
  1953. (string :tag "Extension")
  1954. (const :tag "System command to open files" system)
  1955. (const :tag "Default for unrecognized files" t)
  1956. (const :tag "Remote file" remote)
  1957. (const :tag "Links to a directory" directory)
  1958. (const :tag "Any files that have Emacs modes"
  1959. auto-mode))
  1960. (choice :value ""
  1961. (const :tag "Visit with Emacs" emacs)
  1962. (const :tag "Use default" default)
  1963. (const :tag "Use the system command" system)
  1964. (string :tag "Command")
  1965. (function :tag "Function")))))
  1966. (defcustom org-doi-server-url "http://dx.doi.org/"
  1967. "The URL of the DOI server."
  1968. :type 'string
  1969. :version "24.3"
  1970. :group 'org-link-follow)
  1971. (defgroup org-refile nil
  1972. "Options concerning refiling entries in Org-mode."
  1973. :tag "Org Refile"
  1974. :group 'org)
  1975. (defcustom org-directory "~/org"
  1976. "Directory with Org files.
  1977. This is just a default location to look for Org files. There is no need
  1978. at all to put your files into this directory. It is used in the
  1979. following situations:
  1980. 1. When a capture template specifies a target file that is not an
  1981. absolute path. The path will then be interpreted relative to
  1982. `org-directory'
  1983. 2. When the value of variable `org-agenda-files' is a single file, any
  1984. relative paths in this file will be taken as relative to
  1985. `org-directory'."
  1986. :group 'org-refile
  1987. :group 'org-capture
  1988. :type 'directory)
  1989. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1990. "Default target for storing notes.
  1991. Used as a fall back file for org-capture.el, for templates that
  1992. do not specify a target file."
  1993. :group 'org-refile
  1994. :group 'org-capture
  1995. :type 'file)
  1996. (defcustom org-goto-interface 'outline
  1997. "The default interface to be used for `org-goto'.
  1998. Allowed values are:
  1999. outline The interface shows an outline of the relevant file
  2000. and the correct heading is found by moving through
  2001. the outline or by searching with incremental search.
  2002. outline-path-completion Headlines in the current buffer are offered via
  2003. completion. This is the interface also used by
  2004. the refile command."
  2005. :group 'org-refile
  2006. :type '(choice
  2007. (const :tag "Outline" outline)
  2008. (const :tag "Outline-path-completion" outline-path-completion)))
  2009. (defcustom org-goto-max-level 5
  2010. "Maximum target level when running `org-goto' with refile interface."
  2011. :group 'org-refile
  2012. :type 'integer)
  2013. (defcustom org-reverse-note-order nil
  2014. "Non-nil means store new notes at the beginning of a file or entry.
  2015. When nil, new notes will be filed to the end of a file or entry.
  2016. This can also be a list with cons cells of regular expressions that
  2017. are matched against file names, and values."
  2018. :group 'org-capture
  2019. :group 'org-refile
  2020. :type '(choice
  2021. (const :tag "Reverse always" t)
  2022. (const :tag "Reverse never" nil)
  2023. (repeat :tag "By file name regexp"
  2024. (cons regexp boolean))))
  2025. (defcustom org-log-refile nil
  2026. "Information to record when a task is refiled.
  2027. Possible values are:
  2028. nil Don't add anything
  2029. time Add a time stamp to the task
  2030. note Prompt for a note and add it with template `org-log-note-headings'
  2031. This option can also be set with on a per-file-basis with
  2032. #+STARTUP: nologrefile
  2033. #+STARTUP: logrefile
  2034. #+STARTUP: lognoterefile
  2035. You can have local logging settings for a subtree by setting the LOGGING
  2036. property to one or more of these keywords.
  2037. When bulk-refiling from the agenda, the value `note' is forbidden and
  2038. will temporarily be changed to `time'."
  2039. :group 'org-refile
  2040. :group 'org-progress
  2041. :version "24.1"
  2042. :type '(choice
  2043. (const :tag "No logging" nil)
  2044. (const :tag "Record timestamp" time)
  2045. (const :tag "Record timestamp with note." note)))
  2046. (defcustom org-refile-targets nil
  2047. "Targets for refiling entries with \\[org-refile].
  2048. This is a list of cons cells. Each cell contains:
  2049. - a specification of the files to be considered, either a list of files,
  2050. or a symbol whose function or variable value will be used to retrieve
  2051. a file name or a list of file names. If you use `org-agenda-files' for
  2052. that, all agenda files will be scanned for targets. Nil means consider
  2053. headings in the current buffer.
  2054. - A specification of how to find candidate refile targets. This may be
  2055. any of:
  2056. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2057. This tag has to be present in all target headlines, inheritance will
  2058. not be considered.
  2059. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2060. todo keyword.
  2061. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2062. headlines that are refiling targets.
  2063. - a cons cell (:level . N). Any headline of level N is considered a target.
  2064. Note that, when `org-odd-levels-only' is set, level corresponds to
  2065. order in hierarchy, not to the number of stars.
  2066. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2067. Note that, when `org-odd-levels-only' is set, level corresponds to
  2068. order in hierarchy, not to the number of stars.
  2069. Each element of this list generates a set of possible targets.
  2070. The union of these sets is presented (with completion) to
  2071. the user by `org-refile'.
  2072. You can set the variable `org-refile-target-verify-function' to a function
  2073. to verify each headline found by the simple criteria above.
  2074. When this variable is nil, all top-level headlines in the current buffer
  2075. are used, equivalent to the value `((nil . (:level . 1))'."
  2076. :group 'org-refile
  2077. :type '(repeat
  2078. (cons
  2079. (choice :value org-agenda-files
  2080. (const :tag "All agenda files" org-agenda-files)
  2081. (const :tag "Current buffer" nil)
  2082. (function) (variable) (file))
  2083. (choice :tag "Identify target headline by"
  2084. (cons :tag "Specific tag" (const :value :tag) (string))
  2085. (cons :tag "TODO keyword" (const :value :todo) (string))
  2086. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2087. (cons :tag "Level number" (const :value :level) (integer))
  2088. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2089. (defcustom org-refile-target-verify-function nil
  2090. "Function to verify if the headline at point should be a refile target.
  2091. The function will be called without arguments, with point at the
  2092. beginning of the headline. It should return t and leave point
  2093. where it is if the headline is a valid target for refiling.
  2094. If the target should not be selected, the function must return nil.
  2095. In addition to this, it may move point to a place from where the search
  2096. should be continued. For example, the function may decide that the entire
  2097. subtree of the current entry should be excluded and move point to the end
  2098. of the subtree."
  2099. :group 'org-refile
  2100. :type '(choice
  2101. (const nil)
  2102. (function)))
  2103. (defcustom org-refile-use-cache nil
  2104. "Non-nil means cache refile targets to speed up the process.
  2105. \\<org-mode-map>\
  2106. The cache for a particular file will be updated automatically when
  2107. the buffer has been killed, or when any of the marker used for flagging
  2108. refile targets no longer points at a live buffer.
  2109. If you have added new entries to a buffer that might themselves be targets,
  2110. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2111. if you find that easier, \
  2112. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2113. \\[org-refile]'."
  2114. :group 'org-refile
  2115. :version "24.1"
  2116. :type 'boolean)
  2117. (defcustom org-refile-use-outline-path nil
  2118. "Non-nil means provide refile targets as paths.
  2119. So a level 3 headline will be available as level1/level2/level3.
  2120. When the value is `file', also include the file name (without directory)
  2121. into the path. In this case, you can also stop the completion after
  2122. the file name, to get entries inserted as top level in the file.
  2123. When `full-file-path', include the full file path."
  2124. :group 'org-refile
  2125. :type '(choice
  2126. (const :tag "Not" nil)
  2127. (const :tag "Yes" t)
  2128. (const :tag "Start with file name" file)
  2129. (const :tag "Start with full file path" full-file-path)))
  2130. (defcustom org-outline-path-complete-in-steps t
  2131. "Non-nil means complete the outline path in hierarchical steps.
  2132. When Org-mode uses the refile interface to select an outline path
  2133. \(see variable `org-refile-use-outline-path'), the completion of
  2134. the path can be done in a single go, or it can be done in steps down
  2135. the headline hierarchy. Going in steps is probably the best if you
  2136. do not use a special completion package like `ido' or `icicles'.
  2137. However, when using these packages, going in one step can be very
  2138. fast, while still showing the whole path to the entry."
  2139. :group 'org-refile
  2140. :type 'boolean)
  2141. (defcustom org-refile-allow-creating-parent-nodes nil
  2142. "Non-nil means allow the creation of new nodes as refile targets.
  2143. New nodes are then created by adding \"/new node name\" to the completion
  2144. of an existing node. When the value of this variable is `confirm',
  2145. new node creation must be confirmed by the user (recommended).
  2146. When nil, the completion must match an existing entry.
  2147. Note that, if the new heading is not seen by the criteria
  2148. listed in `org-refile-targets', multiple instances of the same
  2149. heading would be created by trying again to file under the new
  2150. heading."
  2151. :group 'org-refile
  2152. :type '(choice
  2153. (const :tag "Never" nil)
  2154. (const :tag "Always" t)
  2155. (const :tag "Prompt for confirmation" confirm)))
  2156. (defcustom org-refile-active-region-within-subtree nil
  2157. "Non-nil means also refile active region within a subtree.
  2158. By default `org-refile' doesn't allow refiling regions if they
  2159. don't contain a set of subtrees, but it might be convenient to
  2160. do so sometimes: in that case, the first line of the region is
  2161. converted to a headline before refiling."
  2162. :group 'org-refile
  2163. :version "24.1"
  2164. :type 'boolean)
  2165. (defgroup org-todo nil
  2166. "Options concerning TODO items in Org-mode."
  2167. :tag "Org TODO"
  2168. :group 'org)
  2169. (defgroup org-progress nil
  2170. "Options concerning Progress logging in Org-mode."
  2171. :tag "Org Progress"
  2172. :group 'org-time)
  2173. (defvar org-todo-interpretation-widgets
  2174. '((:tag "Sequence (cycling hits every state)" sequence)
  2175. (:tag "Type (cycling directly to DONE)" type))
  2176. "The available interpretation symbols for customizing `org-todo-keywords'.
  2177. Interested libraries should add to this list.")
  2178. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2179. "List of TODO entry keyword sequences and their interpretation.
  2180. \\<org-mode-map>This is a list of sequences.
  2181. Each sequence starts with a symbol, either `sequence' or `type',
  2182. indicating if the keywords should be interpreted as a sequence of
  2183. action steps, or as different types of TODO items. The first
  2184. keywords are states requiring action - these states will select a headline
  2185. for inclusion into the global TODO list Org-mode produces. If one of
  2186. the \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2187. signify that no further action is necessary. If \"|\" is not found,
  2188. the last keyword is treated as the only DONE state of the sequence.
  2189. The command \\[org-todo] cycles an entry through these states, and one
  2190. additional state where no keyword is present. For details about this
  2191. cycling, see the manual.
  2192. TODO keywords and interpretation can also be set on a per-file basis with
  2193. the special #+SEQ_TODO and #+TYP_TODO lines.
  2194. Each keyword can optionally specify a character for fast state selection
  2195. \(in combination with the variable `org-use-fast-todo-selection')
  2196. and specifiers for state change logging, using the same syntax that
  2197. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2198. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2199. indicates to record a time stamp each time this state is selected.
  2200. Each keyword may also specify if a timestamp or a note should be
  2201. recorded when entering or leaving the state, by adding additional
  2202. characters in the parenthesis after the keyword. This looks like this:
  2203. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2204. record only the time of the state change. With X and Y being either
  2205. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2206. Y when leaving the state if and only if the *target* state does not
  2207. define X. You may omit any of the fast-selection key or X or /Y,
  2208. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2209. For backward compatibility, this variable may also be just a list
  2210. of keywords. In this case the interpretation (sequence or type) will be
  2211. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2212. :group 'org-todo
  2213. :group 'org-keywords
  2214. :type '(choice
  2215. (repeat :tag "Old syntax, just keywords"
  2216. (string :tag "Keyword"))
  2217. (repeat :tag "New syntax"
  2218. (cons
  2219. (choice
  2220. :tag "Interpretation"
  2221. ;;Quick and dirty way to see
  2222. ;;`org-todo-interpretations'. This takes the
  2223. ;;place of item arguments
  2224. :convert-widget
  2225. (lambda (widget)
  2226. (widget-put widget
  2227. :args (mapcar
  2228. (lambda (x)
  2229. (widget-convert
  2230. (cons 'const x)))
  2231. org-todo-interpretation-widgets))
  2232. widget))
  2233. (repeat
  2234. (string :tag "Keyword"))))))
  2235. (defvar-local org-todo-keywords-1 nil
  2236. "All TODO and DONE keywords active in a buffer.")
  2237. (defvar org-todo-keywords-for-agenda nil)
  2238. (defvar org-done-keywords-for-agenda nil)
  2239. (defvar org-todo-keyword-alist-for-agenda nil)
  2240. (defvar org-tag-alist-for-agenda nil
  2241. "Alist of all tags from all agenda files.")
  2242. (defvar org-tag-groups-alist-for-agenda nil
  2243. "Alist of all groups tags from all current agenda files.")
  2244. (defvar-local org-tag-groups-alist nil)
  2245. (defvar org-agenda-contributing-files nil)
  2246. (defvar-local org-current-tag-alist nil
  2247. "Alist of all tag groups in current buffer.
  2248. This variable takes into consideration `org-tag-alist',
  2249. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2250. (defvar-local org-not-done-keywords nil)
  2251. (defvar-local org-done-keywords nil)
  2252. (defvar-local org-todo-heads nil)
  2253. (defvar-local org-todo-sets nil)
  2254. (defvar-local org-todo-log-states nil)
  2255. (defvar-local org-todo-kwd-alist nil)
  2256. (defvar-local org-todo-key-alist nil)
  2257. (defvar-local org-todo-key-trigger nil)
  2258. (defcustom org-todo-interpretation 'sequence
  2259. "Controls how TODO keywords are interpreted.
  2260. This variable is in principle obsolete and is only used for
  2261. backward compatibility, if the interpretation of todo keywords is
  2262. not given already in `org-todo-keywords'. See that variable for
  2263. more information."
  2264. :group 'org-todo
  2265. :group 'org-keywords
  2266. :type '(choice (const sequence)
  2267. (const type)))
  2268. (defcustom org-use-fast-todo-selection t
  2269. "\\<org-mode-map>\
  2270. Non-nil means use the fast todo selection scheme with \\[org-todo].
  2271. This variable describes if and under what circumstances the cycling
  2272. mechanism for TODO keywords will be replaced by a single-key, direct
  2273. selection scheme.
  2274. When nil, fast selection is never used.
  2275. When the symbol `prefix', it will be used when `org-todo' is called
  2276. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2277. in an Org-mode buffer, and
  2278. `\\[universal-argument] t' in an agenda buffer.
  2279. When t, fast selection is used by default. In this case, the prefix
  2280. argument forces cycling instead.
  2281. In all cases, the special interface is only used if access keys have
  2282. actually been assigned by the user, i.e. if keywords in the configuration
  2283. are followed by a letter in parenthesis, like TODO(t)."
  2284. :group 'org-todo
  2285. :type '(choice
  2286. (const :tag "Never" nil)
  2287. (const :tag "By default" t)
  2288. (const :tag "Only with C-u C-c C-t" prefix)))
  2289. (defcustom org-provide-todo-statistics t
  2290. "Non-nil means update todo statistics after insert and toggle.
  2291. ALL-HEADLINES means update todo statistics by including headlines
  2292. with no TODO keyword as well, counting them as not done.
  2293. A list of TODO keywords means the same, but skip keywords that are
  2294. not in this list.
  2295. When set to a list of two lists, the first list contains keywords
  2296. to consider as TODO keywords, the second list contains keywords
  2297. to consider as DONE keywords.
  2298. When this is set, todo statistics is updated in the parent of the
  2299. current entry each time a todo state is changed."
  2300. :group 'org-todo
  2301. :type '(choice
  2302. (const :tag "Yes, only for TODO entries" t)
  2303. (const :tag "Yes, including all entries" all-headlines)
  2304. (repeat :tag "Yes, for TODOs in this list"
  2305. (string :tag "TODO keyword"))
  2306. (list :tag "Yes, for TODOs and DONEs in these lists"
  2307. (repeat (string :tag "TODO keyword"))
  2308. (repeat (string :tag "DONE keyword")))
  2309. (other :tag "No TODO statistics" nil)))
  2310. (defcustom org-hierarchical-todo-statistics t
  2311. "Non-nil means TODO statistics covers just direct children.
  2312. When nil, all entries in the subtree are considered.
  2313. This has only an effect if `org-provide-todo-statistics' is set.
  2314. To set this to nil for only a single subtree, use a COOKIE_DATA
  2315. property and include the word \"recursive\" into the value."
  2316. :group 'org-todo
  2317. :type 'boolean)
  2318. (defcustom org-after-todo-state-change-hook nil
  2319. "Hook which is run after the state of a TODO item was changed.
  2320. The new state (a string with a TODO keyword, or nil) is available in the
  2321. Lisp variable `org-state'."
  2322. :group 'org-todo
  2323. :type 'hook)
  2324. (defvar org-blocker-hook nil
  2325. "Hook for functions that are allowed to block a state change.
  2326. Functions in this hook should not modify the buffer.
  2327. Each function gets as its single argument a property list,
  2328. see `org-trigger-hook' for more information about this list.
  2329. If any of the functions in this hook returns nil, the state change
  2330. is blocked.")
  2331. (defvar org-trigger-hook nil
  2332. "Hook for functions that are triggered by a state change.
  2333. Each function gets as its single argument a property list with at
  2334. least the following elements:
  2335. (:type type-of-change :position pos-at-entry-start
  2336. :from old-state :to new-state)
  2337. Depending on the type, more properties may be present.
  2338. This mechanism is currently implemented for:
  2339. TODO state changes
  2340. ------------------
  2341. :type todo-state-change
  2342. :from previous state (keyword as a string), or nil, or a symbol
  2343. `todo' or `done', to indicate the general type of state.
  2344. :to new state, like in :from")
  2345. (defcustom org-enforce-todo-dependencies nil
  2346. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2347. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2348. be blocked if any prior sibling is not yet done.
  2349. Finally, if the parent is blocked because of ordered siblings of its own,
  2350. the child will also be blocked."
  2351. :set (lambda (var val)
  2352. (set var val)
  2353. (if val
  2354. (add-hook 'org-blocker-hook
  2355. 'org-block-todo-from-children-or-siblings-or-parent)
  2356. (remove-hook 'org-blocker-hook
  2357. 'org-block-todo-from-children-or-siblings-or-parent)))
  2358. :group 'org-todo
  2359. :type 'boolean)
  2360. (defcustom org-enforce-todo-checkbox-dependencies nil
  2361. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2362. When this is nil, checkboxes have no influence on switching TODO states.
  2363. When non-nil, you first need to check off all check boxes before the TODO
  2364. entry can be switched to DONE.
  2365. This variable needs to be set before org.el is loaded, and you need to
  2366. restart Emacs after a change to make the change effective. The only way
  2367. to change is while Emacs is running is through the customize interface."
  2368. :set (lambda (var val)
  2369. (set var val)
  2370. (if val
  2371. (add-hook 'org-blocker-hook
  2372. 'org-block-todo-from-checkboxes)
  2373. (remove-hook 'org-blocker-hook
  2374. 'org-block-todo-from-checkboxes)))
  2375. :group 'org-todo
  2376. :type 'boolean)
  2377. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2378. "Non-nil means inserting a TODO heading is treated as state change.
  2379. So when the command \\[org-insert-todo-heading] is used, state change
  2380. logging will apply if appropriate. When nil, the new TODO item will
  2381. be inserted directly, and no logging will take place."
  2382. :group 'org-todo
  2383. :type 'boolean)
  2384. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2385. "Non-nil means switching TODO states with S-cursor counts as state change.
  2386. This is the default behavior. However, setting this to nil allows a
  2387. convenient way to select a TODO state and bypass any logging associated
  2388. with that."
  2389. :group 'org-todo
  2390. :type 'boolean)
  2391. (defcustom org-todo-state-tags-triggers nil
  2392. "Tag changes that should be triggered by TODO state changes.
  2393. This is a list. Each entry is
  2394. (state-change (tag . flag) .......)
  2395. State-change can be a string with a state, and empty string to indicate the
  2396. state that has no TODO keyword, or it can be one of the symbols `todo'
  2397. or `done', meaning any not-done or done state, respectively."
  2398. :group 'org-todo
  2399. :group 'org-tags
  2400. :type '(repeat
  2401. (cons (choice :tag "When changing to"
  2402. (const :tag "Not-done state" todo)
  2403. (const :tag "Done state" done)
  2404. (string :tag "State"))
  2405. (repeat
  2406. (cons :tag "Tag action"
  2407. (string :tag "Tag")
  2408. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2409. (defcustom org-log-done nil
  2410. "Information to record when a task moves to the DONE state.
  2411. Possible values are:
  2412. nil Don't add anything, just change the keyword
  2413. time Add a time stamp to the task
  2414. note Prompt for a note and add it with template `org-log-note-headings'
  2415. This option can also be set with on a per-file-basis with
  2416. #+STARTUP: nologdone
  2417. #+STARTUP: logdone
  2418. #+STARTUP: lognotedone
  2419. You can have local logging settings for a subtree by setting the LOGGING
  2420. property to one or more of these keywords."
  2421. :group 'org-todo
  2422. :group 'org-progress
  2423. :type '(choice
  2424. (const :tag "No logging" nil)
  2425. (const :tag "Record CLOSED timestamp" time)
  2426. (const :tag "Record CLOSED timestamp with note." note)))
  2427. ;; Normalize old uses of org-log-done.
  2428. (cond
  2429. ((eq org-log-done t) (setq org-log-done 'time))
  2430. ((and (listp org-log-done) (memq 'done org-log-done))
  2431. (setq org-log-done 'note)))
  2432. (defcustom org-log-reschedule nil
  2433. "Information to record when the scheduling date of a tasks is modified.
  2434. Possible values are:
  2435. nil Don't add anything, just change the date
  2436. time Add a time stamp to the task
  2437. note Prompt for a note and add it with template `org-log-note-headings'
  2438. This option can also be set with on a per-file-basis with
  2439. #+STARTUP: nologreschedule
  2440. #+STARTUP: logreschedule
  2441. #+STARTUP: lognotereschedule"
  2442. :group 'org-todo
  2443. :group 'org-progress
  2444. :type '(choice
  2445. (const :tag "No logging" nil)
  2446. (const :tag "Record timestamp" time)
  2447. (const :tag "Record timestamp with note." note)))
  2448. (defcustom org-log-redeadline nil
  2449. "Information to record when the deadline date of a tasks is modified.
  2450. Possible values are:
  2451. nil Don't add anything, just change the date
  2452. time Add a time stamp to the task
  2453. note Prompt for a note and add it with template `org-log-note-headings'
  2454. This option can also be set with on a per-file-basis with
  2455. #+STARTUP: nologredeadline
  2456. #+STARTUP: logredeadline
  2457. #+STARTUP: lognoteredeadline
  2458. You can have local logging settings for a subtree by setting the LOGGING
  2459. property to one or more of these keywords."
  2460. :group 'org-todo
  2461. :group 'org-progress
  2462. :type '(choice
  2463. (const :tag "No logging" nil)
  2464. (const :tag "Record timestamp" time)
  2465. (const :tag "Record timestamp with note." note)))
  2466. (defcustom org-log-note-clock-out nil
  2467. "Non-nil means record a note when clocking out of an item.
  2468. This can also be configured on a per-file basis by adding one of
  2469. the following lines anywhere in the buffer:
  2470. #+STARTUP: lognoteclock-out
  2471. #+STARTUP: nolognoteclock-out"
  2472. :group 'org-todo
  2473. :group 'org-progress
  2474. :type 'boolean)
  2475. (defcustom org-log-done-with-time t
  2476. "Non-nil means the CLOSED time stamp will contain date and time.
  2477. When nil, only the date will be recorded."
  2478. :group 'org-progress
  2479. :type 'boolean)
  2480. (defcustom org-log-note-headings
  2481. '((done . "CLOSING NOTE %t")
  2482. (state . "State %-12s from %-12S %t")
  2483. (note . "Note taken on %t")
  2484. (reschedule . "Rescheduled from %S on %t")
  2485. (delschedule . "Not scheduled, was %S on %t")
  2486. (redeadline . "New deadline from %S on %t")
  2487. (deldeadline . "Removed deadline, was %S on %t")
  2488. (refile . "Refiled on %t")
  2489. (clock-out . ""))
  2490. "Headings for notes added to entries.
  2491. The value is an alist, with the car being a symbol indicating the
  2492. note context, and the cdr is the heading to be used. The heading
  2493. may also be the empty string. The following placeholders can be
  2494. used:
  2495. %t a time stamp.
  2496. %T an active time stamp instead the default inactive one
  2497. %d a short-format time stamp.
  2498. %D an active short-format time stamp.
  2499. %s the new TODO state or time stamp (inactive), in double quotes.
  2500. %S the old TODO state or time stamp (inactive), in double quotes.
  2501. %u the user name.
  2502. %U full user name.
  2503. In fact, it is not a good idea to change the `state' entry,
  2504. because Agenda Log mode depends on the format of these entries."
  2505. :group 'org-todo
  2506. :group 'org-progress
  2507. :type '(list :greedy t
  2508. (cons (const :tag "Heading when closing an item" done) string)
  2509. (cons (const :tag
  2510. "Heading when changing todo state (todo sequence only)"
  2511. state) string)
  2512. (cons (const :tag "Heading when just taking a note" note) string)
  2513. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2514. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2515. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2516. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2517. (cons (const :tag "Heading when refiling" refile) string)
  2518. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2519. (unless (assq 'note org-log-note-headings)
  2520. (push '(note . "%t") org-log-note-headings))
  2521. (defcustom org-log-into-drawer nil
  2522. "Non-nil means insert state change notes and time stamps into a drawer.
  2523. When nil, state changes notes will be inserted after the headline and
  2524. any scheduling and clock lines, but not inside a drawer.
  2525. The value of this variable should be the name of the drawer to use.
  2526. LOGBOOK is proposed as the default drawer for this purpose, you can
  2527. also set this to a string to define the drawer of your choice.
  2528. A value of t is also allowed, representing \"LOGBOOK\".
  2529. A value of t or nil can also be set with on a per-file-basis with
  2530. #+STARTUP: logdrawer
  2531. #+STARTUP: nologdrawer
  2532. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2533. will be ignored.
  2534. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2535. a subtree.
  2536. Do not check directly this variable in a Lisp program. Call
  2537. function `org-log-into-drawer' instead."
  2538. :group 'org-todo
  2539. :group 'org-progress
  2540. :type '(choice
  2541. (const :tag "Not into a drawer" nil)
  2542. (const :tag "LOGBOOK" t)
  2543. (string :tag "Other")))
  2544. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2545. (defun org-log-into-drawer ()
  2546. "Name of the log drawer, as a string, or nil.
  2547. This is the value of `org-log-into-drawer'. However, if the
  2548. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2549. be used instead of the default value."
  2550. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2551. (cond ((equal p "nil") nil)
  2552. ((equal p "t") "LOGBOOK")
  2553. ((stringp p) p)
  2554. (p "LOGBOOK")
  2555. ((stringp org-log-into-drawer) org-log-into-drawer)
  2556. (org-log-into-drawer "LOGBOOK"))))
  2557. (defcustom org-log-state-notes-insert-after-drawers nil
  2558. "Non-nil means insert state change notes after any drawers in entry.
  2559. Only the drawers that *immediately* follow the headline and the
  2560. deadline/scheduled line are skipped.
  2561. When nil, insert notes right after the heading and perhaps the line
  2562. with deadline/scheduling if present.
  2563. This variable will have no effect if `org-log-into-drawer' is
  2564. set."
  2565. :group 'org-todo
  2566. :group 'org-progress
  2567. :type 'boolean)
  2568. (defcustom org-log-states-order-reversed t
  2569. "Non-nil means the latest state note will be directly after heading.
  2570. When nil, the state change notes will be ordered according to time.
  2571. This option can also be set with on a per-file-basis with
  2572. #+STARTUP: logstatesreversed
  2573. #+STARTUP: nologstatesreversed"
  2574. :group 'org-todo
  2575. :group 'org-progress
  2576. :type 'boolean)
  2577. (defcustom org-todo-repeat-to-state nil
  2578. "The TODO state to which a repeater should return the repeating task.
  2579. By default this is the first task in a TODO sequence, or the previous state
  2580. in a TODO_TYP set. But you can specify another task here.
  2581. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2582. :group 'org-todo
  2583. :version "24.1"
  2584. :type '(choice (const :tag "Head of sequence" nil)
  2585. (string :tag "Specific state")))
  2586. (defcustom org-log-repeat 'time
  2587. "Non-nil means record moving through the DONE state when triggering repeat.
  2588. An auto-repeating task is immediately switched back to TODO when
  2589. marked DONE. If you are not logging state changes (by adding \"@\"
  2590. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2591. record a closing note, there will be no record of the task moving
  2592. through DONE. This variable forces taking a note anyway.
  2593. nil Don't force a record
  2594. time Record a time stamp
  2595. note Prompt for a note and add it with template `org-log-note-headings'
  2596. This option can also be set with on a per-file-basis with
  2597. #+STARTUP: nologrepeat
  2598. #+STARTUP: logrepeat
  2599. #+STARTUP: lognoterepeat
  2600. You can have local logging settings for a subtree by setting the LOGGING
  2601. property to one or more of these keywords."
  2602. :group 'org-todo
  2603. :group 'org-progress
  2604. :type '(choice
  2605. (const :tag "Don't force a record" nil)
  2606. (const :tag "Force recording the DONE state" time)
  2607. (const :tag "Force recording a note with the DONE state" note)))
  2608. (defgroup org-priorities nil
  2609. "Priorities in Org-mode."
  2610. :tag "Org Priorities"
  2611. :group 'org-todo)
  2612. (defcustom org-enable-priority-commands t
  2613. "Non-nil means priority commands are active.
  2614. When nil, these commands will be disabled, so that you never accidentally
  2615. set a priority."
  2616. :group 'org-priorities
  2617. :type 'boolean)
  2618. (defcustom org-highest-priority ?A
  2619. "The highest priority of TODO items. A character like ?A, ?B etc.
  2620. Must have a smaller ASCII number than `org-lowest-priority'."
  2621. :group 'org-priorities
  2622. :type 'character)
  2623. (defcustom org-lowest-priority ?C
  2624. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2625. Must have a larger ASCII number than `org-highest-priority'."
  2626. :group 'org-priorities
  2627. :type 'character)
  2628. (defcustom org-default-priority ?B
  2629. "The default priority of TODO items.
  2630. This is the priority an item gets if no explicit priority is given.
  2631. When starting to cycle on an empty priority the first step in the cycle
  2632. depends on `org-priority-start-cycle-with-default'. The resulting first
  2633. step priority must not exceed the range from `org-highest-priority' to
  2634. `org-lowest-priority' which means that `org-default-priority' has to be
  2635. in this range exclusive or inclusive the range boundaries. Else the
  2636. first step refuses to set the default and the second will fall back
  2637. to (depending on the command used) the highest or lowest priority."
  2638. :group 'org-priorities
  2639. :type 'character)
  2640. (defcustom org-priority-start-cycle-with-default t
  2641. "Non-nil means start with default priority when starting to cycle.
  2642. When this is nil, the first step in the cycle will be (depending on the
  2643. command used) one higher or lower than the default priority.
  2644. See also `org-default-priority'."
  2645. :group 'org-priorities
  2646. :type 'boolean)
  2647. (defcustom org-get-priority-function nil
  2648. "Function to extract the priority from a string.
  2649. The string is normally the headline. If this is nil Org computes the
  2650. priority from the priority cookie like [#A] in the headline. It returns
  2651. an integer, increasing by 1000 for each priority level.
  2652. The user can set a different function here, which should take a string
  2653. as an argument and return the numeric priority."
  2654. :group 'org-priorities
  2655. :version "24.1"
  2656. :type '(choice
  2657. (const nil)
  2658. (function)))
  2659. (defgroup org-time nil
  2660. "Options concerning time stamps and deadlines in Org-mode."
  2661. :tag "Org Time"
  2662. :group 'org)
  2663. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2664. "Number of minutes to round time stamps to.
  2665. \\<org-mode-map>\
  2666. These are two values, the first applies when first creating a time stamp.
  2667. The second applies when changing it with the commands `S-up' and `S-down'.
  2668. When changing the time stamp, this means that it will change in steps
  2669. of N minutes, as given by the second value.
  2670. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2671. numbers should be factors of 60, so for example 5, 10, 15.
  2672. When this is larger than 1, you can still force an exact time stamp by using
  2673. a double prefix argument to a time stamp command like \
  2674. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2675. and by using a prefix arg to `S-up/down' to specify the exact number
  2676. of minutes to shift."
  2677. :group 'org-time
  2678. :get (lambda (var) ; Make sure both elements are there
  2679. (if (integerp (default-value var))
  2680. (list (default-value var) 5)
  2681. (default-value var)))
  2682. :type '(list
  2683. (integer :tag "when inserting times")
  2684. (integer :tag "when modifying times")))
  2685. ;; Normalize old customizations of this variable.
  2686. (when (integerp org-time-stamp-rounding-minutes)
  2687. (setq org-time-stamp-rounding-minutes
  2688. (list org-time-stamp-rounding-minutes
  2689. org-time-stamp-rounding-minutes)))
  2690. (defcustom org-display-custom-times nil
  2691. "Non-nil means overlay custom formats over all time stamps.
  2692. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2693. To turn this on on a per-file basis, insert anywhere in the file:
  2694. #+STARTUP: customtime"
  2695. :group 'org-time
  2696. :set 'set-default
  2697. :type 'sexp)
  2698. (make-variable-buffer-local 'org-display-custom-times)
  2699. (defcustom org-time-stamp-custom-formats
  2700. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2701. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2702. These are overlaid over the default ISO format if the variable
  2703. `org-display-custom-times' is set. Time like %H:%M should be at the
  2704. end of the second format. The custom formats are also honored by export
  2705. commands, if custom time display is turned on at the time of export."
  2706. :group 'org-time
  2707. :type 'sexp)
  2708. (defun org-time-stamp-format (&optional long inactive)
  2709. "Get the right format for a time string."
  2710. (let ((f (if long (cdr org-time-stamp-formats)
  2711. (car org-time-stamp-formats))))
  2712. (if inactive
  2713. (concat "[" (substring f 1 -1) "]")
  2714. f)))
  2715. (defcustom org-time-clocksum-format
  2716. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2717. "The format string used when creating CLOCKSUM lines.
  2718. This is also used when Org mode generates a time duration.
  2719. The value can be a single format string containing two
  2720. %-sequences, which will be filled with the number of hours and
  2721. minutes in that order.
  2722. Alternatively, the value can be a plist associating any of the
  2723. keys :years, :months, :weeks, :days, :hours or :minutes with
  2724. format strings. The time duration is formatted using only the
  2725. time components that are needed and concatenating the results.
  2726. If a time unit in absent, it falls back to the next smallest
  2727. unit.
  2728. The keys :require-years, :require-months, :require-days,
  2729. :require-weeks, :require-hours, :require-minutes are also
  2730. meaningful. A non-nil value for these keys indicates that the
  2731. corresponding time component should always be included, even if
  2732. its value is 0.
  2733. For example,
  2734. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2735. :require-minutes t)
  2736. means durations longer than a day will be expressed in days,
  2737. hours and minutes, and durations less than a day will always be
  2738. expressed in hours and minutes (even for durations less than an
  2739. hour).
  2740. The value
  2741. (:days \"%dd\" :minutes \"%dm\")
  2742. means durations longer than a day will be expressed in days and
  2743. minutes, and durations less than a day will be expressed entirely
  2744. in minutes (even for durations longer than an hour)."
  2745. :group 'org-time
  2746. :group 'org-clock
  2747. :version "24.4"
  2748. :package-version '(Org . "8.0")
  2749. :type '(choice (string :tag "Format string")
  2750. (set :tag "Plist"
  2751. (group :inline t (const :tag "Years" :years)
  2752. (string :tag "Format string"))
  2753. (group :inline t
  2754. (const :tag "Always show years" :require-years)
  2755. (const t))
  2756. (group :inline t (const :tag "Months" :months)
  2757. (string :tag "Format string"))
  2758. (group :inline t
  2759. (const :tag "Always show months" :require-months)
  2760. (const t))
  2761. (group :inline t (const :tag "Weeks" :weeks)
  2762. (string :tag "Format string"))
  2763. (group :inline t
  2764. (const :tag "Always show weeks" :require-weeks)
  2765. (const t))
  2766. (group :inline t (const :tag "Days" :days)
  2767. (string :tag "Format string"))
  2768. (group :inline t
  2769. (const :tag "Always show days" :require-days)
  2770. (const t))
  2771. (group :inline t (const :tag "Hours" :hours)
  2772. (string :tag "Format string"))
  2773. (group :inline t
  2774. (const :tag "Always show hours" :require-hours)
  2775. (const t))
  2776. (group :inline t (const :tag "Minutes" :minutes)
  2777. (string :tag "Format string"))
  2778. (group :inline t
  2779. (const :tag "Always show minutes" :require-minutes)
  2780. (const t)))))
  2781. (defcustom org-time-clocksum-use-fractional nil
  2782. "When non-nil, \\[org-clock-display] uses fractional times.
  2783. See `org-time-clocksum-format' for more on time clock formats."
  2784. :group 'org-time
  2785. :group 'org-clock
  2786. :version "24.3"
  2787. :type 'boolean)
  2788. (defcustom org-time-clocksum-use-effort-durations nil
  2789. "When non-nil, \\[org-clock-display] uses effort durations.
  2790. E.g. by default, one day is considered to be a 8 hours effort,
  2791. so a task that has been clocked for 16 hours will be displayed
  2792. as during 2 days in the clock display or in the clocktable.
  2793. See `org-effort-durations' on how to set effort durations
  2794. and `org-time-clocksum-format' for more on time clock formats."
  2795. :group 'org-time
  2796. :group 'org-clock
  2797. :version "24.4"
  2798. :package-version '(Org . "8.0")
  2799. :type 'boolean)
  2800. (defcustom org-time-clocksum-fractional-format "%.2f"
  2801. "The format string used when creating CLOCKSUM lines,
  2802. or when Org mode generates a time duration, if
  2803. `org-time-clocksum-use-fractional' is enabled.
  2804. The value can be a single format string containing one
  2805. %-sequence, which will be filled with the number of hours as
  2806. a float.
  2807. Alternatively, the value can be a plist associating any of the
  2808. keys :years, :months, :weeks, :days, :hours or :minutes with
  2809. a format string. The time duration is formatted using the
  2810. largest time unit which gives a non-zero integer part. If all
  2811. specified formats have zero integer part, the smallest time unit
  2812. is used."
  2813. :group 'org-time
  2814. :type '(choice (string :tag "Format string")
  2815. (set (group :inline t (const :tag "Years" :years)
  2816. (string :tag "Format string"))
  2817. (group :inline t (const :tag "Months" :months)
  2818. (string :tag "Format string"))
  2819. (group :inline t (const :tag "Weeks" :weeks)
  2820. (string :tag "Format string"))
  2821. (group :inline t (const :tag "Days" :days)
  2822. (string :tag "Format string"))
  2823. (group :inline t (const :tag "Hours" :hours)
  2824. (string :tag "Format string"))
  2825. (group :inline t (const :tag "Minutes" :minutes)
  2826. (string :tag "Format string")))))
  2827. (defcustom org-deadline-warning-days 14
  2828. "Number of days before expiration during which a deadline becomes active.
  2829. This variable governs the display in sparse trees and in the agenda.
  2830. When 0 or negative, it means use this number (the absolute value of it)
  2831. even if a deadline has a different individual lead time specified.
  2832. Custom commands can set this variable in the options section."
  2833. :group 'org-time
  2834. :group 'org-agenda-daily/weekly
  2835. :type 'integer)
  2836. (defcustom org-scheduled-delay-days 0
  2837. "Number of days before a scheduled item becomes active.
  2838. This variable governs the display in sparse trees and in the agenda.
  2839. The default value (i.e. 0) means: don't delay scheduled item.
  2840. When negative, it means use this number (the absolute value of it)
  2841. even if a scheduled item has a different individual delay time
  2842. specified.
  2843. Custom commands can set this variable in the options section."
  2844. :group 'org-time
  2845. :group 'org-agenda-daily/weekly
  2846. :version "24.4"
  2847. :package-version '(Org . "8.0")
  2848. :type 'integer)
  2849. (defcustom org-read-date-prefer-future t
  2850. "Non-nil means assume future for incomplete date input from user.
  2851. This affects the following situations:
  2852. 1. The user gives a month but not a year.
  2853. For example, if it is April and you enter \"feb 2\", this will be read
  2854. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2855. 2. The user gives a day, but no month.
  2856. For example, if today is the 15th, and you enter \"3\", Org-mode will
  2857. read this as the third of *next* month. However, if you enter \"17\",
  2858. it will be considered as *this* month.
  2859. If you set this variable to the symbol `time', then also the following
  2860. will work:
  2861. 3. If the user gives a time.
  2862. If the time is before now, it will be interpreted as tomorrow.
  2863. Currently none of this works for ISO week specifications.
  2864. When this option is nil, the current day, month and year will always be
  2865. used as defaults.
  2866. See also `org-agenda-jump-prefer-future'."
  2867. :group 'org-time
  2868. :type '(choice
  2869. (const :tag "Never" nil)
  2870. (const :tag "Check month and day" t)
  2871. (const :tag "Check month, day, and time" time)))
  2872. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2873. "Should the agenda jump command prefer the future for incomplete dates?
  2874. The default is to do the same as configured in `org-read-date-prefer-future'.
  2875. But you can also set a deviating value here.
  2876. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2877. :group 'org-agenda
  2878. :group 'org-time
  2879. :version "24.1"
  2880. :type '(choice
  2881. (const :tag "Use org-read-date-prefer-future"
  2882. org-read-date-prefer-future)
  2883. (const :tag "Never" nil)
  2884. (const :tag "Always" t)))
  2885. (defcustom org-read-date-force-compatible-dates t
  2886. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2887. Depending on the system Emacs is running on, certain dates cannot
  2888. be represented with the type used internally to represent time.
  2889. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2890. correctly. Some systems allow for earlier dates, some for later,
  2891. some for both. One way to find out it to insert any date into an
  2892. Org buffer, putting the cursor on the year and hitting S-up and
  2893. S-down to test the range.
  2894. When this variable is set to t, the date/time prompt will not let
  2895. you specify dates outside the 1970-2037 range, so it is certain that
  2896. these dates will work in whatever version of Emacs you are
  2897. running, and also that you can move a file from one Emacs implementation
  2898. to another. WHenever Org is forcing the year for you, it will display
  2899. a message and beep.
  2900. When this variable is nil, Org will check if the date is
  2901. representable in the specific Emacs implementation you are using.
  2902. If not, it will force a year, usually the current year, and beep
  2903. to remind you. Currently this setting is not recommended because
  2904. the likelihood that you will open your Org files in an Emacs that
  2905. has limited date range is not negligible.
  2906. A workaround for this problem is to use diary sexp dates for time
  2907. stamps outside of this range."
  2908. :group 'org-time
  2909. :version "24.1"
  2910. :type 'boolean)
  2911. (defcustom org-read-date-display-live t
  2912. "Non-nil means display current interpretation of date prompt live.
  2913. This display will be in an overlay, in the minibuffer."
  2914. :group 'org-time
  2915. :type 'boolean)
  2916. (defcustom org-read-date-popup-calendar t
  2917. "Non-nil means pop up a calendar when prompting for a date.
  2918. In the calendar, the date can be selected with mouse-1. However, the
  2919. minibuffer will also be active, and you can simply enter the date as well.
  2920. When nil, only the minibuffer will be available."
  2921. :group 'org-time
  2922. :type 'boolean)
  2923. (defvaralias 'org-popup-calendar-for-date-prompt
  2924. 'org-read-date-popup-calendar)
  2925. (defcustom org-extend-today-until 0
  2926. "The hour when your day really ends. Must be an integer.
  2927. This has influence for the following applications:
  2928. - When switching the agenda to \"today\". It it is still earlier than
  2929. the time given here, the day recognized as TODAY is actually yesterday.
  2930. - When a date is read from the user and it is still before the time given
  2931. here, the current date and time will be assumed to be yesterday, 23:59.
  2932. Also, timestamps inserted in capture templates follow this rule.
  2933. IMPORTANT: This is a feature whose implementation is and likely will
  2934. remain incomplete. Really, it is only here because past midnight seems to
  2935. be the favorite working time of John Wiegley :-)"
  2936. :group 'org-time
  2937. :type 'integer)
  2938. (defcustom org-use-effective-time nil
  2939. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2940. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2941. \"effective time\" of any timestamps between midnight and 8am will be
  2942. 23:59 of the previous day."
  2943. :group 'org-time
  2944. :version "24.1"
  2945. :type 'boolean)
  2946. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2947. "When non-nil, use the last clock out time for `org-todo'.
  2948. Note that this option has precedence over the combined use of
  2949. `org-use-effective-time' and `org-extend-today-until'."
  2950. :group 'org-time
  2951. :version "24.4"
  2952. :package-version '(Org . "8.0")
  2953. :type 'boolean)
  2954. (defcustom org-edit-timestamp-down-means-later nil
  2955. "Non-nil means S-down will increase the time in a time stamp.
  2956. When nil, S-up will increase."
  2957. :group 'org-time
  2958. :type 'boolean)
  2959. (defcustom org-calendar-follow-timestamp-change t
  2960. "Non-nil means make the calendar window follow timestamp changes.
  2961. When a timestamp is modified and the calendar window is visible, it will be
  2962. moved to the new date."
  2963. :group 'org-time
  2964. :type 'boolean)
  2965. (defgroup org-tags nil
  2966. "Options concerning tags in Org-mode."
  2967. :tag "Org Tags"
  2968. :group 'org)
  2969. (defcustom org-tag-alist nil
  2970. "Default tags available in Org files.
  2971. The value of this variable is an alist. Associations either:
  2972. (TAG)
  2973. (TAG . SELECT)
  2974. (SPECIAL)
  2975. where TAG is a tag as a string, SELECT is a character, used to
  2976. select that tag through the fast tag selection interface, and
  2977. SPECIAL is one of the following keywords: `:startgroup',
  2978. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2979. `:newline'. These keywords are used to define a hierarchy of
  2980. tags. See manual for details.
  2981. When this variable is nil, Org mode bases tag input on what is
  2982. already in the buffer. The value can be overridden locally by
  2983. using a TAGS keyword, e.g.,
  2984. #+TAGS: tag1 tag2
  2985. See also `org-tag-persistent-alist' to sidestep this behavior."
  2986. :group 'org-tags
  2987. :type '(repeat
  2988. (choice
  2989. (cons (string :tag "Tag name")
  2990. (character :tag "Access char"))
  2991. (const :tag "Start radio group" (:startgroup))
  2992. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2993. (const :tag "Group tags delimiter" (:grouptags))
  2994. (const :tag "End radio group" (:endgroup))
  2995. (const :tag "End tag group, non distinct" (:endgrouptag))
  2996. (const :tag "New line" (:newline)))))
  2997. (defcustom org-tag-persistent-alist nil
  2998. "Tags always available in Org files.
  2999. The value of this variable is an alist. Associations either:
  3000. (TAG)
  3001. (TAG . SELECT)
  3002. (SPECIAL)
  3003. where TAG is a tag as a string, SELECT is a character, used to
  3004. select that tag through the fast tag selection interface, and
  3005. SPECIAL is one of the following keywords: `:startgroup',
  3006. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3007. `:newline'. These keywords are used to define a hierarchy of
  3008. tags. See manual for details.
  3009. Unlike to `org-tag-alist', tags defined in this variable do not
  3010. depend on a local TAGS keyword. Instead, to disable these tags
  3011. on a per-file basis, insert anywhere in the file:
  3012. #+STARTUP: noptag"
  3013. :group 'org-tags
  3014. :type '(repeat
  3015. (choice
  3016. (cons (string :tag "Tag name")
  3017. (character :tag "Access char"))
  3018. (const :tag "Start radio group" (:startgroup))
  3019. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3020. (const :tag "Group tags delimiter" (:grouptags))
  3021. (const :tag "End radio group" (:endgroup))
  3022. (const :tag "End tag group, non distinct" (:endgrouptag))
  3023. (const :tag "New line" (:newline)))))
  3024. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3025. "If non-nil, always offer completion for all tags of all agenda files.
  3026. Instead of customizing this variable directly, you might want to
  3027. set it locally for capture buffers, because there no list of
  3028. tags in that file can be created dynamically (there are none).
  3029. (add-hook \\='org-capture-mode-hook
  3030. (lambda ()
  3031. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3032. :group 'org-tags
  3033. :version "24.1"
  3034. :type 'boolean)
  3035. (defvar org-file-tags nil
  3036. "List of tags that can be inherited by all entries in the file.
  3037. The tags will be inherited if the variable `org-use-tag-inheritance'
  3038. says they should be.
  3039. This variable is populated from #+FILETAGS lines.")
  3040. (defcustom org-use-fast-tag-selection 'auto
  3041. "Non-nil means use fast tag selection scheme.
  3042. This is a special interface to select and deselect tags with single keys.
  3043. When nil, fast selection is never used.
  3044. When the symbol `auto', fast selection is used if and only if selection
  3045. characters for tags have been configured, either through the variable
  3046. `org-tag-alist' or through a #+TAGS line in the buffer.
  3047. When t, fast selection is always used and selection keys are assigned
  3048. automatically if necessary."
  3049. :group 'org-tags
  3050. :type '(choice
  3051. (const :tag "Always" t)
  3052. (const :tag "Never" nil)
  3053. (const :tag "When selection characters are configured" auto)))
  3054. (defcustom org-fast-tag-selection-single-key nil
  3055. "Non-nil means fast tag selection exits after first change.
  3056. When nil, you have to press RET to exit it.
  3057. During fast tag selection, you can toggle this flag with `C-c'.
  3058. This variable can also have the value `expert'. In this case, the window
  3059. displaying the tags menu is not even shown, until you press C-c again."
  3060. :group 'org-tags
  3061. :type '(choice
  3062. (const :tag "No" nil)
  3063. (const :tag "Yes" t)
  3064. (const :tag "Expert" expert)))
  3065. (defvar org-fast-tag-selection-include-todo nil
  3066. "Non-nil means fast tags selection interface will also offer TODO states.
  3067. This is an undocumented feature, you should not rely on it.")
  3068. (defcustom org-tags-column -77
  3069. "The column to which tags should be indented in a headline.
  3070. If this number is positive, it specifies the column. If it is negative,
  3071. it means that the tags should be flushright to that column. For example,
  3072. -80 works well for a normal 80 character screen.
  3073. When 0, place tags directly after headline text, with only one space in
  3074. between."
  3075. :group 'org-tags
  3076. :type 'integer)
  3077. (defcustom org-auto-align-tags t
  3078. "Non-nil keeps tags aligned when modifying headlines.
  3079. Some operations (i.e. demoting) change the length of a headline and
  3080. therefore shift the tags around. With this option turned on, after
  3081. each such operation the tags are again aligned to `org-tags-column'."
  3082. :group 'org-tags
  3083. :type 'boolean)
  3084. (defcustom org-use-tag-inheritance t
  3085. "Non-nil means tags in levels apply also for sublevels.
  3086. When nil, only the tags directly given in a specific line apply there.
  3087. This may also be a list of tags that should be inherited, or a regexp that
  3088. matches tags that should be inherited. Additional control is possible
  3089. with the variable `org-tags-exclude-from-inheritance' which gives an
  3090. explicit list of tags to be excluded from inheritance, even if the value of
  3091. `org-use-tag-inheritance' would select it for inheritance.
  3092. If this option is t, a match early-on in a tree can lead to a large
  3093. number of matches in the subtree when constructing the agenda or creating
  3094. a sparse tree. If you only want to see the first match in a tree during
  3095. a search, check out the variable `org-tags-match-list-sublevels'."
  3096. :group 'org-tags
  3097. :type '(choice
  3098. (const :tag "Not" nil)
  3099. (const :tag "Always" t)
  3100. (repeat :tag "Specific tags" (string :tag "Tag"))
  3101. (regexp :tag "Tags matched by regexp")))
  3102. (defcustom org-tags-exclude-from-inheritance nil
  3103. "List of tags that should never be inherited.
  3104. This is a way to exclude a few tags from inheritance. For way to do
  3105. the opposite, to actively allow inheritance for selected tags,
  3106. see the variable `org-use-tag-inheritance'."
  3107. :group 'org-tags
  3108. :type '(repeat (string :tag "Tag")))
  3109. (defun org-tag-inherit-p (tag)
  3110. "Check if TAG is one that should be inherited."
  3111. (cond
  3112. ((member tag org-tags-exclude-from-inheritance) nil)
  3113. ((eq org-use-tag-inheritance t) t)
  3114. ((not org-use-tag-inheritance) nil)
  3115. ((stringp org-use-tag-inheritance)
  3116. (string-match org-use-tag-inheritance tag))
  3117. ((listp org-use-tag-inheritance)
  3118. (member tag org-use-tag-inheritance))
  3119. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3120. (defcustom org-tags-match-list-sublevels t
  3121. "Non-nil means list also sublevels of headlines matching a search.
  3122. This variable applies to tags/property searches, and also to stuck
  3123. projects because this search is based on a tags match as well.
  3124. When set to the symbol `indented', sublevels are indented with
  3125. leading dots.
  3126. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3127. the sublevels of a headline matching a tag search often also match
  3128. the same search. Listing all of them can create very long lists.
  3129. Setting this variable to nil causes subtrees of a match to be skipped.
  3130. This variable is semi-obsolete and probably should always be true. It
  3131. is better to limit inheritance to certain tags using the variables
  3132. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3133. :group 'org-tags
  3134. :type '(choice
  3135. (const :tag "No, don't list them" nil)
  3136. (const :tag "Yes, do list them" t)
  3137. (const :tag "List them, indented with leading dots" indented)))
  3138. (defcustom org-tags-sort-function nil
  3139. "When set, tags are sorted using this function as a comparator."
  3140. :group 'org-tags
  3141. :type '(choice
  3142. (const :tag "No sorting" nil)
  3143. (const :tag "Alphabetical" string<)
  3144. (const :tag "Reverse alphabetical" string>)
  3145. (function :tag "Custom function" nil)))
  3146. (defvar org-tags-history nil
  3147. "History of minibuffer reads for tags.")
  3148. (defvar org-last-tags-completion-table nil
  3149. "The last used completion table for tags.")
  3150. (defvar org-after-tags-change-hook nil
  3151. "Hook that is run after the tags in a line have changed.")
  3152. (defgroup org-properties nil
  3153. "Options concerning properties in Org-mode."
  3154. :tag "Org Properties"
  3155. :group 'org)
  3156. (defcustom org-property-format "%-10s %s"
  3157. "How property key/value pairs should be formatted by `indent-line'.
  3158. When `indent-line' hits a property definition, it will format the line
  3159. according to this format, mainly to make sure that the values are
  3160. lined-up with respect to each other."
  3161. :group 'org-properties
  3162. :type 'string)
  3163. (defcustom org-properties-postprocess-alist nil
  3164. "Alist of properties and functions to adjust inserted values.
  3165. Elements of this alist must be of the form
  3166. ([string] [function])
  3167. where [string] must be a property name and [function] must be a
  3168. lambda expression: this lambda expression must take one argument,
  3169. the value to adjust, and return the new value as a string.
  3170. For example, this element will allow the property \"Remaining\"
  3171. to be updated wrt the relation between the \"Effort\" property
  3172. and the clock summary:
  3173. ((\"Remaining\" (lambda(value)
  3174. (let ((clocksum (org-clock-sum-current-item))
  3175. (effort (org-duration-string-to-minutes
  3176. (org-entry-get (point) \"Effort\"))))
  3177. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3178. :group 'org-properties
  3179. :version "24.1"
  3180. :type '(alist :key-type (string :tag "Property")
  3181. :value-type (function :tag "Function")))
  3182. (defcustom org-use-property-inheritance nil
  3183. "Non-nil means properties apply also for sublevels.
  3184. This setting is chiefly used during property searches. Turning it on can
  3185. cause significant overhead when doing a search, which is why it is not
  3186. on by default.
  3187. When nil, only the properties directly given in the current entry count.
  3188. When t, every property is inherited. The value may also be a list of
  3189. properties that should have inheritance, or a regular expression matching
  3190. properties that should be inherited.
  3191. However, note that some special properties use inheritance under special
  3192. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3193. and the properties ending in \"_ALL\" when they are used as descriptor
  3194. for valid values of a property.
  3195. Note for programmers:
  3196. When querying an entry with `org-entry-get', you can control if inheritance
  3197. should be used. By default, `org-entry-get' looks only at the local
  3198. properties. You can request inheritance by setting the inherit argument
  3199. to t (to force inheritance) or to `selective' (to respect the setting
  3200. in this variable)."
  3201. :group 'org-properties
  3202. :type '(choice
  3203. (const :tag "Not" nil)
  3204. (const :tag "Always" t)
  3205. (repeat :tag "Specific properties" (string :tag "Property"))
  3206. (regexp :tag "Properties matched by regexp")))
  3207. (defun org-property-inherit-p (property)
  3208. "Check if PROPERTY is one that should be inherited."
  3209. (cond
  3210. ((eq org-use-property-inheritance t) t)
  3211. ((not org-use-property-inheritance) nil)
  3212. ((stringp org-use-property-inheritance)
  3213. (string-match org-use-property-inheritance property))
  3214. ((listp org-use-property-inheritance)
  3215. (member property org-use-property-inheritance))
  3216. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3217. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3218. "The default column format, if no other format has been defined.
  3219. This variable can be set on the per-file basis by inserting a line
  3220. #+COLUMNS: %25ITEM ....."
  3221. :group 'org-properties
  3222. :type 'string)
  3223. (defcustom org-columns-ellipses ".."
  3224. "The ellipses to be used when a field in column view is truncated.
  3225. When this is the empty string, as many characters as possible are shown,
  3226. but then there will be no visual indication that the field has been truncated.
  3227. When this is a string of length N, the last N characters of a truncated
  3228. field are replaced by this string. If the column is narrower than the
  3229. ellipses string, only part of the ellipses string will be shown."
  3230. :group 'org-properties
  3231. :type 'string)
  3232. (defconst org-global-properties-fixed
  3233. '(("VISIBILITY_ALL" . "folded children content all")
  3234. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3235. "List of property/value pairs that can be inherited by any entry.
  3236. These are fixed values, for the preset properties. The user variable
  3237. that can be used to add to this list is `org-global-properties'.
  3238. The entries in this list are cons cells where the car is a property
  3239. name and cdr is a string with the value. If the value represents
  3240. multiple items like an \"_ALL\" property, separate the items by
  3241. spaces.")
  3242. (defcustom org-global-properties nil
  3243. "List of property/value pairs that can be inherited by any entry.
  3244. This list will be combined with the constant `org-global-properties-fixed'.
  3245. The entries in this list are cons cells where the car is a property
  3246. name and cdr is a string with the value.
  3247. You can set buffer-local values for the same purpose in the variable
  3248. `org-file-properties' this by adding lines like
  3249. #+PROPERTY: NAME VALUE"
  3250. :group 'org-properties
  3251. :type '(repeat
  3252. (cons (string :tag "Property")
  3253. (string :tag "Value"))))
  3254. (defvar-local org-file-properties nil
  3255. "List of property/value pairs that can be inherited by any entry.
  3256. Valid for the current buffer.
  3257. This variable is populated from #+PROPERTY lines.")
  3258. (defgroup org-agenda nil
  3259. "Options concerning agenda views in Org-mode."
  3260. :tag "Org Agenda"
  3261. :group 'org)
  3262. (defvar-local org-category nil
  3263. "Variable used by org files to set a category for agenda display.
  3264. Such files should use a file variable to set it, for example
  3265. # -*- mode: org; org-category: \"ELisp\"
  3266. or contain a special line
  3267. #+CATEGORY: ELisp
  3268. If the file does not specify a category, then file's base name
  3269. is used instead.")
  3270. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3271. (defcustom org-agenda-files nil
  3272. "The files to be used for agenda display.
  3273. Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
  3274. \\[org-remove-file]. You can also use customize to edit the list.
  3275. If an entry is a directory, all files in that directory that are matched by
  3276. `org-agenda-file-regexp' will be part of the file list.
  3277. If the value of the variable is not a list but a single file name, then
  3278. the list of agenda files is actually stored and maintained in that file, one
  3279. agenda file per line. In this file paths can be given relative to
  3280. `org-directory'. Tilde expansion and environment variable substitution
  3281. are also made."
  3282. :group 'org-agenda
  3283. :type '(choice
  3284. (repeat :tag "List of files and directories" file)
  3285. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3286. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3287. "Regular expression to match files for `org-agenda-files'.
  3288. If any element in the list in that variable contains a directory instead
  3289. of a normal file, all files in that directory that are matched by this
  3290. regular expression will be included."
  3291. :group 'org-agenda
  3292. :type 'regexp)
  3293. (defcustom org-agenda-text-search-extra-files nil
  3294. "List of extra files to be searched by text search commands.
  3295. These files will be searched in addition to the agenda files by the
  3296. commands `org-search-view' (`\\[org-agenda] s') \
  3297. and `org-occur-in-agenda-files'.
  3298. Note that these files will only be searched for text search commands,
  3299. not for the other agenda views like todo lists, tag searches or the weekly
  3300. agenda. This variable is intended to list notes and possibly archive files
  3301. that should also be searched by these two commands.
  3302. In fact, if the first element in the list is the symbol `agenda-archives',
  3303. then all archive files of all agenda files will be added to the search
  3304. scope."
  3305. :group 'org-agenda
  3306. :type '(set :greedy t
  3307. (const :tag "Agenda Archives" agenda-archives)
  3308. (repeat :inline t (file))))
  3309. (defvaralias 'org-agenda-multi-occur-extra-files
  3310. 'org-agenda-text-search-extra-files)
  3311. (defcustom org-agenda-skip-unavailable-files nil
  3312. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3313. A nil value means to remove them, after a query, from the list."
  3314. :group 'org-agenda
  3315. :type 'boolean)
  3316. (defcustom org-calendar-to-agenda-key [?c]
  3317. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3318. The command `org-calendar-goto-agenda' will be bound to this key. The
  3319. default is the character `c' because then `c' can be used to switch back and
  3320. forth between agenda and calendar."
  3321. :group 'org-agenda
  3322. :type 'sexp)
  3323. (defcustom org-calendar-insert-diary-entry-key [?i]
  3324. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3325. This option is irrelevant until `org-agenda-diary-file' has been configured
  3326. to point to an Org-mode file. When that is the case, the command
  3327. `org-agenda-diary-entry' will be bound to the key given here, by default
  3328. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3329. if you want to continue doing this, you need to change this to a different
  3330. key."
  3331. :group 'org-agenda
  3332. :type 'sexp)
  3333. (defcustom org-agenda-diary-file 'diary-file
  3334. "File to which to add new entries with the `i' key in agenda and calendar.
  3335. When this is the symbol `diary-file', the functionality in the Emacs
  3336. calendar will be used to add entries to the `diary-file'. But when this
  3337. points to a file, `org-agenda-diary-entry' will be used instead."
  3338. :group 'org-agenda
  3339. :type '(choice
  3340. (const :tag "The standard Emacs diary file" diary-file)
  3341. (file :tag "Special Org file diary entries")))
  3342. (eval-after-load "calendar"
  3343. '(progn
  3344. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3345. 'org-calendar-goto-agenda)
  3346. (add-hook 'calendar-mode-hook
  3347. (lambda ()
  3348. (unless (eq org-agenda-diary-file 'diary-file)
  3349. (define-key calendar-mode-map
  3350. org-calendar-insert-diary-entry-key
  3351. 'org-agenda-diary-entry))))))
  3352. (defgroup org-latex nil
  3353. "Options for embedding LaTeX code into Org-mode."
  3354. :tag "Org LaTeX"
  3355. :group 'org)
  3356. (defcustom org-format-latex-options
  3357. '(:foreground default :background default :scale 1.0
  3358. :html-foreground "Black" :html-background "Transparent"
  3359. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3360. "Options for creating images from LaTeX fragments.
  3361. This is a property list with the following properties:
  3362. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3363. `default' means use the foreground of the default face.
  3364. `auto' means use the foreground from the text face.
  3365. :background the background color, or \"Transparent\".
  3366. `default' means use the background of the default face.
  3367. `auto' means use the background from the text face.
  3368. :scale a scaling factor for the size of the images, to get more pixels
  3369. :html-foreground, :html-background, :html-scale
  3370. the same numbers for HTML export.
  3371. :matchers a list indicating which matchers should be used to
  3372. find LaTeX fragments. Valid members of this list are:
  3373. \"begin\" find environments
  3374. \"$1\" find single characters surrounded by $.$
  3375. \"$\" find math expressions surrounded by $...$
  3376. \"$$\" find math expressions surrounded by $$....$$
  3377. \"\\(\" find math expressions surrounded by \\(...\\)
  3378. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3379. :group 'org-latex
  3380. :type 'plist)
  3381. (defcustom org-format-latex-signal-error t
  3382. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3383. When nil, just push out a message."
  3384. :group 'org-latex
  3385. :version "24.1"
  3386. :type 'boolean)
  3387. (defcustom org-latex-to-mathml-jar-file nil
  3388. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3389. Use this to specify additional executable file say a jar file.
  3390. When using MathToWeb as the converter, specify the full-path to
  3391. your mathtoweb.jar file."
  3392. :group 'org-latex
  3393. :version "24.1"
  3394. :type '(choice
  3395. (const :tag "None" nil)
  3396. (file :tag "JAR file" :must-match t)))
  3397. (defcustom org-latex-to-mathml-convert-command nil
  3398. "Command to convert LaTeX fragments to MathML.
  3399. Replace format-specifiers in the command as noted below and use
  3400. `shell-command' to convert LaTeX to MathML.
  3401. %j: Executable file in fully expanded form as specified by
  3402. `org-latex-to-mathml-jar-file'.
  3403. %I: Input LaTeX file in fully expanded form.
  3404. %i: The latex fragment to be converted.
  3405. %o: Output MathML file.
  3406. This command is used by `org-create-math-formula'.
  3407. When using MathToWeb as the converter, set this option to
  3408. \"java -jar %j -unicode -force -df %o %I\".
  3409. When using LaTeXML set this option to
  3410. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3411. :group 'org-latex
  3412. :version "24.1"
  3413. :type '(choice
  3414. (const :tag "None" nil)
  3415. (string :tag "\nShell command")))
  3416. (defcustom org-preview-latex-default-process 'dvipng
  3417. "The default process to convert LaTeX fragments to image files.
  3418. All available processes and theirs documents can be found in
  3419. `org-preview-latex-process-alist', which see."
  3420. :group 'org-latex
  3421. :version "25.2"
  3422. :package-version '(Org . "9.0")
  3423. :type 'symbol)
  3424. (defcustom org-preview-latex-process-alist
  3425. '((dvipng
  3426. :programs ("latex" "dvipng" "gs")
  3427. :description "dvi > png"
  3428. :message "you need to install the programs: latex, dvipng and ghostscript."
  3429. :image-input-type "dvi"
  3430. :image-output-type "png"
  3431. :image-size-adjust (1.0 . 1.0)
  3432. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3433. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
  3434. (dvisvgm
  3435. :programs ("latex" "dvisvgm" "gs")
  3436. :description "dvi > svg"
  3437. :message "you need to install the programs: latex, dvisvgm and ghostscript."
  3438. :use-xcolor t
  3439. :image-input-type "dvi"
  3440. :image-output-type "svg"
  3441. :image-size-adjust (1.7 . 1.5)
  3442. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3443. :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
  3444. (imagemagick
  3445. :programs ("latex" "convert" "gs")
  3446. :description "pdf > png"
  3447. :message
  3448. "you need to install the programs: latex, imagemagick and ghostscript."
  3449. :use-xcolor t
  3450. :image-input-type "pdf"
  3451. :image-output-type "png"
  3452. :image-size-adjust (1.0 . 1.0)
  3453. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3454. :image-converter
  3455. ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
  3456. "Definitions of external processes for LaTeX previewing.
  3457. Org mode can use some external commands to generate TeX snippet's images for
  3458. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3459. `org-create-formula-image' how to call them.
  3460. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3461. PROPERTIES accepts the following attributes:
  3462. :programs list of strings, required programs.
  3463. :description string, describe the process.
  3464. :message string, message it when required programs cannot be found.
  3465. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3466. :image-output-type string, output file type of image converter (e.g., \"png\").
  3467. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3468. deal with background and foreground color of image.
  3469. Otherwise, dvipng style background and foregroud color
  3470. format are generated. You may then refer to them in
  3471. command options with \"%F\" and \"%B\".
  3472. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3473. image size showed in buffer and the cdr element is for
  3474. HTML file. This option is only useful for process
  3475. developers, users should use variable
  3476. `org-format-latex-options' instead.
  3477. :post-clean list of strings, files matched are to be cleaned up once
  3478. the image is generated. When nil, the files with \".dvi\",
  3479. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3480. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3481. be cleaned up.
  3482. :latex-header list of strings, the LaTeX header of the snippet file.
  3483. When nil, the fallback value is used instead, which is
  3484. controlled by `org-format-latex-header',
  3485. `org-latex-default-packages-alist' and
  3486. `org-latex-packages-alist', which see.
  3487. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3488. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3489. replaced with values defined below.
  3490. :image-converter list of image converter commands strings. Each of them is
  3491. given to the shell and supports any of the following
  3492. place-holders defined below.
  3493. Place-holders used by `:image-converter' and `:latex-compiler':
  3494. %f input file name.
  3495. %b base name of input file.
  3496. %o base directory of input file.
  3497. Place-holders only used by `:image-converter':
  3498. %F foreground of image
  3499. %B background of image
  3500. %D dpi, which is used to adjust image size by some processing commands.
  3501. %S the image size scale ratio, which is used to adjust image size by some
  3502. processing commands."
  3503. :group 'org-latex
  3504. :version "25.2"
  3505. :package-version '(Org . "9.0")
  3506. :type '(alist :tag "LaTeX to image backends"
  3507. :value-type (plist)))
  3508. (defcustom org-preview-latex-image-directory "ltximg/"
  3509. "Path to store latex preview images.
  3510. A relative path here creates many directories relative to the
  3511. processed org files paths. An absolute path puts all preview
  3512. images at the same place."
  3513. :group 'org-latex
  3514. :version "25.1"
  3515. :package-version '(Org . "9.0")
  3516. :type 'string)
  3517. (defun org-format-latex-mathml-available-p ()
  3518. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3519. (save-match-data
  3520. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3521. org-latex-to-mathml-convert-command)
  3522. (let ((executable (car (split-string
  3523. org-latex-to-mathml-convert-command))))
  3524. (when (executable-find executable)
  3525. (if (string-match
  3526. "%j" org-latex-to-mathml-convert-command)
  3527. (file-readable-p org-latex-to-mathml-jar-file)
  3528. t))))))
  3529. (defcustom org-format-latex-header "\\documentclass{article}
  3530. \\usepackage[usenames]{color}
  3531. \[PACKAGES]
  3532. \[DEFAULT-PACKAGES]
  3533. \\pagestyle{empty} % do not remove
  3534. % The settings below are copied from fullpage.sty
  3535. \\setlength{\\textwidth}{\\paperwidth}
  3536. \\addtolength{\\textwidth}{-3cm}
  3537. \\setlength{\\oddsidemargin}{1.5cm}
  3538. \\addtolength{\\oddsidemargin}{-2.54cm}
  3539. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3540. \\setlength{\\textheight}{\\paperheight}
  3541. \\addtolength{\\textheight}{-\\headheight}
  3542. \\addtolength{\\textheight}{-\\headsep}
  3543. \\addtolength{\\textheight}{-\\footskip}
  3544. \\addtolength{\\textheight}{-3cm}
  3545. \\setlength{\\topmargin}{1.5cm}
  3546. \\addtolength{\\topmargin}{-2.54cm}"
  3547. "The document header used for processing LaTeX fragments.
  3548. It is imperative that this header make sure that no page number
  3549. appears on the page. The package defined in the variables
  3550. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3551. will either replace the placeholder \"[PACKAGES]\" in this
  3552. header, or they will be appended."
  3553. :group 'org-latex
  3554. :type 'string)
  3555. (defun org-set-packages-alist (var val)
  3556. "Set the packages alist and make sure it has 3 elements per entry."
  3557. (set var (mapcar (lambda (x)
  3558. (if (and (consp x) (= (length x) 2))
  3559. (list (car x) (nth 1 x) t)
  3560. x))
  3561. val)))
  3562. (defun org-get-packages-alist (var)
  3563. "Get the packages alist and make sure it has 3 elements per entry."
  3564. (mapcar (lambda (x)
  3565. (if (and (consp x) (= (length x) 2))
  3566. (list (car x) (nth 1 x) t)
  3567. x))
  3568. (default-value var)))
  3569. (defcustom org-latex-default-packages-alist
  3570. '(("AUTO" "inputenc" t ("pdflatex"))
  3571. ("T1" "fontenc" t ("pdflatex"))
  3572. ("" "graphicx" t)
  3573. ("" "grffile" t)
  3574. ("" "longtable" nil)
  3575. ("" "wrapfig" nil)
  3576. ("" "rotating" nil)
  3577. ("normalem" "ulem" t)
  3578. ("" "amsmath" t)
  3579. ("" "textcomp" t)
  3580. ("" "amssymb" t)
  3581. ("" "capt-of" nil)
  3582. ("" "hyperref" nil))
  3583. "Alist of default packages to be inserted in the header.
  3584. Change this only if one of the packages here causes an
  3585. incompatibility with another package you are using.
  3586. The packages in this list are needed by one part or another of
  3587. Org mode to function properly:
  3588. - inputenc, fontenc: for basic font and character selection
  3589. - graphicx: for including images
  3590. - grffile: allow periods and spaces in graphics file names
  3591. - longtable: For multipage tables
  3592. - wrapfig: for figure placement
  3593. - rotating: for sideways figures and tables
  3594. - ulem: for underline and strike-through
  3595. - amsmath: for subscript and superscript and math environments
  3596. - textcomp, amssymb: for various symbols used
  3597. for interpreting the entities in `org-entities'. You can skip
  3598. some of these packages if you don't use any of their symbols.
  3599. - capt-of: for captions outside of floats
  3600. - hyperref: for cross references
  3601. Therefore you should not modify this variable unless you know
  3602. what you are doing. The one reason to change it anyway is that
  3603. you might be loading some other package that conflicts with one
  3604. of the default packages. Each element is either a cell or
  3605. a string.
  3606. A cell is of the format
  3607. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3608. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3609. when compiling LaTeX snippets into images for inclusion into
  3610. non-LaTeX output. COMPILERS is a list of compilers that should
  3611. include the package, see `org-latex-compiler'. If the document
  3612. compiler is not in the list, and the list is non-nil, the package
  3613. will not be inserted in the final document.
  3614. A string will be inserted as-is in the header of the document."
  3615. :group 'org-latex
  3616. :group 'org-export-latex
  3617. :set 'org-set-packages-alist
  3618. :get 'org-get-packages-alist
  3619. :version "25.1"
  3620. :package-version '(Org . "8.3")
  3621. :type '(repeat
  3622. (choice
  3623. (list :tag "options/package pair"
  3624. (string :tag "options")
  3625. (string :tag "package")
  3626. (boolean :tag "Snippet"))
  3627. (string :tag "A line of LaTeX"))))
  3628. (defcustom org-latex-packages-alist nil
  3629. "Alist of packages to be inserted in every LaTeX header.
  3630. These will be inserted after `org-latex-default-packages-alist'.
  3631. Each element is either a cell or a string.
  3632. A cell is of the format:
  3633. (\"options\" \"package\" SNIPPET-FLAG)
  3634. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3635. needed when turning LaTeX snippets into images for inclusion into
  3636. non-LaTeX output.
  3637. A string will be inserted as-is in the header of the document.
  3638. Make sure that you only list packages here which:
  3639. - you want in every file;
  3640. - do not conflict with the setup in `org-format-latex-header';
  3641. - do not conflict with the default packages in
  3642. `org-latex-default-packages-alist'."
  3643. :group 'org-latex
  3644. :group 'org-export-latex
  3645. :set 'org-set-packages-alist
  3646. :get 'org-get-packages-alist
  3647. :type '(repeat
  3648. (choice
  3649. (list :tag "options/package pair"
  3650. (string :tag "options")
  3651. (string :tag "package")
  3652. (boolean :tag "Snippet"))
  3653. (string :tag "A line of LaTeX"))))
  3654. (defgroup org-appearance nil
  3655. "Settings for Org-mode appearance."
  3656. :tag "Org Appearance"
  3657. :group 'org)
  3658. (defcustom org-level-color-stars-only nil
  3659. "Non-nil means fontify only the stars in each headline.
  3660. When nil, the entire headline is fontified.
  3661. Changing it requires restart of `font-lock-mode' to become effective
  3662. also in regions already fontified."
  3663. :group 'org-appearance
  3664. :type 'boolean)
  3665. (defcustom org-hide-leading-stars nil
  3666. "Non-nil means hide the first N-1 stars in a headline.
  3667. This works by using the face `org-hide' for these stars. This
  3668. face is white for a light background, and black for a dark
  3669. background. You may have to customize the face `org-hide' to
  3670. make this work.
  3671. Changing it requires restart of `font-lock-mode' to become effective
  3672. also in regions already fontified.
  3673. You may also set this on a per-file basis by adding one of the following
  3674. lines to the buffer:
  3675. #+STARTUP: hidestars
  3676. #+STARTUP: showstars"
  3677. :group 'org-appearance
  3678. :type 'boolean)
  3679. (defcustom org-hidden-keywords nil
  3680. "List of symbols corresponding to keywords to be hidden the org buffer.
  3681. For example, a value \\='(title) for this list will make the document's title
  3682. appear in the buffer without the initial #+TITLE: keyword."
  3683. :group 'org-appearance
  3684. :version "24.1"
  3685. :type '(set (const :tag "#+AUTHOR" author)
  3686. (const :tag "#+DATE" date)
  3687. (const :tag "#+EMAIL" email)
  3688. (const :tag "#+TITLE" title)))
  3689. (defcustom org-custom-properties nil
  3690. "List of properties (as strings) with a special meaning.
  3691. The default use of these custom properties is to let the user
  3692. hide them with `org-toggle-custom-properties-visibility'."
  3693. :group 'org-properties
  3694. :group 'org-appearance
  3695. :version "24.3"
  3696. :type '(repeat (string :tag "Property Name")))
  3697. (defcustom org-fontify-done-headline nil
  3698. "Non-nil means change the face of a headline if it is marked DONE.
  3699. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3700. When this is non-nil, the headline after the keyword is set to the
  3701. `org-headline-done' as an additional indication."
  3702. :group 'org-appearance
  3703. :type 'boolean)
  3704. (defcustom org-fontify-emphasized-text t
  3705. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3706. Changing this variable requires a restart of Emacs to take effect."
  3707. :group 'org-appearance
  3708. :type 'boolean)
  3709. (defcustom org-fontify-whole-heading-line nil
  3710. "Non-nil means fontify the whole line for headings.
  3711. This is useful when setting a background color for the
  3712. org-level-* faces."
  3713. :group 'org-appearance
  3714. :type 'boolean)
  3715. (defcustom org-highlight-latex-and-related nil
  3716. "Non-nil means highlight LaTeX related syntax in the buffer.
  3717. When non nil, the value should be a list containing any of the
  3718. following symbols:
  3719. `latex' Highlight LaTeX snippets and environments.
  3720. `script' Highlight subscript and superscript.
  3721. `entities' Highlight entities."
  3722. :group 'org-appearance
  3723. :version "24.4"
  3724. :package-version '(Org . "8.0")
  3725. :type '(choice
  3726. (const :tag "No highlighting" nil)
  3727. (set :greedy t :tag "Highlight"
  3728. (const :tag "LaTeX snippets and environments" latex)
  3729. (const :tag "Subscript and superscript" script)
  3730. (const :tag "Entities" entities))))
  3731. (defcustom org-hide-emphasis-markers nil
  3732. "Non-nil mean font-lock should hide the emphasis marker characters."
  3733. :group 'org-appearance
  3734. :type 'boolean)
  3735. (defcustom org-hide-macro-markers nil
  3736. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3737. :group 'org-appearance
  3738. :type 'boolean)
  3739. (defcustom org-pretty-entities nil
  3740. "Non-nil means show entities as UTF8 characters.
  3741. When nil, the \\name form remains in the buffer."
  3742. :group 'org-appearance
  3743. :version "24.1"
  3744. :type 'boolean)
  3745. (defcustom org-pretty-entities-include-sub-superscripts t
  3746. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3747. :group 'org-appearance
  3748. :version "24.1"
  3749. :type 'boolean)
  3750. (defvar org-emph-re nil
  3751. "Regular expression for matching emphasis.
  3752. After a match, the match groups contain these elements:
  3753. 0 The match of the full regular expression, including the characters
  3754. before and after the proper match
  3755. 1 The character before the proper match, or empty at beginning of line
  3756. 2 The proper match, including the leading and trailing markers
  3757. 3 The leading marker like * or /, indicating the type of highlighting
  3758. 4 The text between the emphasis markers, not including the markers
  3759. 5 The character after the match, empty at the end of a line")
  3760. (defvar org-verbatim-re nil
  3761. "Regular expression for matching verbatim text.")
  3762. (defvar org-emphasis-regexp-components) ; defined just below
  3763. (defvar org-emphasis-alist) ; defined just below
  3764. (defun org-set-emph-re (var val)
  3765. "Set variable and compute the emphasis regular expression."
  3766. (set var val)
  3767. (when (and (boundp 'org-emphasis-alist)
  3768. (boundp 'org-emphasis-regexp-components)
  3769. org-emphasis-alist org-emphasis-regexp-components)
  3770. (let* ((e org-emphasis-regexp-components)
  3771. (pre (car e))
  3772. (post (nth 1 e))
  3773. (border (nth 2 e))
  3774. (body (nth 3 e))
  3775. (nl (nth 4 e))
  3776. (body1 (concat body "*?"))
  3777. (markers (mapconcat 'car org-emphasis-alist ""))
  3778. (vmarkers (mapconcat
  3779. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3780. org-emphasis-alist "")))
  3781. ;; make sure special characters appear at the right position in the class
  3782. (if (string-match "\\^" markers)
  3783. (setq markers (concat (replace-match "" t t markers) "^")))
  3784. (if (string-match "-" markers)
  3785. (setq markers (concat (replace-match "" t t markers) "-")))
  3786. (if (string-match "\\^" vmarkers)
  3787. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3788. (if (string-match "-" vmarkers)
  3789. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3790. (if (> nl 0)
  3791. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3792. (int-to-string nl) "\\}")))
  3793. ;; Make the regexp
  3794. (setq org-emph-re
  3795. (concat "\\([" pre "]\\|^\\)"
  3796. "\\("
  3797. "\\([" markers "]\\)"
  3798. "\\("
  3799. "[^" border "]\\|"
  3800. "[^" border "]"
  3801. body1
  3802. "[^" border "]"
  3803. "\\)"
  3804. "\\3\\)"
  3805. "\\([" post "]\\|$\\)"))
  3806. (setq org-verbatim-re
  3807. (concat "\\([" pre "]\\|^\\)"
  3808. "\\("
  3809. "\\([" vmarkers "]\\)"
  3810. "\\("
  3811. "[^" border "]\\|"
  3812. "[^" border "]"
  3813. body1
  3814. "[^" border "]"
  3815. "\\)"
  3816. "\\3\\)"
  3817. "\\([" post "]\\|$\\)")))))
  3818. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3819. ;; set this option proved cumbersome. See this message/thread:
  3820. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3821. (defvar org-emphasis-regexp-components
  3822. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3823. "Components used to build the regular expression for emphasis.
  3824. This is a list with five entries. Terminology: In an emphasis string
  3825. like \" *strong word* \", we call the initial space PREMATCH, the final
  3826. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3827. and \"trong wor\" is the body. The different components in this variable
  3828. specify what is allowed/forbidden in each part:
  3829. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3830. post Chars allowed as postmatch. End of line will be allowed too.
  3831. border The chars *forbidden* as border characters.
  3832. body-regexp A regexp like \".\" to match a body character. Don't use
  3833. non-shy groups here, and don't allow newline here.
  3834. newline The maximum number of newlines allowed in an emphasis exp.
  3835. You need to reload Org or to restart Emacs after customizing this.")
  3836. (defcustom org-emphasis-alist
  3837. '(("*" bold)
  3838. ("/" italic)
  3839. ("_" underline)
  3840. ("=" org-verbatim verbatim)
  3841. ("~" org-code verbatim)
  3842. ("+" (:strike-through t)))
  3843. "Alist of characters and faces to emphasize text.
  3844. Text starting and ending with a special character will be emphasized,
  3845. for example *bold*, _underlined_ and /italic/. This variable sets the
  3846. marker characters and the face to be used by font-lock for highlighting
  3847. in Org-mode Emacs buffers.
  3848. You need to reload Org or to restart Emacs after customizing this."
  3849. :group 'org-appearance
  3850. :set 'org-set-emph-re
  3851. :version "24.4"
  3852. :package-version '(Org . "8.0")
  3853. :type '(repeat
  3854. (list
  3855. (string :tag "Marker character")
  3856. (choice
  3857. (face :tag "Font-lock-face")
  3858. (plist :tag "Face property list"))
  3859. (option (const verbatim)))))
  3860. (defvar org-protecting-blocks '("src" "example" "export")
  3861. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3862. This is needed for font-lock setup.")
  3863. ;;; Functions and variables from their packages
  3864. ;; Declared here to avoid compiler warnings
  3865. (defvar mark-active)
  3866. ;; Various packages
  3867. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3868. (declare-function calendar-forward-day "cal-move" (arg))
  3869. (declare-function calendar-goto-date "cal-move" (date))
  3870. (declare-function calendar-goto-today "cal-move" ())
  3871. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3872. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3873. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3874. (declare-function cdlatex-tab "ext:cdlatex" ())
  3875. (declare-function dired-get-filename
  3876. "dired"
  3877. (&optional localp no-error-if-not-filep))
  3878. (declare-function iswitchb-read-buffer
  3879. "iswitchb"
  3880. (prompt &optional
  3881. default require-match _predicate start matches-set))
  3882. (declare-function org-agenda-change-all-lines
  3883. "org-agenda"
  3884. (newhead hdmarker &optional fixface just-this))
  3885. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3886. "org-agenda"
  3887. (&optional end))
  3888. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3889. (declare-function org-agenda-format-item
  3890. "org-agenda"
  3891. (extra txt &optional level category tags dotime
  3892. remove-re habitp))
  3893. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3894. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3895. (declare-function org-agenda-save-markers-for-cut-and-paste
  3896. "org-agenda"
  3897. (beg end))
  3898. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3899. (declare-function org-agenda-skip "org-agenda" ())
  3900. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3901. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3902. (declare-function org-indent-mode "org-indent" (&optional arg))
  3903. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3904. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3905. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3906. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3907. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3908. (declare-function parse-time-string "parse-time" (string))
  3909. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3910. (declare-function table--at-cell-p
  3911. "table"
  3912. (position &optional object at-column))
  3913. (defvar align-mode-rules-list)
  3914. (defvar calc-embedded-close-formula)
  3915. (defvar calc-embedded-open-formula)
  3916. (defvar calc-embedded-open-mode)
  3917. (defvar font-lock-unfontify-region-function)
  3918. (defvar iswitchb-temp-buflist)
  3919. (defvar org-agenda-tags-todo-honor-ignore-options)
  3920. (defvar remember-data-file)
  3921. (defvar texmathp-why)
  3922. ;;;###autoload
  3923. (defun turn-on-orgtbl ()
  3924. "Unconditionally turn on `orgtbl-mode'."
  3925. (require 'org-table)
  3926. (orgtbl-mode 1))
  3927. (defun org-at-table-p (&optional table-type)
  3928. "Non-nil if the cursor is inside an Org table.
  3929. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3930. If `org-enable-table-editor' is nil, return nil unconditionally."
  3931. (and
  3932. org-enable-table-editor
  3933. (save-excursion
  3934. (beginning-of-line)
  3935. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3936. (or (not (derived-mode-p 'org-mode))
  3937. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3938. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3939. (defun org-at-table.el-p ()
  3940. "Non-nil when point is at a table.el table."
  3941. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3942. (let ((element (org-element-at-point)))
  3943. (and (eq (org-element-type element) 'table)
  3944. (eq (org-element-property :type element) 'table.el)))))
  3945. (defun org-table-recognize-table.el ()
  3946. "If there is a table.el table nearby, recognize it and move into it."
  3947. (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
  3948. (beginning-of-line)
  3949. (unless (or (looking-at org-table-dataline-regexp)
  3950. (not (looking-at org-table1-hline-regexp)))
  3951. (forward-line)
  3952. (when (looking-at org-table-any-border-regexp)
  3953. (forward-line -2)))
  3954. (if (re-search-forward "|" (org-table-end t) t)
  3955. (progn
  3956. (require 'table)
  3957. (if (table--at-cell-p (point)) t
  3958. (message "recognizing table.el table...")
  3959. (table-recognize-table)
  3960. (message "recognizing table.el table...done")))
  3961. (error "This should not happen"))))
  3962. ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
  3963. (make-obsolete 'org-table-recognize-table.el
  3964. "please notify the org mailing list if you use this function."
  3965. "Org 9.0")
  3966. (defun org-at-table-hline-p ()
  3967. "Non-nil when point is inside a hline in a table.
  3968. Assume point is already in a table. If `org-enable-table-editor'
  3969. is nil, return nil unconditionally."
  3970. (and org-enable-table-editor
  3971. (save-excursion
  3972. (beginning-of-line)
  3973. (looking-at org-table-hline-regexp))))
  3974. (defun org-table-map-tables (function &optional quietly)
  3975. "Apply FUNCTION to the start of all tables in the buffer."
  3976. (save-excursion
  3977. (save-restriction
  3978. (widen)
  3979. (goto-char (point-min))
  3980. (while (re-search-forward org-table-any-line-regexp nil t)
  3981. (unless quietly
  3982. (message "Mapping tables: %d%%"
  3983. (floor (* 100.0 (point)) (buffer-size))))
  3984. (beginning-of-line 1)
  3985. (when (and (looking-at org-table-line-regexp)
  3986. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3987. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3988. (save-excursion (funcall function))
  3989. (or (looking-at org-table-line-regexp)
  3990. (forward-char 1)))
  3991. (re-search-forward org-table-any-border-regexp nil 1))))
  3992. (unless quietly (message "Mapping tables: done")))
  3993. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3994. (declare-function org-clock-update-mode-line "org-clock" ())
  3995. (declare-function org-resolve-clocks "org-clock"
  3996. (&optional also-non-dangling-p prompt last-valid))
  3997. (defun org-at-TBLFM-p (&optional pos)
  3998. "Non-nil when point (or POS) is in #+TBLFM line."
  3999. (save-excursion
  4000. (goto-char (or pos (point)))
  4001. (beginning-of-line)
  4002. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4003. (eq (org-element-type (org-element-at-point)) 'table))))
  4004. (defvar org-clock-start-time)
  4005. (defvar org-clock-marker (make-marker)
  4006. "Marker recording the last clock-in.")
  4007. (defvar org-clock-hd-marker (make-marker)
  4008. "Marker recording the last clock-in, but the headline position.")
  4009. (defvar org-clock-heading ""
  4010. "The heading of the current clock entry.")
  4011. (defun org-clock-is-active ()
  4012. "Return the buffer where the clock is currently running.
  4013. Return nil if no clock is running."
  4014. (marker-buffer org-clock-marker))
  4015. (defun org-check-running-clock ()
  4016. "Check if the current buffer contains the running clock.
  4017. If yes, offer to stop it and to save the buffer with the changes."
  4018. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4019. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4020. (buffer-name))))
  4021. (org-clock-out)
  4022. (when (y-or-n-p "Save changed buffer?")
  4023. (save-buffer))))
  4024. (defun org-clocktable-try-shift (dir n)
  4025. "Check if this line starts a clock table, if yes, shift the time block."
  4026. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4027. (org-clocktable-shift dir n)))
  4028. ;;;###autoload
  4029. (defun org-clock-persistence-insinuate ()
  4030. "Set up hooks for clock persistence."
  4031. (require 'org-clock)
  4032. (add-hook 'org-mode-hook 'org-clock-load)
  4033. (add-hook 'kill-emacs-hook 'org-clock-save))
  4034. (defgroup org-archive nil
  4035. "Options concerning archiving in Org-mode."
  4036. :tag "Org Archive"
  4037. :group 'org-structure)
  4038. (defcustom org-archive-location "%s_archive::"
  4039. "The location where subtrees should be archived.
  4040. The value of this variable is a string, consisting of two parts,
  4041. separated by a double-colon. The first part is a filename and
  4042. the second part is a headline.
  4043. When the filename is omitted, archiving happens in the same file.
  4044. %s in the filename will be replaced by the current file
  4045. name (without the directory part). Archiving to a different file
  4046. is useful to keep archived entries from contributing to the
  4047. Org-mode Agenda.
  4048. The archived entries will be filed as subtrees of the specified
  4049. headline. When the headline is omitted, the subtrees are simply
  4050. filed away at the end of the file, as top-level entries. Also in
  4051. the heading you can use %s to represent the file name, this can be
  4052. useful when using the same archive for a number of different files.
  4053. Here are a few examples:
  4054. \"%s_archive::\"
  4055. If the current file is Projects.org, archive in file
  4056. Projects.org_archive, as top-level trees. This is the default.
  4057. \"::* Archived Tasks\"
  4058. Archive in the current file, under the top-level headline
  4059. \"* Archived Tasks\".
  4060. \"~/org/archive.org::\"
  4061. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4062. \"~/org/archive.org::* From %s\"
  4063. Archive in file ~/org/archive.org (absolute path), under headlines
  4064. \"From FILENAME\" where file name is the current file name.
  4065. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4066. The \"datetree/\" string is special, signifying to archive
  4067. items to the datetree. Items are placed in either the CLOSED
  4068. date of the item, or the current date if there is no CLOSED date.
  4069. The heading will be a subentry to the current date. There doesn't
  4070. need to be a heading, but there always needs to be a slash after
  4071. datetree. For example, to store archived items directly in the
  4072. datetree, use \"~/org/datetree.org::datetree/\".
  4073. \"basement::** Finished Tasks\"
  4074. Archive in file ./basement (relative path), as level 3 trees
  4075. below the level 2 heading \"** Finished Tasks\".
  4076. You may set this option on a per-file basis by adding to the buffer a
  4077. line like
  4078. #+ARCHIVE: basement::** Finished Tasks
  4079. You may also define it locally for a subtree by setting an ARCHIVE property
  4080. in the entry. If such a property is found in an entry, or anywhere up
  4081. the hierarchy, it will be used."
  4082. :group 'org-archive
  4083. :type 'string)
  4084. (defcustom org-agenda-skip-archived-trees t
  4085. "Non-nil means the agenda will skip any items located in archived trees.
  4086. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4087. variable is no longer recommended, you should leave it at the value t.
  4088. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4089. :group 'org-archive
  4090. :group 'org-agenda-skip
  4091. :type 'boolean)
  4092. (defcustom org-columns-skip-archived-trees t
  4093. "Non-nil means ignore archived trees when creating column view."
  4094. :group 'org-archive
  4095. :group 'org-properties
  4096. :type 'boolean)
  4097. (defcustom org-cycle-open-archived-trees nil
  4098. "Non-nil means `org-cycle' will open archived trees.
  4099. An archived tree is a tree marked with the tag ARCHIVE.
  4100. When nil, archived trees will stay folded. You can still open them with
  4101. normal outline commands like `show-all', but not with the cycling commands."
  4102. :group 'org-archive
  4103. :group 'org-cycle
  4104. :type 'boolean)
  4105. (defcustom org-sparse-tree-open-archived-trees nil
  4106. "Non-nil means sparse tree construction shows matches in archived trees.
  4107. When nil, matches in these trees are highlighted, but the trees are kept in
  4108. collapsed state."
  4109. :group 'org-archive
  4110. :group 'org-sparse-trees
  4111. :type 'boolean)
  4112. (defcustom org-sparse-tree-default-date-type nil
  4113. "The default date type when building a sparse tree.
  4114. When this is nil, a date is a scheduled or a deadline timestamp.
  4115. Otherwise, these types are allowed:
  4116. all: all timestamps
  4117. active: only active timestamps (<...>)
  4118. inactive: only inactive timestamps ([...])
  4119. scheduled: only scheduled timestamps
  4120. deadline: only deadline timestamps"
  4121. :type '(choice (const :tag "Scheduled or deadline" nil)
  4122. (const :tag "All timestamps" all)
  4123. (const :tag "Only active timestamps" active)
  4124. (const :tag "Only inactive timestamps" inactive)
  4125. (const :tag "Only scheduled timestamps" scheduled)
  4126. (const :tag "Only deadline timestamps" deadline)
  4127. (const :tag "Only closed timestamps" closed))
  4128. :version "25.1"
  4129. :package-version '(Org . "8.3")
  4130. :group 'org-sparse-trees)
  4131. (defun org-cycle-hide-archived-subtrees (state)
  4132. "Re-hide all archived subtrees after a visibility state change."
  4133. (when (and (not org-cycle-open-archived-trees)
  4134. (not (memq state '(overview folded))))
  4135. (save-excursion
  4136. (let* ((globalp (memq state '(contents all)))
  4137. (beg (if globalp (point-min) (point)))
  4138. (end (if globalp (point-max) (org-end-of-subtree t))))
  4139. (org-hide-archived-subtrees beg end)
  4140. (goto-char beg)
  4141. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4142. (message "%s" (substitute-command-keys
  4143. "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
  4144. (defun org-force-cycle-archived ()
  4145. "Cycle subtree even if it is archived."
  4146. (interactive)
  4147. (setq this-command 'org-cycle)
  4148. (let ((org-cycle-open-archived-trees t))
  4149. (call-interactively 'org-cycle)))
  4150. (defun org-hide-archived-subtrees (beg end)
  4151. "Re-hide all archived subtrees after a visibility state change."
  4152. (org-with-wide-buffer
  4153. (let ((case-fold-search nil)
  4154. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4155. (goto-char beg)
  4156. ;; Include headline point is currently on.
  4157. (beginning-of-line)
  4158. (while (and (< (point) end) (re-search-forward re end t))
  4159. (when (member org-archive-tag (org-get-tags))
  4160. (org-flag-subtree t)
  4161. (org-end-of-subtree t))))))
  4162. (declare-function outline-end-of-heading "outline" ())
  4163. (declare-function outline-flag-region "outline" (from to flag))
  4164. (defun org-flag-subtree (flag)
  4165. (save-excursion
  4166. (org-back-to-heading t)
  4167. (outline-end-of-heading)
  4168. (outline-flag-region (point)
  4169. (progn (org-end-of-subtree t) (point))
  4170. flag)))
  4171. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4172. ;; Declare Column View Code
  4173. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4174. (declare-function org-columns-compute "org-colview" (property))
  4175. ;; Declare ID code
  4176. (declare-function org-id-store-link "org-id")
  4177. (declare-function org-id-locations-load "org-id")
  4178. (declare-function org-id-locations-save "org-id")
  4179. (defvar org-id-track-globally)
  4180. ;;; Variables for pre-computed regular expressions, all buffer local
  4181. (defvar-local org-todo-regexp nil
  4182. "Matches any of the TODO state keywords.")
  4183. (defvar-local org-not-done-regexp nil
  4184. "Matches any of the TODO state keywords except the last one.")
  4185. (defvar-local org-not-done-heading-regexp nil
  4186. "Matches a TODO headline that is not done.")
  4187. (defvar-local org-todo-line-regexp nil
  4188. "Matches a headline and puts TODO state into group 2 if present.")
  4189. (defvar-local org-complex-heading-regexp nil
  4190. "Matches a headline and puts everything into groups:
  4191. group 1: the stars
  4192. group 2: The todo keyword, maybe
  4193. group 3: Priority cookie
  4194. group 4: True headline
  4195. group 5: Tags")
  4196. (defvar-local org-complex-heading-regexp-format nil
  4197. "Printf format to make regexp to match an exact headline.
  4198. This regexp will match the headline of any node which has the
  4199. exact headline text that is put into the format, but may have any
  4200. TODO state, priority and tags.")
  4201. (defvar-local org-todo-line-tags-regexp nil
  4202. "Matches a headline and puts TODO state into group 2 if present.
  4203. Also put tags into group 4 if tags are present.")
  4204. (defconst org-plain-time-of-day-regexp
  4205. (concat
  4206. "\\(\\<[012]?[0-9]"
  4207. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4208. "\\(--?"
  4209. "\\(\\<[012]?[0-9]"
  4210. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4211. "\\)?")
  4212. "Regular expression to match a plain time or time range.
  4213. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4214. groups carry important information:
  4215. 0 the full match
  4216. 1 the first time, range or not
  4217. 8 the second time, if it is a range.")
  4218. (defconst org-plain-time-extension-regexp
  4219. (concat
  4220. "\\(\\<[012]?[0-9]"
  4221. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4222. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4223. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4224. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4225. groups carry important information:
  4226. 0 the full match
  4227. 7 hours of duration
  4228. 9 minutes of duration")
  4229. (defconst org-stamp-time-of-day-regexp
  4230. (concat
  4231. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4232. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4233. "\\(--?"
  4234. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4235. "Regular expression to match a timestamp time or time range.
  4236. After a match, the following groups carry important information:
  4237. 0 the full match
  4238. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4239. 2 the first time, range or not
  4240. 4 the second time, if it is a range.")
  4241. (defconst org-startup-options
  4242. '(("fold" org-startup-folded t)
  4243. ("overview" org-startup-folded t)
  4244. ("nofold" org-startup-folded nil)
  4245. ("showall" org-startup-folded nil)
  4246. ("showeverything" org-startup-folded showeverything)
  4247. ("content" org-startup-folded content)
  4248. ("indent" org-startup-indented t)
  4249. ("noindent" org-startup-indented nil)
  4250. ("hidestars" org-hide-leading-stars t)
  4251. ("showstars" org-hide-leading-stars nil)
  4252. ("odd" org-odd-levels-only t)
  4253. ("oddeven" org-odd-levels-only nil)
  4254. ("align" org-startup-align-all-tables t)
  4255. ("noalign" org-startup-align-all-tables nil)
  4256. ("inlineimages" org-startup-with-inline-images t)
  4257. ("noinlineimages" org-startup-with-inline-images nil)
  4258. ("latexpreview" org-startup-with-latex-preview t)
  4259. ("nolatexpreview" org-startup-with-latex-preview nil)
  4260. ("customtime" org-display-custom-times t)
  4261. ("logdone" org-log-done time)
  4262. ("lognotedone" org-log-done note)
  4263. ("nologdone" org-log-done nil)
  4264. ("lognoteclock-out" org-log-note-clock-out t)
  4265. ("nolognoteclock-out" org-log-note-clock-out nil)
  4266. ("logrepeat" org-log-repeat state)
  4267. ("lognoterepeat" org-log-repeat note)
  4268. ("logdrawer" org-log-into-drawer t)
  4269. ("nologdrawer" org-log-into-drawer nil)
  4270. ("logstatesreversed" org-log-states-order-reversed t)
  4271. ("nologstatesreversed" org-log-states-order-reversed nil)
  4272. ("nologrepeat" org-log-repeat nil)
  4273. ("logreschedule" org-log-reschedule time)
  4274. ("lognotereschedule" org-log-reschedule note)
  4275. ("nologreschedule" org-log-reschedule nil)
  4276. ("logredeadline" org-log-redeadline time)
  4277. ("lognoteredeadline" org-log-redeadline note)
  4278. ("nologredeadline" org-log-redeadline nil)
  4279. ("logrefile" org-log-refile time)
  4280. ("lognoterefile" org-log-refile note)
  4281. ("nologrefile" org-log-refile nil)
  4282. ("fninline" org-footnote-define-inline t)
  4283. ("nofninline" org-footnote-define-inline nil)
  4284. ("fnlocal" org-footnote-section nil)
  4285. ("fnauto" org-footnote-auto-label t)
  4286. ("fnprompt" org-footnote-auto-label nil)
  4287. ("fnconfirm" org-footnote-auto-label confirm)
  4288. ("fnplain" org-footnote-auto-label plain)
  4289. ("fnadjust" org-footnote-auto-adjust t)
  4290. ("nofnadjust" org-footnote-auto-adjust nil)
  4291. ("constcgs" constants-unit-system cgs)
  4292. ("constSI" constants-unit-system SI)
  4293. ("noptag" org-tag-persistent-alist nil)
  4294. ("hideblocks" org-hide-block-startup t)
  4295. ("nohideblocks" org-hide-block-startup nil)
  4296. ("beamer" org-startup-with-beamer-mode t)
  4297. ("entitiespretty" org-pretty-entities t)
  4298. ("entitiesplain" org-pretty-entities nil))
  4299. "Variable associated with STARTUP options for org-mode.
  4300. Each element is a list of three items: the startup options (as written
  4301. in the #+STARTUP line), the corresponding variable, and the value to set
  4302. this variable to if the option is found. An optional forth element PUSH
  4303. means to push this value onto the list in the variable.")
  4304. (defcustom org-group-tags t
  4305. "When non-nil (the default), use group tags.
  4306. This can be turned on/off through `org-toggle-tags-groups'."
  4307. :group 'org-tags
  4308. :group 'org-startup
  4309. :type 'boolean)
  4310. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4311. (defun org-toggle-tags-groups ()
  4312. "Toggle support for group tags.
  4313. Support for group tags is controlled by the option
  4314. `org-group-tags', which is non-nil by default."
  4315. (interactive)
  4316. (setq org-group-tags (not org-group-tags))
  4317. (cond ((and (derived-mode-p 'org-agenda-mode)
  4318. org-group-tags)
  4319. (org-agenda-redo))
  4320. ((derived-mode-p 'org-mode)
  4321. (let ((org-inhibit-startup t)) (org-mode))))
  4322. (message "Groups tags support has been turned %s"
  4323. (if org-group-tags "on" "off")))
  4324. (defun org-set-regexps-and-options (&optional tags-only)
  4325. "Precompute regular expressions used in the current buffer.
  4326. When optional argument TAGS-ONLY is non-nil, only compute tags
  4327. related expressions."
  4328. (when (derived-mode-p 'org-mode)
  4329. (let ((alist (org--setup-collect-keywords
  4330. (org-make-options-regexp
  4331. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4332. (and (not tags-only)
  4333. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4334. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4335. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4336. ;; Startup options. Get this early since it does change
  4337. ;; behavior for other options (e.g., tags).
  4338. (let ((startup (cdr (assq 'startup alist))))
  4339. (dolist (option startup)
  4340. (let ((entry (assoc-string option org-startup-options t)))
  4341. (when entry
  4342. (let ((var (nth 1 entry))
  4343. (val (nth 2 entry)))
  4344. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4345. (unless (listp (symbol-value var))
  4346. (set (make-local-variable var) nil))
  4347. (add-to-list var val)))))))
  4348. (setq-local org-file-tags
  4349. (mapcar #'org-add-prop-inherited
  4350. (cdr (assq 'filetags alist))))
  4351. (setq org-current-tag-alist
  4352. (append org-tag-persistent-alist
  4353. (let ((tags (cdr (assq 'tags alist))))
  4354. (if tags (org-tag-string-to-alist tags)
  4355. org-tag-alist))))
  4356. (setq org-tag-groups-alist
  4357. (org-tag-alist-to-groups org-current-tag-alist))
  4358. (unless tags-only
  4359. ;; File properties.
  4360. (setq-local org-file-properties (cdr (assq 'property alist)))
  4361. ;; Archive location.
  4362. (let ((archive (cdr (assq 'archive alist))))
  4363. (when archive (setq-local org-archive-location archive)))
  4364. ;; Category.
  4365. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4366. (when cat
  4367. (setq-local org-category (intern cat))
  4368. (setq-local org-file-properties
  4369. (org--update-property-plist
  4370. "CATEGORY" cat org-file-properties))))
  4371. ;; Columns.
  4372. (let ((column (cdr (assq 'columns alist))))
  4373. (when column (setq-local org-columns-default-format column)))
  4374. ;; Constants.
  4375. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4376. ;; Link abbreviations.
  4377. (let ((links (cdr (assq 'link alist))))
  4378. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4379. ;; Priorities.
  4380. (let ((priorities (cdr (assq 'priorities alist))))
  4381. (when priorities
  4382. (setq-local org-highest-priority (nth 0 priorities))
  4383. (setq-local org-lowest-priority (nth 1 priorities))
  4384. (setq-local org-default-priority (nth 2 priorities))))
  4385. ;; Scripts.
  4386. (let ((scripts (assq 'scripts alist)))
  4387. (when scripts
  4388. (setq-local org-use-sub-superscripts (cdr scripts))))
  4389. ;; TODO keywords.
  4390. (setq-local org-todo-kwd-alist nil)
  4391. (setq-local org-todo-key-alist nil)
  4392. (setq-local org-todo-key-trigger nil)
  4393. (setq-local org-todo-keywords-1 nil)
  4394. (setq-local org-done-keywords nil)
  4395. (setq-local org-todo-heads nil)
  4396. (setq-local org-todo-sets nil)
  4397. (setq-local org-todo-log-states nil)
  4398. (let ((todo-sequences
  4399. (or (nreverse (cdr (assq 'todo alist)))
  4400. (let ((d (default-value 'org-todo-keywords)))
  4401. (if (not (stringp (car d))) d
  4402. ;; XXX: Backward compatibility code.
  4403. (list (cons org-todo-interpretation d)))))))
  4404. (dolist (sequence todo-sequences)
  4405. (let* ((sequence (or (run-hook-with-args-until-success
  4406. 'org-todo-setup-filter-hook sequence)
  4407. sequence))
  4408. (sequence-type (car sequence))
  4409. (keywords (cdr sequence))
  4410. (sep (member "|" keywords))
  4411. names alist)
  4412. (dolist (k (remove "|" keywords))
  4413. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4414. k)
  4415. (error "Invalid TODO keyword %s" k))
  4416. (let ((name (match-string 1 k))
  4417. (key (match-string 2 k))
  4418. (log (org-extract-log-state-settings k)))
  4419. (push name names)
  4420. (push (cons name (and key (string-to-char key))) alist)
  4421. (when log (push log org-todo-log-states))))
  4422. (let* ((names (nreverse names))
  4423. (done (if sep (org-remove-keyword-keys (cdr sep))
  4424. (last names)))
  4425. (head (car names))
  4426. (tail (list sequence-type head (car done) (org-last done))))
  4427. (add-to-list 'org-todo-heads head 'append)
  4428. (push names org-todo-sets)
  4429. (setq org-done-keywords (append org-done-keywords done nil))
  4430. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4431. (setq org-todo-key-alist
  4432. (append org-todo-key-alist
  4433. (and alist
  4434. (append '((:startgroup))
  4435. (nreverse alist)
  4436. '((:endgroup))))))
  4437. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4438. (setq org-todo-sets (nreverse org-todo-sets)
  4439. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4440. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4441. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4442. ;; Compute the regular expressions and other local variables.
  4443. ;; Using `org-outline-regexp-bol' would complicate them much,
  4444. ;; because of the fixed white space at the end of that string.
  4445. (unless org-done-keywords
  4446. (setq org-done-keywords
  4447. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4448. (setq org-not-done-keywords
  4449. (org-delete-all org-done-keywords
  4450. (copy-sequence org-todo-keywords-1))
  4451. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4452. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4453. org-not-done-heading-regexp
  4454. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4455. org-todo-line-regexp
  4456. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4457. org-complex-heading-regexp
  4458. (concat "^\\(\\*+\\)"
  4459. "\\(?: +" org-todo-regexp "\\)?"
  4460. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4461. "\\(?: +\\(.*?\\)\\)??"
  4462. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4463. "[ \t]*$")
  4464. org-complex-heading-regexp-format
  4465. (concat "^\\(\\*+\\)"
  4466. "\\(?: +" org-todo-regexp "\\)?"
  4467. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4468. "\\(?: +"
  4469. ;; Stats cookies can be stuck to body.
  4470. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4471. "\\(%s\\)"
  4472. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4473. "\\)"
  4474. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4475. "[ \t]*$")
  4476. org-todo-line-tags-regexp
  4477. (concat "^\\(\\*+\\)"
  4478. "\\(?: +" org-todo-regexp "\\)?"
  4479. "\\(?: +\\(.*?\\)\\)??"
  4480. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4481. "[ \t]*$"))
  4482. (org-compute-latex-and-related-regexp)))))
  4483. (defun org--setup-collect-keywords (regexp &optional files alist)
  4484. "Return setup keywords values as an alist.
  4485. REGEXP matches a subset of setup keywords. FILES is a list of
  4486. file names already visited. It is used to avoid circular setup
  4487. files. ALIST, when non-nil, is the alist computed so far.
  4488. Return value contains the following keys: `archive', `category',
  4489. `columns', `constants', `filetags', `link', `priorities',
  4490. `property', `scripts', `startup', `tags' and `todo'."
  4491. (org-with-wide-buffer
  4492. (goto-char (point-min))
  4493. (let ((case-fold-search t))
  4494. (while (re-search-forward regexp nil t)
  4495. (let ((element (org-element-at-point)))
  4496. (when (eq (org-element-type element) 'keyword)
  4497. (let ((key (org-element-property :key element))
  4498. (value (org-element-property :value element)))
  4499. (cond
  4500. ((equal key "ARCHIVE")
  4501. (when (org-string-nw-p value)
  4502. (push (cons 'archive value) alist)))
  4503. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4504. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4505. ((equal key "CONSTANTS")
  4506. (let* ((constants (assq 'constants alist))
  4507. (store (cdr constants)))
  4508. (dolist (pair (org-split-string value))
  4509. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4510. pair)
  4511. (let* ((name (match-string 1 pair))
  4512. (value (match-string 2 pair))
  4513. (old (assoc name store)))
  4514. (if old (setcdr old value)
  4515. (push (cons name value) store)))))
  4516. (if constants (setcdr constants store)
  4517. (push (cons 'constants store) alist))))
  4518. ((equal key "FILETAGS")
  4519. (when (org-string-nw-p value)
  4520. (let ((old (assq 'filetags alist))
  4521. (new (apply #'nconc
  4522. (mapcar (lambda (x) (org-split-string x ":"))
  4523. (org-split-string value)))))
  4524. (if old (setcdr old (append new (cdr old)))
  4525. (push (cons 'filetags new) alist)))))
  4526. ((equal key "LINK")
  4527. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4528. (let ((links (assq 'link alist))
  4529. (pair (cons (match-string-no-properties 1 value)
  4530. (match-string-no-properties 2 value))))
  4531. (if links (push pair (cdr links))
  4532. (push (list 'link pair) alist)))))
  4533. ((equal key "OPTIONS")
  4534. (when (and (org-string-nw-p value)
  4535. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4536. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4537. ((equal key "PRIORITIES")
  4538. (push (cons 'priorities
  4539. (let ((prio (org-split-string value)))
  4540. (if (< (length prio) 3) '(?A ?C ?B)
  4541. (mapcar #'string-to-char prio))))
  4542. alist))
  4543. ((equal key "PROPERTY")
  4544. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4545. (let* ((property (assq 'property alist))
  4546. (value (org--update-property-plist
  4547. (match-string-no-properties 1 value)
  4548. (match-string-no-properties 2 value)
  4549. (cdr property))))
  4550. (if property (setcdr property value)
  4551. (push (cons 'property value) alist)))))
  4552. ((equal key "STARTUP")
  4553. (let ((startup (assq 'startup alist)))
  4554. (if startup
  4555. (setcdr startup
  4556. (append (cdr startup) (org-split-string value)))
  4557. (push (cons 'startup (org-split-string value)) alist))))
  4558. ((equal key "TAGS")
  4559. (let ((tag-cell (assq 'tags alist)))
  4560. (if tag-cell
  4561. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4562. (push (cons 'tags value) alist))))
  4563. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4564. (let ((todo (assq 'todo alist))
  4565. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4566. (org-split-string value))))
  4567. (if todo (push value (cdr todo))
  4568. (push (list 'todo value) alist))))
  4569. ((equal key "SETUPFILE")
  4570. (unless buffer-read-only ; Do not check in Gnus messages.
  4571. (let ((f (and (org-string-nw-p value)
  4572. (expand-file-name
  4573. (org-remove-double-quotes value)))))
  4574. (when (and f (file-readable-p f) (not (member f files)))
  4575. (with-temp-buffer
  4576. (setq default-directory (file-name-directory f))
  4577. (insert-file-contents f)
  4578. (setq alist
  4579. ;; Fake Org mode to benefit from cache
  4580. ;; without recurring needlessly.
  4581. (let ((major-mode 'org-mode))
  4582. (org--setup-collect-keywords
  4583. regexp (cons f files) alist)))))))))))))))
  4584. alist)
  4585. (defun org-tag-string-to-alist (s)
  4586. "Return tag alist associated to string S.
  4587. S is a value for TAGS keyword or produced with
  4588. `org-tag-alist-to-string'. Return value is an alist suitable for
  4589. `org-tag-alist' or `org-tag-persistent-alist'."
  4590. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4591. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4592. "\\|{.+?}\\)" ; regular expression
  4593. "\\(?:(\\(.\\))\\)?\\'"))
  4594. alist group-flag)
  4595. (dolist (tokens lines (cdr (nreverse alist)))
  4596. (push '(:newline) alist)
  4597. (while tokens
  4598. (let ((token (pop tokens)))
  4599. (pcase token
  4600. ("{"
  4601. (push '(:startgroup) alist)
  4602. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4603. ("}"
  4604. (push '(:endgroup) alist)
  4605. (setq group-flag nil))
  4606. ("["
  4607. (push '(:startgrouptag) alist)
  4608. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4609. ("]"
  4610. (push '(:endgrouptag) alist)
  4611. (setq group-flag nil))
  4612. (":"
  4613. (push '(:grouptags) alist))
  4614. ((guard (string-match tag-re token))
  4615. (let ((tag (match-string 1 token))
  4616. (key (and (match-beginning 2)
  4617. (string-to-char (match-string 2 token)))))
  4618. ;; Push all tags in groups, no matter if they already
  4619. ;; appear somewhere else in the list.
  4620. (when (or group-flag (not (assoc tag alist)))
  4621. (push (cons tag key) alist))))))))))
  4622. (defun org-tag-alist-to-string (alist &optional skip-key)
  4623. "Return tag string associated to ALIST.
  4624. ALIST is an alist, as defined in `org-tag-alist' or
  4625. `org-tag-persistent-alist', or produced with
  4626. `org-tag-string-to-alist'.
  4627. Return value is a string suitable as a value for \"TAGS\"
  4628. keyword.
  4629. When optional argument SKIP-KEY is non-nil, skip selection keys
  4630. next to tags."
  4631. (mapconcat (lambda (token)
  4632. (pcase token
  4633. (`(:startgroup) "{")
  4634. (`(:endgroup) "}")
  4635. (`(:startgrouptag) "[")
  4636. (`(:endgrouptag) "]")
  4637. (`(:grouptags) ":")
  4638. (`(:newline) "\\n")
  4639. ((and
  4640. (guard (not skip-key))
  4641. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4642. (format "%s(%c)" tag key))
  4643. (`(,(and tag (pred stringp)) . ,_) tag)
  4644. (_ (user-error "Invalid tag token: %S" token))))
  4645. alist
  4646. " "))
  4647. (defun org-tag-alist-to-groups (alist)
  4648. "Return group alist from tag ALIST.
  4649. ALIST is an alist, as defined in `org-tag-alist' or
  4650. `org-tag-persistent-alist', or produced with
  4651. `org-tag-string-to-alist'. Return value is an alist following
  4652. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4653. a string, summarizing TAGS, as a list of strings."
  4654. (let (groups group-status current-group)
  4655. (dolist (token alist (nreverse groups))
  4656. (pcase token
  4657. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4658. (`(,(or :endgroup :endgrouptag))
  4659. (when (eq group-status 'append)
  4660. (push (nreverse current-group) groups))
  4661. (setq group-status nil))
  4662. (`(:grouptags) (setq group-status 'append))
  4663. ((and `(,tag . ,_) (guard group-status))
  4664. (if (eq group-status 'append) (push tag current-group)
  4665. (setq current-group (list tag))))
  4666. (_ nil)))))
  4667. (defun org-file-contents (file &optional noerror)
  4668. "Return the contents of FILE, as a string."
  4669. (if (and file (file-readable-p file))
  4670. (with-temp-buffer
  4671. (insert-file-contents file)
  4672. (buffer-string))
  4673. (funcall (if noerror 'message 'error)
  4674. "Cannot read file \"%s\"%s"
  4675. file
  4676. (let ((from (buffer-file-name (buffer-base-buffer))))
  4677. (if from (concat " (referenced in file \"" from "\")") "")))))
  4678. (defun org-extract-log-state-settings (x)
  4679. "Extract the log state setting from a TODO keyword string.
  4680. This will extract info from a string like \"WAIT(w@/!)\"."
  4681. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4682. (let ((kw (match-string 1 x))
  4683. (log1 (and (match-end 3) (match-string 3 x)))
  4684. (log2 (and (match-end 4) (match-string 4 x))))
  4685. (and (or log1 log2)
  4686. (list kw
  4687. (and log1 (if (equal log1 "!") 'time 'note))
  4688. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4689. (defun org-remove-keyword-keys (list)
  4690. "Remove a pair of parenthesis at the end of each string in LIST."
  4691. (mapcar (lambda (x)
  4692. (if (string-match "(.*)$" x)
  4693. (substring x 0 (match-beginning 0))
  4694. x))
  4695. list))
  4696. (defun org-assign-fast-keys (alist)
  4697. "Assign fast keys to a keyword-key alist.
  4698. Respect keys that are already there."
  4699. (let (new e (alt ?0))
  4700. (while (setq e (pop alist))
  4701. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4702. (cdr e)) ;; Key already assigned.
  4703. (push e new)
  4704. (let ((clist (string-to-list (downcase (car e))))
  4705. (used (append new alist)))
  4706. (when (= (car clist) ?@)
  4707. (pop clist))
  4708. (while (and clist (rassoc (car clist) used))
  4709. (pop clist))
  4710. (unless clist
  4711. (while (rassoc alt used)
  4712. (cl-incf alt)))
  4713. (push (cons (car e) (or (car clist) alt)) new))))
  4714. (nreverse new)))
  4715. ;;; Some variables used in various places
  4716. (defvar org-window-configuration nil
  4717. "Used in various places to store a window configuration.")
  4718. (defvar org-selected-window nil
  4719. "Used in various places to store a window configuration.")
  4720. (defvar org-finish-function nil
  4721. "Function to be called when `C-c C-c' is used.
  4722. This is for getting out of special buffers like capture.")
  4723. (defvar org-last-state)
  4724. ;; Defined somewhere in this file, but used before definition.
  4725. (defvar org-entities) ;; defined in org-entities.el
  4726. (defvar org-struct-menu)
  4727. (defvar org-org-menu)
  4728. (defvar org-tbl-menu)
  4729. ;;;; Define the Org-mode
  4730. ;; We use a before-change function to check if a table might need
  4731. ;; an update.
  4732. (defvar org-table-may-need-update t
  4733. "Indicates that a table might need an update.
  4734. This variable is set by `org-before-change-function'.
  4735. `org-table-align' sets it back to nil.")
  4736. (defun org-before-change-function (_beg _end)
  4737. "Every change indicates that a table might need an update."
  4738. (setq org-table-may-need-update t))
  4739. (defvar org-mode-map)
  4740. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4741. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4742. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4743. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4744. (defvar org-table-buffer-is-an nil)
  4745. (defvar bidi-paragraph-direction)
  4746. (defvar buffer-face-mode-face)
  4747. (require 'outline)
  4748. ;; Other stuff we need.
  4749. (require 'time-date)
  4750. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4751. (require 'easymenu)
  4752. (autoload 'easy-menu-add "easymenu")
  4753. (require 'overlay)
  4754. ;; (require 'org-macs) moved higher up in the file before it is first used
  4755. (require 'org-entities)
  4756. ;; (require 'org-compat) moved higher up in the file before it is first used
  4757. (require 'org-faces)
  4758. (require 'org-list)
  4759. (require 'org-pcomplete)
  4760. (require 'org-src)
  4761. (require 'org-footnote)
  4762. (require 'org-macro)
  4763. ;; babel
  4764. (require 'ob)
  4765. ;;;###autoload
  4766. (define-derived-mode org-mode outline-mode "Org"
  4767. "Outline-based notes management and organizer, alias
  4768. \"Carsten's outline-mode for keeping track of everything.\"
  4769. Org-mode develops organizational tasks around a NOTES file which
  4770. contains information about projects as plain text. Org-mode is
  4771. implemented on top of outline-mode, which is ideal to keep the content
  4772. of large files well structured. It supports ToDo items, deadlines and
  4773. time stamps, which magically appear in the diary listing of the Emacs
  4774. calendar. Tables are easily created with a built-in table editor.
  4775. Plain text URL-like links connect to websites, emails (VM), Usenet
  4776. messages (Gnus), BBDB entries, and any files related to the project.
  4777. For printing and sharing of notes, an Org-mode file (or a part of it)
  4778. can be exported as a structured ASCII or HTML file.
  4779. The following commands are available:
  4780. \\{org-mode-map}"
  4781. ;; Get rid of Outline menus, they are not needed
  4782. ;; Need to do this here because define-derived-mode sets up
  4783. ;; the keymap so late. Still, it is a waste to call this each time
  4784. ;; we switch another buffer into Org mode.
  4785. (define-key org-mode-map [menu-bar headings] 'undefined)
  4786. (define-key org-mode-map [menu-bar hide] 'undefined)
  4787. (define-key org-mode-map [menu-bar show] 'undefined)
  4788. (org-load-modules-maybe)
  4789. (org-install-agenda-files-menu)
  4790. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4791. (add-to-invisibility-spec '(org-cwidth))
  4792. (add-to-invisibility-spec '(org-hide-block . t))
  4793. (setq-local outline-regexp org-outline-regexp)
  4794. (setq-local outline-level 'org-outline-level)
  4795. (setq bidi-paragraph-direction 'left-to-right)
  4796. (when (and org-ellipsis
  4797. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4798. (fboundp 'make-glyph-code))
  4799. (unless org-display-table
  4800. (setq org-display-table (make-display-table)))
  4801. (set-display-table-slot
  4802. org-display-table 4
  4803. (vconcat (mapcar
  4804. (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
  4805. org-ellipsis)))
  4806. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4807. (setq buffer-display-table org-display-table))
  4808. (org-set-regexps-and-options)
  4809. (org-set-font-lock-defaults)
  4810. (when (and org-tag-faces (not org-tags-special-faces-re))
  4811. ;; tag faces set outside customize.... force initialization.
  4812. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4813. ;; Calc embedded
  4814. (setq-local calc-embedded-open-mode "# ")
  4815. ;; Modify a few syntax entries
  4816. (modify-syntax-entry ?@ "w")
  4817. (modify-syntax-entry ?\" "\"")
  4818. (modify-syntax-entry ?\\ "_")
  4819. (modify-syntax-entry ?~ "_")
  4820. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4821. ;; Activate before-change-function
  4822. (setq-local org-table-may-need-update t)
  4823. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4824. ;; Check for running clock before killing a buffer
  4825. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4826. ;; Initialize macros templates.
  4827. (org-macro-initialize-templates)
  4828. ;; Initialize radio targets.
  4829. (org-update-radio-target-regexp)
  4830. ;; Indentation.
  4831. (setq-local indent-line-function 'org-indent-line)
  4832. (setq-local indent-region-function 'org-indent-region)
  4833. ;; Filling and auto-filling.
  4834. (org-setup-filling)
  4835. ;; Comments.
  4836. (org-setup-comments-handling)
  4837. ;; Initialize cache.
  4838. (org-element-cache-reset)
  4839. ;; Beginning/end of defun
  4840. (setq-local beginning-of-defun-function 'org-backward-element)
  4841. (setq-local end-of-defun-function
  4842. (lambda ()
  4843. (if (not (org-at-heading-p))
  4844. (org-forward-element)
  4845. (org-forward-element)
  4846. (forward-char -1))))
  4847. ;; Next error for sparse trees
  4848. (setq-local next-error-function 'org-occur-next-match)
  4849. ;; Make sure dependence stuff works reliably, even for users who set it
  4850. ;; too late :-(
  4851. (if org-enforce-todo-dependencies
  4852. (add-hook 'org-blocker-hook
  4853. 'org-block-todo-from-children-or-siblings-or-parent)
  4854. (remove-hook 'org-blocker-hook
  4855. 'org-block-todo-from-children-or-siblings-or-parent))
  4856. (if org-enforce-todo-checkbox-dependencies
  4857. (add-hook 'org-blocker-hook
  4858. 'org-block-todo-from-checkboxes)
  4859. (remove-hook 'org-blocker-hook
  4860. 'org-block-todo-from-checkboxes))
  4861. ;; Align options lines
  4862. (setq-local
  4863. align-mode-rules-list
  4864. '((org-in-buffer-settings
  4865. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4866. (modes . '(org-mode)))))
  4867. ;; Imenu
  4868. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4869. ;; Make isearch reveal context
  4870. (setq-local outline-isearch-open-invisible-function
  4871. (lambda (&rest _) (org-show-context 'isearch)))
  4872. ;; Setup the pcomplete hooks
  4873. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4874. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4875. (setq-local pcomplete-default-completion-function 'ignore)
  4876. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4877. (setq-local pcomplete-termination-string "")
  4878. (setq-local buffer-face-mode-face 'org-default)
  4879. ;; If empty file that did not turn on Org mode automatically, make
  4880. ;; it to.
  4881. (when (and org-insert-mode-line-in-empty-file
  4882. (called-interactively-p 'any)
  4883. (= (point-min) (point-max)))
  4884. (insert "# -*- mode: org -*-\n\n"))
  4885. (unless org-inhibit-startup
  4886. (org-unmodified
  4887. (when org-startup-with-beamer-mode (org-beamer-mode))
  4888. (when org-startup-align-all-tables
  4889. (org-table-map-tables #'org-table-align t))
  4890. (when org-startup-with-inline-images (org-display-inline-images))
  4891. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4892. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4893. (when org-startup-truncated (setq truncate-lines t))
  4894. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4895. (org-refresh-effort-properties)))
  4896. ;; Try to set `org-hide' face correctly.
  4897. (let ((foreground (org-find-invisible-foreground)))
  4898. (when foreground
  4899. (set-face-foreground 'org-hide foreground))))
  4900. ;; Update `customize-package-emacs-version-alist'
  4901. (add-to-list 'customize-package-emacs-version-alist
  4902. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4903. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4904. ("8.2.6" . "24.4") ("8.3" . "25.1")))
  4905. (defvar org-mode-transpose-word-syntax-table
  4906. (let ((st (make-syntax-table text-mode-syntax-table)))
  4907. (dolist (c org-emphasis-alist st)
  4908. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4909. (when (fboundp 'abbrev-table-put)
  4910. (abbrev-table-put org-mode-abbrev-table
  4911. :parents (list text-mode-abbrev-table)))
  4912. (defun org-find-invisible-foreground ()
  4913. (let ((candidates (remove
  4914. "unspecified-bg"
  4915. (nconc
  4916. (list (face-background 'default)
  4917. (face-background 'org-default))
  4918. (mapcar
  4919. (lambda (alist)
  4920. (when (boundp alist)
  4921. (cdr (assoc 'background-color (symbol-value alist)))))
  4922. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4923. (list (face-foreground 'org-hide))))))
  4924. (car (remove nil candidates))))
  4925. (defun org-current-time (&optional rounding-minutes past)
  4926. "Current time, possibly rounded to ROUNDING-MINUTES.
  4927. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4928. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4929. the rounding returns a past time."
  4930. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4931. (car org-time-stamp-rounding-minutes)))
  4932. (time (decode-time)) res)
  4933. (if (< r 1)
  4934. (current-time)
  4935. (setq res
  4936. (apply 'encode-time
  4937. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4938. (nthcdr 2 time))))
  4939. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4940. (seconds-to-time (- (float-time res) (* r 60)))
  4941. res))))
  4942. (defun org-today ()
  4943. "Return today date, considering `org-extend-today-until'."
  4944. (time-to-days
  4945. (time-subtract (current-time)
  4946. (list 0 (* 3600 org-extend-today-until) 0))))
  4947. ;;;; Font-Lock stuff, including the activators
  4948. (defvar org-mouse-map (make-sparse-keymap))
  4949. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4950. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4951. (when org-mouse-1-follows-link
  4952. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4953. (when org-tab-follows-link
  4954. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4955. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4956. (require 'font-lock)
  4957. (defconst org-non-link-chars "]\t\n\r<>")
  4958. (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
  4959. "file+sys" "news" "shell" "elisp" "doi" "message"
  4960. "help"))
  4961. (defvar org-link-types-re nil
  4962. "Matches a link that has a url-like prefix like \"http:\"")
  4963. (defvar org-link-re-with-space nil
  4964. "Matches a link with spaces, optional angular brackets around it.")
  4965. (defvar org-link-re-with-space2 nil
  4966. "Matches a link with spaces, optional angular brackets around it.")
  4967. (defvar org-link-re-with-space3 nil
  4968. "Matches a link with spaces, only for internal part in bracket links.")
  4969. (defvar org-angle-link-re nil
  4970. "Matches link with angular brackets, spaces are allowed.")
  4971. (defvar org-plain-link-re nil
  4972. "Matches plain link, without spaces.")
  4973. (defvar org-bracket-link-regexp nil
  4974. "Matches a link in double brackets.")
  4975. (defvar org-bracket-link-analytic-regexp nil
  4976. "Regular expression used to analyze links.
  4977. Here is what the match groups contain after a match:
  4978. 1: http:
  4979. 2: http
  4980. 3: path
  4981. 4: [desc]
  4982. 5: desc")
  4983. (defvar org-bracket-link-analytic-regexp++ nil
  4984. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4985. (defvar org-any-link-re nil
  4986. "Regular expression matching any link.")
  4987. (defconst org-match-sexp-depth 3
  4988. "Number of stacked braces for sub/superscript matching.")
  4989. (defun org-create-multibrace-regexp (left right n)
  4990. "Create a regular expression which will match a balanced sexp.
  4991. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4992. as single character strings.
  4993. The regexp returned will match the entire expression including the
  4994. delimiters. It will also define a single group which contains the
  4995. match except for the outermost delimiters. The maximum depth of
  4996. stacked delimiters is N. Escaping delimiters is not possible."
  4997. (let* ((nothing (concat "[^" left right "]*?"))
  4998. (or "\\|")
  4999. (re nothing)
  5000. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5001. (while (> n 1)
  5002. (setq n (1- n)
  5003. re (concat re or next)
  5004. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5005. (concat left "\\(" re "\\)" right)))
  5006. (defconst org-match-substring-regexp
  5007. (concat
  5008. "\\(\\S-\\)\\([_^]\\)\\("
  5009. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5010. "\\|"
  5011. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5012. "\\|"
  5013. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5014. "The regular expression matching a sub- or superscript.")
  5015. (defconst org-match-substring-with-braces-regexp
  5016. (concat
  5017. "\\(\\S-\\)\\([_^]\\)"
  5018. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5019. "The regular expression matching a sub- or superscript, forcing braces.")
  5020. (defun org-make-link-regexps ()
  5021. "Update the link regular expressions.
  5022. This should be called after the variable `org-link-types' has changed."
  5023. (let ((types-re (regexp-opt org-link-types t)))
  5024. (setq org-link-types-re
  5025. (concat "\\`" types-re ":")
  5026. org-link-re-with-space
  5027. (concat "<?" types-re ":"
  5028. "\\([^" org-non-link-chars " ]"
  5029. "[^" org-non-link-chars "]*"
  5030. "[^" org-non-link-chars " ]\\)>?")
  5031. org-link-re-with-space2
  5032. (concat "<?" types-re ":"
  5033. "\\([^" org-non-link-chars " ]"
  5034. "[^\t\n\r]*"
  5035. "[^" org-non-link-chars " ]\\)>?")
  5036. org-link-re-with-space3
  5037. (concat "<?" types-re ":"
  5038. "\\([^" org-non-link-chars " ]"
  5039. "[^\t\n\r]*\\)")
  5040. org-angle-link-re
  5041. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5042. types-re)
  5043. org-plain-link-re
  5044. (concat
  5045. "\\<" types-re ":"
  5046. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5047. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5048. org-bracket-link-regexp
  5049. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5050. org-bracket-link-analytic-regexp
  5051. (concat
  5052. "\\[\\["
  5053. "\\(" types-re ":\\)?"
  5054. "\\([^]]+\\)"
  5055. "\\]"
  5056. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5057. "\\]")
  5058. org-bracket-link-analytic-regexp++
  5059. (concat
  5060. "\\[\\["
  5061. "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
  5062. "\\([^]]+\\)"
  5063. "\\]"
  5064. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5065. "\\]")
  5066. org-any-link-re
  5067. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5068. org-angle-link-re "\\)\\|\\("
  5069. org-plain-link-re "\\)"))))
  5070. (org-make-link-regexps)
  5071. (defvar org-emph-face nil)
  5072. (defun org-do-emphasis-faces (limit)
  5073. "Run through the buffer and emphasize strings."
  5074. (let (rtn a)
  5075. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5076. (let* ((border (char-after (match-beginning 3)))
  5077. (bre (regexp-quote (char-to-string border))))
  5078. (when (and (not (= border (char-after (match-beginning 4))))
  5079. (not (string-match-p (concat bre ".*" bre)
  5080. (replace-regexp-in-string
  5081. "\n" " "
  5082. (substring (match-string 2) 1 -1)))))
  5083. (setq rtn t)
  5084. (setq a (assoc (match-string 3) org-emphasis-alist))
  5085. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5086. 'face
  5087. (nth 1 a))
  5088. (and (nth 2 a)
  5089. (org-remove-flyspell-overlays-in
  5090. (match-beginning 0) (match-end 0)))
  5091. (add-text-properties (match-beginning 2) (match-end 2)
  5092. '(font-lock-multiline t org-emphasis t))
  5093. (when org-hide-emphasis-markers
  5094. (add-text-properties (match-end 4) (match-beginning 5)
  5095. '(invisible org-link))
  5096. (add-text-properties (match-beginning 3) (match-end 3)
  5097. '(invisible org-link)))))
  5098. (goto-char (1+ (match-beginning 0))))
  5099. rtn))
  5100. (defun org-emphasize (&optional char)
  5101. "Insert or change an emphasis, i.e. a font like bold or italic.
  5102. If there is an active region, change that region to a new emphasis.
  5103. If there is no region, just insert the marker characters and position
  5104. the cursor between them.
  5105. CHAR should be the marker character. If it is a space, it means to
  5106. remove the emphasis of the selected region.
  5107. If CHAR is not given (for example in an interactive call) it will be
  5108. prompted for."
  5109. (interactive)
  5110. (let ((erc org-emphasis-regexp-components)
  5111. (string "") beg end move s)
  5112. (if (org-region-active-p)
  5113. (setq beg (region-beginning)
  5114. end (region-end)
  5115. string (buffer-substring beg end))
  5116. (setq move t))
  5117. (unless char
  5118. (message "Emphasis marker or tag: [%s]"
  5119. (mapconcat #'car org-emphasis-alist ""))
  5120. (setq char (read-char-exclusive)))
  5121. (if (equal char ?\s)
  5122. (setq s ""
  5123. move nil)
  5124. (unless (assoc (char-to-string char) org-emphasis-alist)
  5125. (user-error "No such emphasis marker: \"%c\"" char))
  5126. (setq s (char-to-string char)))
  5127. (while (and (> (length string) 1)
  5128. (equal (substring string 0 1) (substring string -1))
  5129. (assoc (substring string 0 1) org-emphasis-alist))
  5130. (setq string (substring string 1 -1)))
  5131. (setq string (concat s string s))
  5132. (when beg (delete-region beg end))
  5133. (unless (or (bolp)
  5134. (string-match (concat "[" (nth 0 erc) "\n]")
  5135. (char-to-string (char-before (point)))))
  5136. (insert " "))
  5137. (unless (or (eobp)
  5138. (string-match (concat "[" (nth 1 erc) "\n]")
  5139. (char-to-string (char-after (point)))))
  5140. (insert " ") (backward-char 1))
  5141. (insert string)
  5142. (and move (backward-char 1))))
  5143. (defconst org-nonsticky-props
  5144. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5145. (defsubst org-rear-nonsticky-at (pos)
  5146. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5147. (defun org-activate-plain-links (limit)
  5148. "Add link properties for plain links."
  5149. (when (and (re-search-forward org-plain-link-re limit t)
  5150. (not (org-in-src-block-p)))
  5151. (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5152. 'face))
  5153. (link (match-string-no-properties 0)))
  5154. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5155. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5156. (add-text-properties (match-beginning 0) (match-end 0)
  5157. (list 'mouse-face 'highlight
  5158. 'face 'org-link
  5159. 'htmlize-link `(:uri ,link)
  5160. 'keymap org-mouse-map))
  5161. (org-rear-nonsticky-at (match-end 0))
  5162. t))))
  5163. (defun org-activate-code (limit)
  5164. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5165. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5166. (remove-text-properties (match-beginning 0) (match-end 0)
  5167. '(display t invisible t intangible t))
  5168. t))
  5169. (defcustom org-src-fontify-natively t
  5170. "When non-nil, fontify code in code blocks.
  5171. See also the `org-block' face."
  5172. :type 'boolean
  5173. :version "24.4"
  5174. :package-version '(Org . "8.3")
  5175. :group 'org-appearance
  5176. :group 'org-babel)
  5177. (defcustom org-allow-promoting-top-level-subtree nil
  5178. "When non-nil, allow promoting a top level subtree.
  5179. The leading star of the top level headline will be replaced
  5180. by a #."
  5181. :type 'boolean
  5182. :version "24.1"
  5183. :group 'org-appearance)
  5184. (defun org-fontify-meta-lines-and-blocks (limit)
  5185. (condition-case nil
  5186. (org-fontify-meta-lines-and-blocks-1 limit)
  5187. (error (message "org-mode fontification error in %S at %d"
  5188. (current-buffer)
  5189. (line-number-at-pos)))))
  5190. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5191. "Fontify #+ lines and blocks."
  5192. (let ((case-fold-search t))
  5193. (when (re-search-forward
  5194. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5195. limit t)
  5196. (let ((beg (match-beginning 0))
  5197. (block-start (match-end 0))
  5198. (block-end nil)
  5199. (lang (match-string 7))
  5200. (beg1 (line-beginning-position 2))
  5201. (dc1 (downcase (match-string 2)))
  5202. (dc3 (downcase (match-string 3)))
  5203. end end1 quoting block-type)
  5204. (cond
  5205. ((and (match-end 4) (equal dc3 "+begin"))
  5206. ;; Truly a block
  5207. (setq block-type (downcase (match-string 5))
  5208. quoting (member block-type org-protecting-blocks))
  5209. (when (re-search-forward
  5210. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5211. nil t) ;; on purpose, we look further than LIMIT
  5212. (setq end (min (point-max) (match-end 0))
  5213. end1 (min (point-max) (1- (match-beginning 0))))
  5214. (setq block-end (match-beginning 0))
  5215. (when quoting
  5216. (org-remove-flyspell-overlays-in beg1 end1)
  5217. (remove-text-properties beg end
  5218. '(display t invisible t intangible t)))
  5219. (add-text-properties
  5220. beg end '(font-lock-fontified t font-lock-multiline t))
  5221. (add-text-properties beg beg1 '(face org-meta-line))
  5222. (org-remove-flyspell-overlays-in beg beg1)
  5223. (add-text-properties ; For end_src
  5224. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5225. (org-remove-flyspell-overlays-in end1 end)
  5226. (cond
  5227. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5228. (org-src-font-lock-fontify-block lang block-start block-end)
  5229. (add-text-properties beg1 block-end '(src-block t)))
  5230. (quoting
  5231. (add-text-properties beg1 (min (point-max) (1+ end1))
  5232. (list 'face
  5233. (list :inherit
  5234. (let ((face-name
  5235. (intern (format "org-block-%s" lang))))
  5236. (append (and (facep face-name) (list face-name))
  5237. '(org-block))))))) ; end of source block
  5238. ((not org-fontify-quote-and-verse-blocks))
  5239. ((string= block-type "quote")
  5240. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5241. ((string= block-type "verse")
  5242. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5243. (add-text-properties beg beg1 '(face org-block-begin-line))
  5244. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5245. '(face org-block-end-line))
  5246. t))
  5247. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5248. (org-remove-flyspell-overlays-in
  5249. (match-beginning 0)
  5250. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5251. (add-text-properties
  5252. beg (match-end 3)
  5253. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5254. '(font-lock-fontified t invisible t)
  5255. '(font-lock-fontified t face org-document-info-keyword)))
  5256. (add-text-properties
  5257. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5258. (if (string-equal dc1 "+title:")
  5259. '(font-lock-fontified t face org-document-title)
  5260. '(font-lock-fontified t face org-document-info))))
  5261. ((equal dc1 "+caption:")
  5262. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5263. (remove-text-properties (match-beginning 0) (match-end 0)
  5264. '(display t invisible t intangible t))
  5265. (add-text-properties (match-beginning 1) (match-end 3)
  5266. '(font-lock-fontified t face org-meta-line))
  5267. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5268. '(font-lock-fontified t face org-block))
  5269. t)
  5270. ((member dc3 '(" " ""))
  5271. (org-remove-flyspell-overlays-in beg (match-end 0))
  5272. (add-text-properties
  5273. beg (match-end 0)
  5274. '(font-lock-fontified t face font-lock-comment-face)))
  5275. (t ;; just any other in-buffer setting, but not indented
  5276. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5277. (remove-text-properties (match-beginning 0) (match-end 0)
  5278. '(display t invisible t intangible t))
  5279. (add-text-properties beg (match-end 0)
  5280. '(font-lock-fontified t face org-meta-line))
  5281. t))))))
  5282. (defun org-fontify-drawers (limit)
  5283. "Fontify drawers."
  5284. (when (re-search-forward org-drawer-regexp limit t)
  5285. (add-text-properties
  5286. (match-beginning 0) (match-end 0)
  5287. '(font-lock-fontified t face org-special-keyword))
  5288. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5289. t))
  5290. (defun org-fontify-macros (limit)
  5291. "Fontify macros."
  5292. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5293. (add-text-properties
  5294. (match-beginning 0) (match-end 0)
  5295. '(font-lock-fontified t face org-macro))
  5296. (when org-hide-macro-markers
  5297. (add-text-properties (match-end 2) (match-beginning 2)
  5298. '(invisible t))
  5299. (add-text-properties (match-beginning 1) (match-end 1)
  5300. '(invisible t)))
  5301. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5302. t))
  5303. (defun org-activate-angle-links (limit)
  5304. "Add text properties for angle links."
  5305. (when (and (re-search-forward org-angle-link-re limit t)
  5306. (not (org-in-src-block-p)))
  5307. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5308. (add-text-properties (match-beginning 0) (match-end 0)
  5309. (list 'mouse-face 'highlight
  5310. 'keymap org-mouse-map
  5311. 'font-lock-multiline t))
  5312. (org-rear-nonsticky-at (match-end 0))
  5313. t))
  5314. (defun org-activate-footnote-links (limit)
  5315. "Add text properties for footnotes."
  5316. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5317. (when fn
  5318. (let* ((beg (nth 1 fn))
  5319. (end (nth 2 fn))
  5320. (label (car fn))
  5321. (referencep (/= (line-beginning-position) beg)))
  5322. (when (and referencep (nth 3 fn))
  5323. (save-excursion
  5324. (goto-char beg)
  5325. (search-forward (or label "fn:"))
  5326. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5327. (add-text-properties beg end
  5328. (list 'mouse-face 'highlight
  5329. 'keymap org-mouse-map
  5330. 'help-echo
  5331. (if referencep "Footnote reference"
  5332. "Footnote definition")
  5333. 'font-lock-fontified t
  5334. 'font-lock-multiline t
  5335. 'face 'org-footnote))))))
  5336. (defun org-activate-bracket-links (limit)
  5337. "Add text properties for bracketed links."
  5338. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5339. (not (org-in-src-block-p)))
  5340. (let* ((hl (match-string-no-properties 1))
  5341. (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
  5342. (ip (list 'invisible 'org-link
  5343. 'keymap org-mouse-map 'mouse-face 'highlight
  5344. 'font-lock-multiline t 'help-echo help
  5345. 'htmlize-link `(:uri ,hl)))
  5346. (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
  5347. 'font-lock-multiline t 'help-echo help
  5348. 'htmlize-link `(:uri ,hl))))
  5349. ;; We need to remove the invisible property here. Table narrowing
  5350. ;; may have made some of this invisible.
  5351. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5352. (remove-text-properties (match-beginning 0) (match-end 0)
  5353. '(invisible nil))
  5354. (if (match-end 3)
  5355. (progn
  5356. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5357. (org-rear-nonsticky-at (match-beginning 3))
  5358. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5359. (org-rear-nonsticky-at (match-end 3))
  5360. (add-text-properties (match-end 3) (match-end 0) ip)
  5361. (org-rear-nonsticky-at (match-end 0)))
  5362. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5363. (org-rear-nonsticky-at (match-beginning 1))
  5364. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5365. (org-rear-nonsticky-at (match-end 1))
  5366. (add-text-properties (match-end 1) (match-end 0) ip)
  5367. (org-rear-nonsticky-at (match-end 0)))
  5368. t)))
  5369. (defun org-activate-dates (limit)
  5370. "Add text properties for dates."
  5371. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5372. (not (equal (char-before (match-beginning 0)) 91)))
  5373. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5374. (add-text-properties (match-beginning 0) (match-end 0)
  5375. (list 'mouse-face 'highlight
  5376. 'keymap org-mouse-map))
  5377. (org-rear-nonsticky-at (match-end 0))
  5378. (when org-display-custom-times
  5379. (if (match-end 3)
  5380. (org-display-custom-time (match-beginning 3) (match-end 3))
  5381. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5382. t))
  5383. (defvar-local org-target-link-regexp nil
  5384. "Regular expression matching radio targets in plain text.")
  5385. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5386. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5387. border border border))
  5388. "Regular expression matching a link target.")
  5389. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5390. "Regular expression matching a radio target.")
  5391. (defconst org-any-target-regexp
  5392. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5393. "Regular expression matching any target.")
  5394. (defun org-activate-target-links (limit)
  5395. "Add text properties for target matches."
  5396. (when org-target-link-regexp
  5397. (let ((case-fold-search t))
  5398. (when (re-search-forward org-target-link-regexp limit t)
  5399. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5400. (add-text-properties (match-beginning 1) (match-end 1)
  5401. (list 'mouse-face 'highlight
  5402. 'keymap org-mouse-map
  5403. 'help-echo "Radio target link"
  5404. 'org-linked-text t))
  5405. (org-rear-nonsticky-at (match-end 1))
  5406. t))))
  5407. (defun org-update-radio-target-regexp ()
  5408. "Find all radio targets in this file and update the regular expression.
  5409. Also refresh fontification if needed."
  5410. (interactive)
  5411. (let ((old-regexp org-target-link-regexp)
  5412. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5413. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5414. (targets
  5415. (org-with-wide-buffer
  5416. (goto-char (point-min))
  5417. (let (rtn)
  5418. (while (re-search-forward org-radio-target-regexp nil t)
  5419. ;; Make sure point is really within the object.
  5420. (backward-char)
  5421. (let ((obj (org-element-context)))
  5422. (when (eq (org-element-type obj) 'radio-target)
  5423. (cl-pushnew (org-element-property :value obj) rtn
  5424. :test #'equal))))
  5425. rtn))))
  5426. (setq org-target-link-regexp
  5427. (and targets
  5428. (concat before-re
  5429. (mapconcat
  5430. (lambda (x)
  5431. (replace-regexp-in-string
  5432. " +" "\\s-+" (regexp-quote x) t t))
  5433. targets
  5434. "\\|")
  5435. after-re)))
  5436. (unless (equal old-regexp org-target-link-regexp)
  5437. ;; Clean-up cache.
  5438. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5439. ((not org-target-link-regexp) old-regexp)
  5440. (t
  5441. (concat before-re
  5442. (mapconcat
  5443. (lambda (re)
  5444. (substring re (length before-re)
  5445. (- (length after-re))))
  5446. (list old-regexp org-target-link-regexp)
  5447. "\\|")
  5448. after-re)))))
  5449. (org-with-wide-buffer
  5450. (goto-char (point-min))
  5451. (while (re-search-forward regexp nil t)
  5452. (org-element-cache-refresh (match-beginning 1)))))
  5453. ;; Re fontify buffer.
  5454. (when (memq 'radio org-highlight-links)
  5455. (org-restart-font-lock)))))
  5456. (defun org-hide-wide-columns (limit)
  5457. (let (s e)
  5458. (setq s (text-property-any (point) (or limit (point-max))
  5459. 'org-cwidth t))
  5460. (when s
  5461. (setq e (next-single-property-change s 'org-cwidth))
  5462. (add-text-properties s e '(invisible org-cwidth))
  5463. (goto-char e)
  5464. t)))
  5465. (defvar org-latex-and-related-regexp nil
  5466. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5467. (defun org-compute-latex-and-related-regexp ()
  5468. "Compute regular expression for LaTeX, entities and sub/superscript.
  5469. Result depends on variable `org-highlight-latex-and-related'."
  5470. (setq-local
  5471. org-latex-and-related-regexp
  5472. (let* ((re-sub
  5473. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5474. ((eq org-use-sub-superscripts '{})
  5475. (list org-match-substring-with-braces-regexp))
  5476. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5477. (re-latex
  5478. (when (memq 'latex org-highlight-latex-and-related)
  5479. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5480. (delq nil
  5481. (mapcar (lambda (x)
  5482. (and (member (car x) matchers) (nth 1 x)))
  5483. org-latex-regexps)))))
  5484. (re-entities
  5485. (when (memq 'entities org-highlight-latex-and-related)
  5486. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5487. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5488. (defun org-do-latex-and-related (limit)
  5489. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5490. LIMIT bounds the search for syntax to highlight. Stop at first
  5491. highlighted object, if any. Return t if some highlighting was
  5492. done, nil otherwise."
  5493. (when (org-string-nw-p org-latex-and-related-regexp)
  5494. (catch 'found
  5495. (while (re-search-forward org-latex-and-related-regexp limit t)
  5496. (unless
  5497. (cl-some
  5498. (lambda (f)
  5499. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5500. (save-excursion
  5501. (goto-char (1+ (match-beginning 0)))
  5502. (face-at-point nil t)))
  5503. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5504. '(?_ ?^))
  5505. 1
  5506. 0)))
  5507. (font-lock-prepend-text-property
  5508. (+ offset (match-beginning 0)) (match-end 0)
  5509. 'face 'org-latex-and-related)
  5510. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5511. '(font-lock-multiline t)))
  5512. (throw 'found t)))
  5513. nil)))
  5514. (defun org-restart-font-lock ()
  5515. "Restart `font-lock-mode', to force refontification."
  5516. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5517. (font-lock-mode -1)
  5518. (font-lock-mode 1)))
  5519. (defun org-activate-tags (limit)
  5520. (when (re-search-forward
  5521. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5522. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5523. (add-text-properties (match-beginning 1) (match-end 1)
  5524. (list 'mouse-face 'highlight
  5525. 'keymap org-mouse-map))
  5526. (org-rear-nonsticky-at (match-end 1))
  5527. t))
  5528. (defun org-outline-level ()
  5529. "Compute the outline level of the heading at point.
  5530. If this is called at a normal headline, the level is the number
  5531. of stars. Use `org-reduced-level' to remove the effect of
  5532. `org-odd-levels'. Unlike to `org-current-level', this function
  5533. takes into consideration inlinetasks."
  5534. (org-with-wide-buffer
  5535. (end-of-line)
  5536. (if (re-search-backward org-outline-regexp-bol nil t)
  5537. (1- (- (match-end 0) (match-beginning 0)))
  5538. 0)))
  5539. (defvar org-font-lock-keywords nil)
  5540. (defsubst org-re-property (property &optional literal allow-null value)
  5541. "Return a regexp matching a PROPERTY line.
  5542. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5543. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5544. non-nil, match properties even without a value.
  5545. Match group 3 is set to the value when it exists. If there is no
  5546. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5547. With optional argument VALUE, match only property lines with
  5548. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5549. unless LITERAL is non-nil."
  5550. (concat
  5551. "^\\(?4:[ \t]*\\)"
  5552. (format "\\(?1::\\(?2:%s\\):\\)"
  5553. (if literal property (regexp-quote property)))
  5554. (cond (value
  5555. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5556. (if literal value (regexp-quote value))))
  5557. (allow-null
  5558. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5559. (t
  5560. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5561. (defconst org-property-re
  5562. (org-re-property "\\S-+" 'literal t)
  5563. "Regular expression matching a property line.
  5564. There are four matching groups:
  5565. 1: :PROPKEY: including the leading and trailing colon,
  5566. 2: PROPKEY without the leading and trailing colon,
  5567. 3: PROPVAL without leading or trailing spaces,
  5568. 4: the indentation of the current line,
  5569. 5: trailing whitespace.")
  5570. (defvar org-font-lock-hook nil
  5571. "Functions to be called for special font lock stuff.")
  5572. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5573. (defvar org-font-lock-set-keywords-hook nil
  5574. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5575. This is called after `org-font-lock-extra-keywords' is defined, but before
  5576. it is installed to be used by font lock. This can be useful if something
  5577. needs to be inserted at a specific position in the font-lock sequence.")
  5578. (defun org-font-lock-hook (limit)
  5579. "Run `org-font-lock-hook' within LIMIT."
  5580. (run-hook-with-args 'org-font-lock-hook limit))
  5581. (defun org-set-font-lock-defaults ()
  5582. "Set font lock defaults for the current buffer."
  5583. (let* ((em org-fontify-emphasized-text)
  5584. (lk org-highlight-links)
  5585. (org-font-lock-extra-keywords
  5586. (list
  5587. ;; Call the hook
  5588. '(org-font-lock-hook)
  5589. ;; Headlines
  5590. `(,(if org-fontify-whole-heading-line
  5591. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5592. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5593. (1 (org-get-level-face 1))
  5594. (2 (org-get-level-face 2))
  5595. (3 (org-get-level-face 3)))
  5596. ;; Table lines
  5597. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5598. (1 'org-table t))
  5599. ;; Table internals
  5600. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5601. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5602. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5603. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5604. ;; Drawers
  5605. '(org-fontify-drawers)
  5606. ;; Properties
  5607. (list org-property-re
  5608. '(1 'org-special-keyword t)
  5609. '(3 'org-property-value t))
  5610. ;; Links
  5611. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5612. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5613. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
  5614. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
  5615. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5616. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5617. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5618. ;; Targets.
  5619. (list org-any-target-regexp '(0 'org-target t))
  5620. ;; Diary sexps.
  5621. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5622. ;; Macro
  5623. '(org-fontify-macros)
  5624. '(org-hide-wide-columns (0 nil append))
  5625. ;; TODO keyword
  5626. (list (format org-heading-keyword-regexp-format
  5627. org-todo-regexp)
  5628. '(2 (org-get-todo-face 2) t))
  5629. ;; DONE
  5630. (if org-fontify-done-headline
  5631. (list (format org-heading-keyword-regexp-format
  5632. (concat
  5633. "\\(?:"
  5634. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5635. "\\)"))
  5636. '(2 'org-headline-done t))
  5637. nil)
  5638. ;; Priorities
  5639. '(org-font-lock-add-priority-faces)
  5640. ;; Tags
  5641. '(org-font-lock-add-tag-faces)
  5642. ;; Tags groups
  5643. (when (and org-group-tags org-tag-groups-alist)
  5644. (list (concat org-outline-regexp-bol ".+\\(:"
  5645. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5646. ":\\).*$")
  5647. '(1 'org-tag-group prepend)))
  5648. ;; Special keywords
  5649. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5650. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5651. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5652. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5653. ;; Emphasis
  5654. (when em '(org-do-emphasis-faces))
  5655. ;; Checkboxes
  5656. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5657. 1 'org-checkbox prepend)
  5658. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5659. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5660. (0 (org-get-checkbox-statistics-face) t)))
  5661. ;; Description list items
  5662. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5663. 1 'org-list-dt prepend)
  5664. ;; ARCHIVEd headings
  5665. (list (concat
  5666. org-outline-regexp-bol
  5667. "\\(.*:" org-archive-tag ":.*\\)")
  5668. '(1 'org-archived prepend))
  5669. ;; Specials
  5670. '(org-do-latex-and-related)
  5671. '(org-fontify-entities)
  5672. '(org-raise-scripts)
  5673. ;; Code
  5674. '(org-activate-code (1 'org-code t))
  5675. ;; COMMENT
  5676. (list (format
  5677. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5678. org-todo-regexp
  5679. org-comment-string)
  5680. '(9 'org-special-keyword t))
  5681. ;; Blocks and meta lines
  5682. '(org-fontify-meta-lines-and-blocks))))
  5683. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5684. (run-hooks 'org-font-lock-set-keywords-hook)
  5685. ;; Now set the full font-lock-keywords
  5686. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5687. (setq-local font-lock-defaults
  5688. '(org-font-lock-keywords t nil nil backward-paragraph))
  5689. (kill-local-variable 'font-lock-keywords)
  5690. nil))
  5691. (defun org-toggle-pretty-entities ()
  5692. "Toggle the composition display of entities as UTF8 characters."
  5693. (interactive)
  5694. (setq-local org-pretty-entities (not org-pretty-entities))
  5695. (org-restart-font-lock)
  5696. (if org-pretty-entities
  5697. (message "Entities are now displayed as UTF8 characters")
  5698. (save-restriction
  5699. (widen)
  5700. (decompose-region (point-min) (point-max))
  5701. (message "Entities are now displayed as plain text"))))
  5702. (defvar-local org-custom-properties-overlays nil
  5703. "List of overlays used for custom properties.")
  5704. (defun org-toggle-custom-properties-visibility ()
  5705. "Display or hide properties in `org-custom-properties'."
  5706. (interactive)
  5707. (if org-custom-properties-overlays
  5708. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5709. (setq org-custom-properties-overlays nil))
  5710. (when org-custom-properties
  5711. (org-with-wide-buffer
  5712. (goto-char (point-min))
  5713. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5714. (while (re-search-forward regexp nil t)
  5715. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5716. (when (and end (< (point) end))
  5717. ;; Hide first custom property in current drawer.
  5718. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5719. (overlay-put o 'invisible t)
  5720. (overlay-put o 'org-custom-property t)
  5721. (push o org-custom-properties-overlays))
  5722. ;; Hide additional custom properties in the same drawer.
  5723. (while (re-search-forward regexp end t)
  5724. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5725. (overlay-put o 'invisible t)
  5726. (overlay-put o 'org-custom-property t)
  5727. (push o org-custom-properties-overlays)))))
  5728. ;; Each entry is limited to a single property drawer.
  5729. (outline-next-heading)))))))
  5730. (defun org-fontify-entities (limit)
  5731. "Find an entity to fontify."
  5732. (let (ee)
  5733. (when org-pretty-entities
  5734. (catch 'match
  5735. ;; "\_ "-family is left out on purpose. Only the first one,
  5736. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5737. ;; confusing when adding a second white space character.
  5738. (while (re-search-forward
  5739. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5740. limit t)
  5741. (when (and (not (org-at-comment-p))
  5742. (setq ee (org-entity-get (match-string 1)))
  5743. (= (length (nth 6 ee)) 1))
  5744. (let* ((end (if (equal (match-string 2) "{}")
  5745. (match-end 2)
  5746. (match-end 1))))
  5747. (add-text-properties
  5748. (match-beginning 0) end
  5749. (list 'font-lock-fontified t))
  5750. (compose-region (match-beginning 0) end
  5751. (nth 6 ee) nil)
  5752. (backward-char 1)
  5753. (throw 'match t))))
  5754. nil))))
  5755. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5756. "Fontify string S like in Org-mode."
  5757. (with-temp-buffer
  5758. (insert s)
  5759. (let ((org-odd-levels-only odd-levels))
  5760. (org-mode)
  5761. (org-font-lock-ensure)
  5762. (buffer-string))))
  5763. (defvar org-m nil)
  5764. (defvar org-l nil)
  5765. (defvar org-f nil)
  5766. (defun org-get-level-face (n)
  5767. "Get the right face for match N in font-lock matching of headlines."
  5768. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5769. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5770. (if org-cycle-level-faces
  5771. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5772. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5773. (cond
  5774. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5775. ((eq n 2) org-f)
  5776. (t (unless org-level-color-stars-only org-f))))
  5777. (defun org-face-from-face-or-color (context inherit face-or-color)
  5778. "Create a face list that inherits INHERIT, but sets the foreground color.
  5779. When FACE-OR-COLOR is not a string, just return it."
  5780. (if (stringp face-or-color)
  5781. (list :inherit inherit
  5782. (cdr (assoc context org-faces-easy-properties))
  5783. face-or-color)
  5784. face-or-color))
  5785. (defun org-get-todo-face (kwd)
  5786. "Get the right face for a TODO keyword KWD.
  5787. If KWD is a number, get the corresponding match group."
  5788. (when (numberp kwd) (setq kwd (match-string kwd)))
  5789. (or (org-face-from-face-or-color
  5790. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5791. (and (member kwd org-done-keywords) 'org-done)
  5792. 'org-todo))
  5793. (defun org-get-priority-face (priority)
  5794. "Get the right face for PRIORITY.
  5795. PRIORITY is a character."
  5796. (or (org-face-from-face-or-color
  5797. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5798. 'org-priority))
  5799. (defun org-get-tag-face (tag)
  5800. "Get the right face for TAG.
  5801. If TAG is a number, get the corresponding match group."
  5802. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5803. (or (org-face-from-face-or-color
  5804. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5805. 'org-tag)))
  5806. (defun org-font-lock-add-priority-faces (limit)
  5807. "Add the special priority faces."
  5808. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5809. (add-text-properties
  5810. (match-beginning 1) (match-end 1)
  5811. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5812. 'font-lock-fontified t))))
  5813. (defun org-font-lock-add-tag-faces (limit)
  5814. "Add the special tag faces."
  5815. (when (and org-tag-faces org-tags-special-faces-re)
  5816. (while (re-search-forward org-tags-special-faces-re limit t)
  5817. (add-text-properties (match-beginning 1) (match-end 1)
  5818. (list 'face (org-get-tag-face 1)
  5819. 'font-lock-fontified t))
  5820. (backward-char 1))))
  5821. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5822. "Remove fontification and activation overlays from links."
  5823. (font-lock-default-unfontify-region beg end)
  5824. (let* ((buffer-undo-list t)
  5825. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5826. (inhibit-modification-hooks t)
  5827. deactivate-mark buffer-file-name buffer-file-truename)
  5828. (decompose-region beg end)
  5829. (remove-text-properties beg end
  5830. '(mouse-face t keymap t org-linked-text t
  5831. invisible t intangible t
  5832. org-emphasis t))
  5833. (org-remove-font-lock-display-properties beg end)))
  5834. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5835. ((raise 0.3) (height 0.7))
  5836. ((raise -0.5))
  5837. ((raise 0.5)))
  5838. "Display properties for showing superscripts and subscripts.")
  5839. (defun org-remove-font-lock-display-properties (beg end)
  5840. "Remove specific display properties that have been added by font lock.
  5841. The will remove the raise properties that are used to show superscripts
  5842. and subscripts."
  5843. (let (next prop)
  5844. (while (< beg end)
  5845. (setq next (next-single-property-change beg 'display nil end)
  5846. prop (get-text-property beg 'display))
  5847. (when (member prop org-script-display)
  5848. (put-text-property beg next 'display nil))
  5849. (setq beg next))))
  5850. (defun org-raise-scripts (limit)
  5851. "Add raise properties to sub/superscripts."
  5852. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5853. (re-search-forward
  5854. (if (eq org-use-sub-superscripts t)
  5855. org-match-substring-regexp
  5856. org-match-substring-with-braces-regexp)
  5857. limit t))
  5858. (let* ((pos (point)) table-p comment-p
  5859. (mpos (match-beginning 3))
  5860. (emph-p (get-text-property mpos 'org-emphasis))
  5861. (link-p (get-text-property mpos 'mouse-face))
  5862. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5863. (goto-char (point-at-bol))
  5864. (setq table-p (looking-at-p org-table-dataline-regexp)
  5865. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5866. (goto-char pos)
  5867. ;; Handle a_b^c
  5868. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5869. (unless (or comment-p emph-p link-p keyw-p)
  5870. (put-text-property (match-beginning 3) (match-end 0)
  5871. 'display
  5872. (if (equal (char-after (match-beginning 2)) ?^)
  5873. (nth (if table-p 3 1) org-script-display)
  5874. (nth (if table-p 2 0) org-script-display)))
  5875. (add-text-properties (match-beginning 2) (match-end 2)
  5876. (list 'invisible t
  5877. 'org-dwidth t 'org-dwidth-n 1))
  5878. (if (and (eq (char-after (match-beginning 3)) ?{)
  5879. (eq (char-before (match-end 3)) ?}))
  5880. (progn
  5881. (add-text-properties
  5882. (match-beginning 3) (1+ (match-beginning 3))
  5883. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5884. (add-text-properties
  5885. (1- (match-end 3)) (match-end 3)
  5886. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5887. t)))
  5888. ;;;; Visibility cycling, including org-goto and indirect buffer
  5889. ;;; Cycling
  5890. (defvar-local org-cycle-global-status nil)
  5891. (put 'org-cycle-global-status 'org-state t)
  5892. (defvar-local org-cycle-subtree-status nil)
  5893. (put 'org-cycle-subtree-status 'org-state t)
  5894. (defvar org-inlinetask-min-level)
  5895. (defun org-unlogged-message (&rest args)
  5896. "Display a message, but avoid logging it in the *Messages* buffer."
  5897. (let ((message-log-max nil))
  5898. (apply 'message args)))
  5899. ;;;###autoload
  5900. (defun org-cycle (&optional arg)
  5901. "TAB-action and visibility cycling for Org-mode.
  5902. This is the command invoked in Org-mode by the TAB key. Its main purpose
  5903. is outline visibility cycling, but it also invokes other actions
  5904. in special contexts.
  5905. - When this function is called with a prefix argument, rotate the entire
  5906. buffer through 3 states (global cycling)
  5907. 1. OVERVIEW: Show only top-level headlines.
  5908. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5909. 3. SHOW ALL: Show everything.
  5910. With a double \\[universal-argument] prefix argument, \
  5911. switch to the startup visibility,
  5912. determined by the variable `org-startup-folded', and by any VISIBILITY
  5913. properties in the buffer.
  5914. With a triple \\[universal-argument] prefix argument, \
  5915. show the entire buffer, including any drawers.
  5916. - When inside a table, re-align the table and move to the next field.
  5917. - When point is at the beginning of a headline, rotate the subtree started
  5918. by this line through 3 different states (local cycling)
  5919. 1. FOLDED: Only the main headline is shown.
  5920. 2. CHILDREN: The main headline and the direct children are shown.
  5921. From this state, you can move to one of the children
  5922. and zoom in further.
  5923. 3. SUBTREE: Show the entire subtree, including body text.
  5924. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5925. - When point is at the beginning of an empty headline and the variable
  5926. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5927. of the headline by demoting and promoting it to likely levels. This
  5928. speeds up creation document structure by pressing TAB once or several
  5929. times right after creating a new headline.
  5930. - When there is a numeric prefix, go up to a heading with level ARG, do
  5931. a `show-subtree' and return to the previous cursor position. If ARG
  5932. is negative, go up that many levels.
  5933. - When point is not at the beginning of a headline, execute the global
  5934. binding for TAB, which is re-indenting the line. See the option
  5935. `org-cycle-emulate-tab' for details.
  5936. - Special case: if point is at the beginning of the buffer and there is
  5937. no headline in line 1, this function will act as if called with prefix arg
  5938. (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
  5939. But only if also the variable `org-cycle-global-at-bob' is t."
  5940. (interactive "P")
  5941. (org-load-modules-maybe)
  5942. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5943. (and org-cycle-level-after-item/entry-creation
  5944. (or (org-cycle-level)
  5945. (org-cycle-item-indentation))))
  5946. (let* ((limit-level
  5947. (or org-cycle-max-level
  5948. (and (boundp 'org-inlinetask-min-level)
  5949. org-inlinetask-min-level
  5950. (1- org-inlinetask-min-level))))
  5951. (nstars (and limit-level
  5952. (if org-odd-levels-only
  5953. (and limit-level (1- (* limit-level 2)))
  5954. limit-level)))
  5955. (org-outline-regexp
  5956. (if (not (derived-mode-p 'org-mode))
  5957. outline-regexp
  5958. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5959. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5960. (not (looking-at org-outline-regexp))))
  5961. (org-cycle-hook
  5962. (if bob-special
  5963. (delq 'org-optimize-window-after-visibility-change
  5964. (copy-sequence org-cycle-hook))
  5965. org-cycle-hook))
  5966. (pos (point)))
  5967. (when (or bob-special (equal arg '(4)))
  5968. ;; special case: use global cycling
  5969. (setq arg t))
  5970. (cond
  5971. ((equal arg '(16))
  5972. (setq last-command 'dummy)
  5973. (org-set-startup-visibility)
  5974. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5975. ((equal arg '(64))
  5976. (outline-show-all)
  5977. (org-unlogged-message "Entire buffer visible, including drawers"))
  5978. ;; Try cdlatex TAB completion
  5979. ((org-try-cdlatex-tab))
  5980. ;; Table: enter it or move to the next field.
  5981. ((org-at-table-p 'any)
  5982. (if (org-at-table.el-p)
  5983. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5984. Use \\[org-edit-special] to edit table.el tables"))
  5985. (if arg (org-table-edit-field t)
  5986. (org-table-justify-field-maybe)
  5987. (call-interactively 'org-table-next-field))))
  5988. ((run-hook-with-args-until-success
  5989. 'org-tab-after-check-for-table-hook))
  5990. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5991. ((eq arg t) (org-cycle-internal-global))
  5992. ;; Drawers: delegate to `org-flag-drawer'.
  5993. ((save-excursion
  5994. (beginning-of-line 1)
  5995. (looking-at org-drawer-regexp))
  5996. (org-flag-drawer ; toggle block visibility
  5997. (not (get-char-property (match-end 0) 'invisible))))
  5998. ;; Show-subtree, ARG levels up from here.
  5999. ((integerp arg)
  6000. (save-excursion
  6001. (org-back-to-heading)
  6002. (outline-up-heading (if (< arg 0) (- arg)
  6003. (- (funcall outline-level) arg)))
  6004. (org-show-subtree)))
  6005. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6006. ((and (featurep 'org-inlinetask)
  6007. (org-inlinetask-at-task-p)
  6008. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6009. (org-inlinetask-toggle-visibility))
  6010. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6011. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6012. (save-excursion (move-beginning-of-line 1)
  6013. (looking-at org-outline-regexp)))
  6014. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6015. (org-cycle-internal-local))
  6016. ;; From there: TAB emulation and template completion.
  6017. (buffer-read-only (org-back-to-heading))
  6018. ((run-hook-with-args-until-success
  6019. 'org-tab-after-check-for-cycling-hook))
  6020. ((org-try-structure-completion))
  6021. ((run-hook-with-args-until-success
  6022. 'org-tab-before-tab-emulation-hook))
  6023. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6024. (or (not (bolp))
  6025. (not (looking-at org-outline-regexp))))
  6026. (call-interactively (global-key-binding "\t")))
  6027. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6028. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6029. (or (and (eq org-cycle-emulate-tab 'white)
  6030. (= (match-end 0) (point-at-eol)))
  6031. (and (eq org-cycle-emulate-tab 'whitestart)
  6032. (>= (match-end 0) pos))))
  6033. t
  6034. (eq org-cycle-emulate-tab t))
  6035. (call-interactively (global-key-binding "\t")))
  6036. (t (save-excursion
  6037. (org-back-to-heading)
  6038. (org-cycle)))))))
  6039. (defun org-cycle-internal-global ()
  6040. "Do the global cycling action."
  6041. ;; Hack to avoid display of messages for .org attachments in Gnus
  6042. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6043. (cond
  6044. ((and (eq last-command this-command)
  6045. (eq org-cycle-global-status 'overview))
  6046. ;; We just created the overview - now do table of contents
  6047. ;; This can be slow in very large buffers, so indicate action
  6048. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6049. (unless ga (org-unlogged-message "CONTENTS..."))
  6050. (org-content)
  6051. (unless ga (org-unlogged-message "CONTENTS...done"))
  6052. (setq org-cycle-global-status 'contents)
  6053. (run-hook-with-args 'org-cycle-hook 'contents))
  6054. ((and (eq last-command this-command)
  6055. (eq org-cycle-global-status 'contents))
  6056. ;; We just showed the table of contents - now show everything
  6057. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6058. (outline-show-all)
  6059. (unless ga (org-unlogged-message "SHOW ALL"))
  6060. (setq org-cycle-global-status 'all)
  6061. (run-hook-with-args 'org-cycle-hook 'all))
  6062. (t
  6063. ;; Default action: go to overview
  6064. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6065. (org-overview)
  6066. (unless ga (org-unlogged-message "OVERVIEW"))
  6067. (setq org-cycle-global-status 'overview)
  6068. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6069. (defvar org-called-with-limited-levels nil
  6070. "Non-nil when `org-with-limited-levels' is currently active.")
  6071. (defun org-cycle-internal-local ()
  6072. "Do the local cycling action."
  6073. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6074. ;; First, determine end of headline (EOH), end of subtree or item
  6075. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6076. (save-excursion
  6077. (if (org-at-item-p)
  6078. (progn
  6079. (beginning-of-line)
  6080. (setq struct (org-list-struct))
  6081. (setq eoh (point-at-eol))
  6082. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6083. (setq has-children (org-list-has-child-p (point) struct)))
  6084. (org-back-to-heading)
  6085. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6086. (setq eos (save-excursion (org-end-of-subtree t t)
  6087. (when (bolp) (backward-char)) (point)))
  6088. (setq has-children
  6089. (or (save-excursion
  6090. (let ((level (funcall outline-level)))
  6091. (outline-next-heading)
  6092. (and (org-at-heading-p t)
  6093. (> (funcall outline-level) level))))
  6094. (save-excursion
  6095. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6096. ;; Determine end invisible part of buffer (EOL)
  6097. (beginning-of-line 2)
  6098. (while (and (not (eobp)) ;This is like `next-line'.
  6099. (get-char-property (1- (point)) 'invisible))
  6100. (goto-char (next-single-char-property-change (point) 'invisible))
  6101. (and (eolp) (beginning-of-line 2)))
  6102. (setq eol (point)))
  6103. ;; Find out what to do next and set `this-command'
  6104. (cond
  6105. ((= eos eoh)
  6106. ;; Nothing is hidden behind this heading
  6107. (unless (org-before-first-heading-p)
  6108. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6109. (org-unlogged-message "EMPTY ENTRY")
  6110. (setq org-cycle-subtree-status nil)
  6111. (save-excursion
  6112. (goto-char eos)
  6113. (outline-next-heading)
  6114. (when (outline-invisible-p) (org-flag-heading nil))))
  6115. ((and (or (>= eol eos)
  6116. (not (string-match "\\S-" (buffer-substring eol eos))))
  6117. (or has-children
  6118. (not (setq children-skipped
  6119. org-cycle-skip-children-state-if-no-children))))
  6120. ;; Entire subtree is hidden in one line: children view
  6121. (unless (org-before-first-heading-p)
  6122. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6123. (if (org-at-item-p)
  6124. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6125. (org-show-entry)
  6126. (org-with-limited-levels (org-show-children))
  6127. ;; FIXME: This slows down the func way too much.
  6128. ;; How keep drawers hidden in subtree anyway?
  6129. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6130. ;; (org-cycle-hide-drawers 'subtree))
  6131. ;; Fold every list in subtree to top-level items.
  6132. (when (eq org-cycle-include-plain-lists 'integrate)
  6133. (save-excursion
  6134. (org-back-to-heading)
  6135. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6136. (beginning-of-line 1)
  6137. (let* ((struct (org-list-struct))
  6138. (prevs (org-list-prevs-alist struct))
  6139. (end (org-list-get-bottom-point struct)))
  6140. (dolist (e (org-list-get-all-items (point) struct prevs))
  6141. (org-list-set-item-visibility e struct 'folded))
  6142. (goto-char (if (< end eos) end eos)))))))
  6143. (org-unlogged-message "CHILDREN")
  6144. (save-excursion
  6145. (goto-char eos)
  6146. (outline-next-heading)
  6147. (when (outline-invisible-p) (org-flag-heading nil)))
  6148. (setq org-cycle-subtree-status 'children)
  6149. (unless (org-before-first-heading-p)
  6150. (run-hook-with-args 'org-cycle-hook 'children)))
  6151. ((or children-skipped
  6152. (and (eq last-command this-command)
  6153. (eq org-cycle-subtree-status 'children)))
  6154. ;; We just showed the children, or no children are there,
  6155. ;; now show everything.
  6156. (unless (org-before-first-heading-p)
  6157. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6158. (outline-flag-region eoh eos nil)
  6159. (org-unlogged-message
  6160. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6161. (setq org-cycle-subtree-status 'subtree)
  6162. (unless (org-before-first-heading-p)
  6163. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6164. (t
  6165. ;; Default action: hide the subtree.
  6166. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6167. (outline-flag-region eoh eos t)
  6168. (org-unlogged-message "FOLDED")
  6169. (setq org-cycle-subtree-status 'folded)
  6170. (unless (org-before-first-heading-p)
  6171. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6172. ;;;###autoload
  6173. (defun org-global-cycle (&optional arg)
  6174. "Cycle the global visibility. For details see `org-cycle'.
  6175. With \\[universal-argument] prefix arg, switch to startup visibility.
  6176. With a numeric prefix, show all headlines up to that level."
  6177. (interactive "P")
  6178. (let ((org-cycle-include-plain-lists
  6179. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6180. (cond
  6181. ((integerp arg)
  6182. (outline-show-all)
  6183. (outline-hide-sublevels arg)
  6184. (setq org-cycle-global-status 'contents))
  6185. ((equal arg '(4))
  6186. (org-set-startup-visibility)
  6187. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6188. (t
  6189. (org-cycle '(4))))))
  6190. (defun org-set-startup-visibility ()
  6191. "Set the visibility required by startup options and properties."
  6192. (cond
  6193. ((eq org-startup-folded t)
  6194. (org-overview))
  6195. ((eq org-startup-folded 'content)
  6196. (org-content))
  6197. ((or (eq org-startup-folded 'showeverything)
  6198. (eq org-startup-folded nil))
  6199. (outline-show-all)))
  6200. (unless (eq org-startup-folded 'showeverything)
  6201. (when org-hide-block-startup (org-hide-block-all))
  6202. (org-set-visibility-according-to-property 'no-cleanup)
  6203. (org-cycle-hide-archived-subtrees 'all)
  6204. (org-cycle-hide-drawers 'all)
  6205. (org-cycle-show-empty-lines t)))
  6206. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6207. "Switch subtree visibilities according to :VISIBILITY: property."
  6208. (interactive)
  6209. (org-with-wide-buffer
  6210. (goto-char (point-min))
  6211. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6212. (if (not (org-at-property-p)) (outline-next-heading)
  6213. (let ((state (match-string 3)))
  6214. (save-excursion
  6215. (org-back-to-heading t)
  6216. (outline-hide-subtree)
  6217. (org-reveal)
  6218. (cond
  6219. ((equal state "folded")
  6220. (outline-hide-subtree))
  6221. ((equal state "children")
  6222. (org-show-hidden-entry)
  6223. (org-show-children))
  6224. ((equal state "content")
  6225. (save-excursion
  6226. (save-restriction
  6227. (org-narrow-to-subtree)
  6228. (org-content))))
  6229. ((member state '("all" "showall"))
  6230. (outline-show-subtree)))))))
  6231. (unless no-cleanup
  6232. (org-cycle-hide-archived-subtrees 'all)
  6233. (org-cycle-hide-drawers 'all)
  6234. (org-cycle-show-empty-lines 'all))))
  6235. ;; This function uses outline-regexp instead of the more fundamental
  6236. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6237. ;; buffers, where outline-regexp is needed.
  6238. (defun org-overview ()
  6239. "Switch to overview mode, showing only top-level headlines.
  6240. This shows all headlines with a level equal or greater than the level
  6241. of the first headline in the buffer. This is important, because if the
  6242. first headline is not level one, then (hide-sublevels 1) gives confusing
  6243. results."
  6244. (interactive)
  6245. (save-excursion
  6246. (let ((level
  6247. (save-excursion
  6248. (goto-char (point-min))
  6249. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6250. (goto-char (match-beginning 0))
  6251. (funcall outline-level)))))
  6252. (and level (outline-hide-sublevels level)))))
  6253. (defun org-content (&optional arg)
  6254. "Show all headlines in the buffer, like a table of contents.
  6255. With numerical argument N, show content up to level N."
  6256. (interactive "P")
  6257. (org-overview)
  6258. (save-excursion
  6259. ;; Visit all headings and show their offspring
  6260. (and (integerp arg) (org-overview))
  6261. (goto-char (point-max))
  6262. (catch 'exit
  6263. (while (and (progn (condition-case nil
  6264. (outline-previous-visible-heading 1)
  6265. (error (goto-char (point-min))))
  6266. t)
  6267. (looking-at org-outline-regexp))
  6268. (if (integerp arg)
  6269. (org-show-children (1- arg))
  6270. (outline-show-branches))
  6271. (when (bobp) (throw 'exit nil))))))
  6272. (defun org-optimize-window-after-visibility-change (state)
  6273. "Adjust the window after a change in outline visibility.
  6274. This function is the default value of the hook `org-cycle-hook'."
  6275. (when (get-buffer-window (current-buffer))
  6276. (cond
  6277. ((eq state 'content) nil)
  6278. ((eq state 'all) nil)
  6279. ((eq state 'folded) nil)
  6280. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6281. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6282. (defun org-remove-empty-overlays-at (pos)
  6283. "Remove outline overlays that do not contain non-white stuff."
  6284. (dolist (o (overlays-at pos))
  6285. (and (eq 'outline (overlay-get o 'invisible))
  6286. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6287. (overlay-end o))))
  6288. (delete-overlay o))))
  6289. (defun org-clean-visibility-after-subtree-move ()
  6290. "Fix visibility issues after moving a subtree."
  6291. ;; First, find a reasonable region to look at:
  6292. ;; Start two siblings above, end three below
  6293. (let* ((beg (save-excursion
  6294. (and (org-get-last-sibling)
  6295. (org-get-last-sibling))
  6296. (point)))
  6297. (end (save-excursion
  6298. (and (org-get-next-sibling)
  6299. (org-get-next-sibling)
  6300. (org-get-next-sibling))
  6301. (if (org-at-heading-p)
  6302. (point-at-eol)
  6303. (point))))
  6304. (level (looking-at "\\*+"))
  6305. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6306. (save-excursion
  6307. (save-restriction
  6308. (narrow-to-region beg end)
  6309. (when re
  6310. ;; Properly fold already folded siblings
  6311. (goto-char (point-min))
  6312. (while (re-search-forward re nil t)
  6313. (when (and (not (outline-invisible-p))
  6314. (save-excursion
  6315. (goto-char (point-at-eol)) (outline-invisible-p)))
  6316. (outline-hide-entry))))
  6317. (org-cycle-show-empty-lines 'overview)
  6318. (org-cycle-hide-drawers 'overview)))))
  6319. (defun org-cycle-show-empty-lines (state)
  6320. "Show empty lines above all visible headlines.
  6321. The region to be covered depends on STATE when called through
  6322. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6323. entire buffer covered. Note that an empty line is only shown if there
  6324. are at least `org-cycle-separator-lines' empty lines before the headline."
  6325. (when (/= org-cycle-separator-lines 0)
  6326. (save-excursion
  6327. (let* ((n (abs org-cycle-separator-lines))
  6328. (re (cond
  6329. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6330. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6331. (t (let ((ns (number-to-string (- n 2))))
  6332. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6333. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6334. beg end)
  6335. (cond
  6336. ((memq state '(overview contents t))
  6337. (setq beg (point-min) end (point-max)))
  6338. ((memq state '(children folded))
  6339. (setq beg (point)
  6340. end (progn (org-end-of-subtree t t)
  6341. (line-beginning-position 2)))))
  6342. (when beg
  6343. (goto-char beg)
  6344. (while (re-search-forward re end t)
  6345. (unless (get-char-property (match-end 1) 'invisible)
  6346. (let ((e (match-end 1))
  6347. (b (if (>= org-cycle-separator-lines 0)
  6348. (match-beginning 1)
  6349. (save-excursion
  6350. (goto-char (match-beginning 0))
  6351. (skip-chars-backward " \t\n")
  6352. (line-end-position)))))
  6353. (outline-flag-region b e nil))))))))
  6354. ;; Never hide empty lines at the end of the file.
  6355. (save-excursion
  6356. (goto-char (point-max))
  6357. (outline-previous-heading)
  6358. (outline-end-of-heading)
  6359. (when (and (looking-at "[ \t\n]+")
  6360. (= (match-end 0) (point-max)))
  6361. (outline-flag-region (point) (match-end 0) nil))))
  6362. (defun org-show-empty-lines-in-parent ()
  6363. "Move to the parent and re-show empty lines before visible headlines."
  6364. (save-excursion
  6365. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6366. (org-cycle-show-empty-lines context))))
  6367. (defun org-files-list ()
  6368. "Return `org-agenda-files' list, plus all open org-mode files.
  6369. This is useful for operations that need to scan all of a user's
  6370. open and agenda-wise Org files."
  6371. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6372. (dolist (buf (buffer-list))
  6373. (with-current-buffer buf
  6374. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6375. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6376. files))
  6377. (defsubst org-entry-beginning-position ()
  6378. "Return the beginning position of the current entry."
  6379. (save-excursion (org-back-to-heading t) (point)))
  6380. (defsubst org-entry-end-position ()
  6381. "Return the end position of the current entry."
  6382. (save-excursion (outline-next-heading) (point)))
  6383. (defun org-cycle-hide-drawers (state &optional exceptions)
  6384. "Re-hide all drawers after a visibility state change.
  6385. When non-nil, optional argument EXCEPTIONS is a list of strings
  6386. specifying which drawers should not be hidden."
  6387. (when (and (derived-mode-p 'org-mode)
  6388. (not (memq state '(overview folded contents))))
  6389. (save-excursion
  6390. (let* ((globalp (memq state '(contents all)))
  6391. (beg (if globalp (point-min) (point)))
  6392. (end (if globalp (point-max)
  6393. (if (eq state 'children)
  6394. (save-excursion (outline-next-heading) (point))
  6395. (org-end-of-subtree t)))))
  6396. (goto-char beg)
  6397. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6398. (unless (member-ignore-case (match-string 1) exceptions)
  6399. (let ((drawer (org-element-at-point)))
  6400. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6401. (org-flag-drawer t drawer)
  6402. ;; Make sure to skip drawer entirely or we might flag
  6403. ;; it another time when matching its ending line with
  6404. ;; `org-drawer-regexp'.
  6405. (goto-char (org-element-property :end drawer))))))))))
  6406. (defun org-flag-drawer (flag &optional element)
  6407. "When FLAG is non-nil, hide the drawer we are at.
  6408. Otherwise make it visible. When optional argument ELEMENT is
  6409. a parsed drawer, as returned by `org-element-at-point', hide or
  6410. show that drawer instead."
  6411. (let ((drawer (or element
  6412. (and (save-excursion
  6413. (beginning-of-line)
  6414. (looking-at-p org-drawer-regexp))
  6415. (org-element-at-point)))))
  6416. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6417. (let ((post (org-element-property :post-affiliated drawer)))
  6418. (save-excursion
  6419. (outline-flag-region
  6420. (progn (goto-char post) (line-end-position))
  6421. (progn (goto-char (org-element-property :end drawer))
  6422. (skip-chars-backward " \r\t\n")
  6423. (line-end-position))
  6424. flag))
  6425. ;; When the drawer is hidden away, make sure point lies in
  6426. ;; a visible part of the buffer.
  6427. (when (and flag (> (line-beginning-position) post))
  6428. (goto-char post))))))
  6429. (defun org-subtree-end-visible-p ()
  6430. "Is the end of the current subtree visible?"
  6431. (pos-visible-in-window-p
  6432. (save-excursion (org-end-of-subtree t) (point))))
  6433. (defun org-first-headline-recenter ()
  6434. "Move cursor to the first headline and recenter the headline."
  6435. (let ((window (get-buffer-window)))
  6436. (when window
  6437. (goto-char (point-min))
  6438. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6439. (set-window-start window (line-beginning-position))))))
  6440. ;;; Saving and restoring visibility
  6441. (defun org-outline-overlay-data (&optional use-markers)
  6442. "Return a list of the locations of all outline overlays.
  6443. These are overlays with the `invisible' property value `outline'.
  6444. The return value is a list of cons cells, with start and stop
  6445. positions for each overlay.
  6446. If USE-MARKERS is set, return the positions as markers."
  6447. (let (beg end)
  6448. (save-excursion
  6449. (save-restriction
  6450. (widen)
  6451. (delq nil
  6452. (mapcar (lambda (o)
  6453. (when (eq (overlay-get o 'invisible) 'outline)
  6454. (setq beg (overlay-start o)
  6455. end (overlay-end o))
  6456. (and beg end (> end beg)
  6457. (if use-markers
  6458. (cons (copy-marker beg)
  6459. (copy-marker end t))
  6460. (cons beg end)))))
  6461. (overlays-in (point-min) (point-max))))))))
  6462. (defun org-set-outline-overlay-data (data)
  6463. "Create visibility overlays for all positions in DATA.
  6464. DATA should have been made by `org-outline-overlay-data'."
  6465. (org-with-wide-buffer
  6466. (outline-show-all)
  6467. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6468. ;;; Folding of blocks
  6469. (defvar-local org-hide-block-overlays nil
  6470. "Overlays hiding blocks.")
  6471. (defun org-block-map (function &optional start end)
  6472. "Call FUNCTION at the head of all source blocks in the current buffer.
  6473. Optional arguments START and END can be used to limit the range."
  6474. (let ((start (or start (point-min)))
  6475. (end (or end (point-max))))
  6476. (save-excursion
  6477. (goto-char start)
  6478. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6479. (save-excursion
  6480. (save-match-data
  6481. (goto-char (match-beginning 0))
  6482. (funcall function)))))))
  6483. (defun org-hide-block-toggle-all ()
  6484. "Toggle the visibility of all blocks in the current buffer."
  6485. (org-block-map 'org-hide-block-toggle))
  6486. (defun org-hide-block-all ()
  6487. "Fold all blocks in the current buffer."
  6488. (interactive)
  6489. (org-show-block-all)
  6490. (org-block-map 'org-hide-block-toggle-maybe))
  6491. (defun org-show-block-all ()
  6492. "Unfold all blocks in the current buffer."
  6493. (interactive)
  6494. (mapc #'delete-overlay org-hide-block-overlays)
  6495. (setq org-hide-block-overlays nil))
  6496. (defun org-hide-block-toggle-maybe ()
  6497. "Toggle visibility of block at point.
  6498. Unlike to `org-hide-block-toggle', this function does not throw
  6499. an error. Return a non-nil value when toggling is successful."
  6500. (interactive)
  6501. (ignore-errors (org-hide-block-toggle)))
  6502. (defun org-hide-block-toggle (&optional force)
  6503. "Toggle the visibility of the current block.
  6504. When optional argument FORCE is `off', make block visible. If it
  6505. is non-nil, hide it unconditionally. Throw an error when not at
  6506. a block. Return a non-nil value when toggling is successful."
  6507. (interactive)
  6508. (let ((element (org-element-at-point)))
  6509. (unless (memq (org-element-type element)
  6510. '(center-block comment-block dynamic-block example-block
  6511. export-block quote-block special-block
  6512. src-block verse-block))
  6513. (user-error "Not at a block"))
  6514. (let* ((start (save-excursion
  6515. (goto-char (org-element-property :post-affiliated element))
  6516. (line-end-position)))
  6517. (end (save-excursion
  6518. (goto-char (org-element-property :end element))
  6519. (skip-chars-backward " \r\t\n")
  6520. (line-end-position)))
  6521. (overlays (overlays-at start)))
  6522. (cond
  6523. ;; Do nothing when not before or at the block opening line or
  6524. ;; at the block closing line.
  6525. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6526. ((and (not (eq force 'off))
  6527. (not (memq t (mapcar
  6528. (lambda (o)
  6529. (eq (overlay-get o 'invisible) 'org-hide-block))
  6530. overlays))))
  6531. (let ((ov (make-overlay start end)))
  6532. (overlay-put ov 'invisible 'org-hide-block)
  6533. ;; Make the block accessible to `isearch'.
  6534. (overlay-put
  6535. ov 'isearch-open-invisible
  6536. (lambda (ov)
  6537. (when (memq ov org-hide-block-overlays)
  6538. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6539. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6540. (delete-overlay ov))))
  6541. (push ov org-hide-block-overlays)
  6542. ;; When the block is hidden away, make sure point is left in
  6543. ;; a visible part of the buffer.
  6544. (when (> (line-beginning-position) start)
  6545. (goto-char start)
  6546. (beginning-of-line))
  6547. ;; Signal successful toggling.
  6548. t))
  6549. ((or (not force) (eq force 'off))
  6550. (dolist (ov overlays t)
  6551. (when (memq ov org-hide-block-overlays)
  6552. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6553. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6554. (delete-overlay ov))))))))
  6555. ;; org-tab-after-check-for-cycling-hook
  6556. (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
  6557. ;; Remove overlays when changing major mode
  6558. (add-hook 'org-mode-hook
  6559. (lambda () (add-hook 'change-major-mode-hook
  6560. 'org-show-block-all 'append 'local)))
  6561. ;;; Org-goto
  6562. (defvar org-goto-window-configuration nil)
  6563. (defvar org-goto-marker nil)
  6564. (defvar org-goto-map)
  6565. (defun org-goto-map ()
  6566. "Set the keymap `org-goto'."
  6567. (setq org-goto-map
  6568. (let ((map (make-sparse-keymap)))
  6569. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6570. mouse-drag-region universal-argument org-occur)))
  6571. (dolist (cmd cmds)
  6572. (substitute-key-definition cmd cmd map global-map)))
  6573. (suppress-keymap map)
  6574. (org-defkey map "\C-m" 'org-goto-ret)
  6575. (org-defkey map [(return)] 'org-goto-ret)
  6576. (org-defkey map [(left)] 'org-goto-left)
  6577. (org-defkey map [(right)] 'org-goto-right)
  6578. (org-defkey map [(control ?g)] 'org-goto-quit)
  6579. (org-defkey map "\C-i" 'org-cycle)
  6580. (org-defkey map [(tab)] 'org-cycle)
  6581. (org-defkey map [(down)] 'outline-next-visible-heading)
  6582. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6583. (if org-goto-auto-isearch
  6584. (if (fboundp 'define-key-after)
  6585. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6586. nil)
  6587. (org-defkey map "q" 'org-goto-quit)
  6588. (org-defkey map "n" 'outline-next-visible-heading)
  6589. (org-defkey map "p" 'outline-previous-visible-heading)
  6590. (org-defkey map "f" 'outline-forward-same-level)
  6591. (org-defkey map "b" 'outline-backward-same-level)
  6592. (org-defkey map "u" 'outline-up-heading))
  6593. (org-defkey map "/" 'org-occur)
  6594. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6595. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6596. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6597. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6598. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6599. map)))
  6600. (defconst org-goto-help
  6601. "Browse buffer copy, to find location or copy text.%s
  6602. RET=jump to location C-g=quit and return to previous location
  6603. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6604. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6605. (defun org-goto (&optional alternative-interface)
  6606. "Look up a different location in the current file, keeping current visibility.
  6607. When you want look-up or go to a different location in a
  6608. document, the fastest way is often to fold the entire buffer and
  6609. then dive into the tree. This method has the disadvantage, that
  6610. the previous location will be folded, which may not be what you
  6611. want.
  6612. This command works around this by showing a copy of the current
  6613. buffer in an indirect buffer, in overview mode. You can dive
  6614. into the tree in that copy, use org-occur and incremental search
  6615. to find a location. When pressing RET or `Q', the command
  6616. returns to the original buffer in which the visibility is still
  6617. unchanged. After RET it will also jump to the location selected
  6618. in the indirect buffer and expose the headline hierarchy above.
  6619. With a prefix argument, use the alternative interface: e.g., if
  6620. `org-goto-interface' is `outline' use `outline-path-completion'."
  6621. (interactive "P")
  6622. (org-goto-map)
  6623. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6624. (org-refile-use-outline-path t)
  6625. (org-refile-target-verify-function nil)
  6626. (interface
  6627. (if (not alternative-interface)
  6628. org-goto-interface
  6629. (if (eq org-goto-interface 'outline)
  6630. 'outline-path-completion
  6631. 'outline)))
  6632. (org-goto-start-pos (point))
  6633. (selected-point
  6634. (if (eq interface 'outline)
  6635. (car (org-get-location (current-buffer) org-goto-help))
  6636. (let ((pa (org-refile-get-location "Goto")))
  6637. (org-refile-check-position pa)
  6638. (nth 3 pa)))))
  6639. (if selected-point
  6640. (progn
  6641. (org-mark-ring-push org-goto-start-pos)
  6642. (goto-char selected-point)
  6643. (when (or (outline-invisible-p) (org-invisible-p2))
  6644. (org-show-context 'org-goto)))
  6645. (message "Quit"))))
  6646. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6647. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6648. (defvar org-goto-local-auto-isearch-map) ; defined below
  6649. (defun org-get-location (_buf help)
  6650. "Let the user select a location in current buffer.
  6651. This function uses a recursive edit. It returns the selected position
  6652. or nil."
  6653. (org-no-popups
  6654. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6655. (isearch-hide-immediately nil)
  6656. (isearch-search-fun-function
  6657. (lambda () 'org-goto-local-search-headings))
  6658. (org-goto-selected-point org-goto-exit-command))
  6659. (save-excursion
  6660. (save-window-excursion
  6661. (delete-other-windows)
  6662. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6663. (pop-to-buffer-same-window
  6664. (condition-case nil
  6665. (make-indirect-buffer (current-buffer) "*org-goto*")
  6666. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6667. (with-output-to-temp-buffer "*Org Help*"
  6668. (princ (format help (if org-goto-auto-isearch
  6669. " Just type for auto-isearch."
  6670. " n/p/f/b/u to navigate, q to quit."))))
  6671. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6672. (setq buffer-read-only nil)
  6673. (let ((org-startup-truncated t)
  6674. (org-startup-folded nil)
  6675. (org-startup-align-all-tables nil))
  6676. (org-mode)
  6677. (org-overview))
  6678. (setq buffer-read-only t)
  6679. (if (and (boundp 'org-goto-start-pos)
  6680. (integer-or-marker-p org-goto-start-pos))
  6681. (progn (goto-char org-goto-start-pos)
  6682. (when (outline-invisible-p)
  6683. (org-show-set-visibility 'lineage)))
  6684. (goto-char (point-min)))
  6685. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6686. (message "Select location and press RET")
  6687. (use-local-map org-goto-map)
  6688. (recursive-edit)))
  6689. (kill-buffer "*org-goto*")
  6690. (cons org-goto-selected-point org-goto-exit-command))))
  6691. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6692. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6693. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6694. (if (fboundp 'isearch-other-control-char)
  6695. (progn
  6696. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6697. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6698. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6699. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6700. (define-key org-goto-local-auto-isearch-map [return] nil))
  6701. (defun org-goto-local-search-headings (string bound noerror)
  6702. "Search and make sure that any matches are in headlines."
  6703. (catch 'return
  6704. (while (if isearch-forward
  6705. (search-forward string bound noerror)
  6706. (search-backward string bound noerror))
  6707. (when (save-match-data
  6708. (and (save-excursion
  6709. (beginning-of-line)
  6710. (looking-at org-complex-heading-regexp))
  6711. (or (not (match-beginning 5))
  6712. (< (point) (match-beginning 5)))))
  6713. (throw 'return (point))))))
  6714. (defun org-goto-local-auto-isearch ()
  6715. "Start isearch."
  6716. (interactive)
  6717. (goto-char (point-min))
  6718. (let ((keys (this-command-keys)))
  6719. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6720. (isearch-mode t)
  6721. (isearch-process-search-char (string-to-char keys)))))
  6722. (defun org-goto-ret (&optional _arg)
  6723. "Finish `org-goto' by going to the new location."
  6724. (interactive "P")
  6725. (setq org-goto-selected-point (point))
  6726. (setq org-goto-exit-command 'return)
  6727. (throw 'exit nil))
  6728. (defun org-goto-left ()
  6729. "Finish `org-goto' by going to the new location."
  6730. (interactive)
  6731. (if (org-at-heading-p)
  6732. (progn
  6733. (beginning-of-line 1)
  6734. (setq org-goto-selected-point (point)
  6735. org-goto-exit-command 'left)
  6736. (throw 'exit nil))
  6737. (user-error "Not on a heading")))
  6738. (defun org-goto-right ()
  6739. "Finish `org-goto' by going to the new location."
  6740. (interactive)
  6741. (if (org-at-heading-p)
  6742. (progn
  6743. (setq org-goto-selected-point (point)
  6744. org-goto-exit-command 'right)
  6745. (throw 'exit nil))
  6746. (user-error "Not on a heading")))
  6747. (defun org-goto-quit ()
  6748. "Finish `org-goto' without cursor motion."
  6749. (interactive)
  6750. (setq org-goto-selected-point nil)
  6751. (setq org-goto-exit-command 'quit)
  6752. (throw 'exit nil))
  6753. ;;; Indirect buffer display of subtrees
  6754. (defvar org-indirect-dedicated-frame nil
  6755. "This is the frame being used for indirect tree display.")
  6756. (defvar org-last-indirect-buffer nil)
  6757. (defun org-tree-to-indirect-buffer (&optional arg)
  6758. "Create indirect buffer and narrow it to current subtree.
  6759. With a numerical prefix ARG, go up to this level and then take that tree.
  6760. If ARG is negative, go up that many levels.
  6761. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6762. indirect buffer previously made with this command, to avoid proliferation of
  6763. indirect buffers. However, when you call the command with a \
  6764. \\[universal-argument] prefix, or
  6765. when `org-indirect-buffer-display' is `new-frame', the last buffer
  6766. is kept so that you can work with several indirect buffers at the same time.
  6767. If `org-indirect-buffer-display' is `dedicated-frame', the \
  6768. \\[universal-argument] prefix also
  6769. requests that a new frame be made for the new buffer, so that the dedicated
  6770. frame is not changed."
  6771. (interactive "P")
  6772. (let ((cbuf (current-buffer))
  6773. (cwin (selected-window))
  6774. (pos (point))
  6775. beg end level heading ibuf)
  6776. (save-excursion
  6777. (org-back-to-heading t)
  6778. (when (numberp arg)
  6779. (setq level (org-outline-level))
  6780. (when (< arg 0) (setq arg (+ level arg)))
  6781. (while (> (setq level (org-outline-level)) arg)
  6782. (org-up-heading-safe)))
  6783. (setq beg (point)
  6784. heading (org-get-heading 'no-tags))
  6785. (org-end-of-subtree t t)
  6786. (when (org-at-heading-p) (backward-char 1))
  6787. (setq end (point)))
  6788. (when (and (buffer-live-p org-last-indirect-buffer)
  6789. (not (eq org-indirect-buffer-display 'new-frame))
  6790. (not arg))
  6791. (kill-buffer org-last-indirect-buffer))
  6792. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6793. org-last-indirect-buffer ibuf)
  6794. (cond
  6795. ((or (eq org-indirect-buffer-display 'new-frame)
  6796. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6797. (select-frame (make-frame))
  6798. (delete-other-windows)
  6799. (pop-to-buffer-same-window ibuf)
  6800. (org-set-frame-title heading))
  6801. ((eq org-indirect-buffer-display 'dedicated-frame)
  6802. (raise-frame
  6803. (select-frame (or (and org-indirect-dedicated-frame
  6804. (frame-live-p org-indirect-dedicated-frame)
  6805. org-indirect-dedicated-frame)
  6806. (setq org-indirect-dedicated-frame (make-frame)))))
  6807. (delete-other-windows)
  6808. (pop-to-buffer-same-window ibuf)
  6809. (org-set-frame-title (concat "Indirect: " heading)))
  6810. ((eq org-indirect-buffer-display 'current-window)
  6811. (pop-to-buffer-same-window ibuf))
  6812. ((eq org-indirect-buffer-display 'other-window)
  6813. (pop-to-buffer ibuf))
  6814. (t (error "Invalid value")))
  6815. (narrow-to-region beg end)
  6816. (outline-show-all)
  6817. (goto-char pos)
  6818. (run-hook-with-args 'org-cycle-hook 'all)
  6819. (and (window-live-p cwin) (select-window cwin))))
  6820. (defun org-get-indirect-buffer (&optional buffer heading)
  6821. (setq buffer (or buffer (current-buffer)))
  6822. (let ((n 1) (base (buffer-name buffer)) bname)
  6823. (while (buffer-live-p
  6824. (get-buffer
  6825. (setq bname
  6826. (concat base "-"
  6827. (if heading (concat heading "-" (number-to-string n))
  6828. (number-to-string n))))))
  6829. (setq n (1+ n)))
  6830. (condition-case nil
  6831. (make-indirect-buffer buffer bname 'clone)
  6832. (error (make-indirect-buffer buffer bname)))))
  6833. (defun org-set-frame-title (title)
  6834. "Set the title of the current frame to the string TITLE."
  6835. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6836. ;;;; Structure editing
  6837. ;;; Inserting headlines
  6838. (defun org--line-empty-p (n)
  6839. "Is the Nth next line empty?
  6840. Counts the current line as N = 1 and the previous line as N = 0;
  6841. see `beginning-of-line'."
  6842. (save-excursion
  6843. (and (not (bobp))
  6844. (or (beginning-of-line n) t)
  6845. (save-match-data
  6846. (looking-at "[ \t]*$")))))
  6847. (defun org-previous-line-empty-p ()
  6848. "Is the previous line a blank line?
  6849. When NEXT is non-nil, check the next line instead."
  6850. (org--line-empty-p 0))
  6851. (defun org-next-line-empty-p ()
  6852. "Is the previous line a blank line?
  6853. When NEXT is non-nil, check the next line instead."
  6854. (org--line-empty-p 2))
  6855. (defun org-insert-heading (&optional arg invisible-ok top)
  6856. "Insert a new heading or an item with the same depth at point.
  6857. If point is at the beginning of a heading or a list item, insert
  6858. a new heading or a new item above the current one. If point is
  6859. at the beginning of a normal line, turn the line into a heading.
  6860. If point is in the middle of a headline or a list item, split the
  6861. headline or the item and create a new headline/item with the text
  6862. in the current line after point \(see `org-M-RET-may-split-line'
  6863. on how to modify this behavior).
  6864. With one universal prefix argument, set the user option
  6865. `org-insert-heading-respect-content' to t for the duration of
  6866. the command. This modifies the behavior described above in this
  6867. ways: on list items and at the beginning of normal lines, force
  6868. the insertion of a heading after the current subtree.
  6869. With two universal prefix arguments, insert the heading at the
  6870. end of the grandparent subtree. For example, if point is within
  6871. a 2nd-level heading, then it will insert a 2nd-level heading at
  6872. the end of the 1st-level parent heading.
  6873. If point is at the beginning of a headline, insert a sibling
  6874. before the current headline. If point is not at the beginning,
  6875. split the line and create a new headline with the text in the
  6876. current line after point \(see `org-M-RET-may-split-line' on how
  6877. to modify this behavior).
  6878. If point is at the beginning of a normal line, turn this line
  6879. into a heading.
  6880. When INVISIBLE-OK is set, stop at invisible headlines when going
  6881. back. This is important for non-interactive uses of the
  6882. command.
  6883. When optional argument TOP is non-nil, insert a level 1 heading,
  6884. unconditionally."
  6885. (interactive "P")
  6886. (let ((itemp (and (not top) (org-in-item-p)))
  6887. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  6888. (respect-content (or org-insert-heading-respect-content
  6889. (equal arg '(4))))
  6890. (initial-content ""))
  6891. (cond
  6892. ((or (= (buffer-size) 0)
  6893. (and (not (save-excursion
  6894. (and (ignore-errors (org-back-to-heading invisible-ok))
  6895. (org-at-heading-p))))
  6896. (or arg (not itemp))))
  6897. ;; At beginning of buffer or so high up that only a heading
  6898. ;; makes sense.
  6899. (cond ((and (bolp) (not respect-content)) (insert "* "))
  6900. ((not respect-content)
  6901. (unless may-split (end-of-line))
  6902. (insert "\n* "))
  6903. ((re-search-forward org-outline-regexp-bol nil t)
  6904. (beginning-of-line)
  6905. (insert "* \n")
  6906. (backward-char))
  6907. (t (goto-char (point-max))
  6908. (insert "\n* ")))
  6909. (run-hooks 'org-insert-heading-hook))
  6910. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  6911. (t
  6912. ;; Maybe move at the end of the subtree
  6913. (when (equal arg '(16))
  6914. (org-up-heading-safe)
  6915. (org-end-of-subtree t))
  6916. ;; Insert a heading
  6917. (save-restriction
  6918. (widen)
  6919. (let* ((level nil)
  6920. (on-heading (org-at-heading-p))
  6921. (empty-line-p (if on-heading
  6922. (org-previous-line-empty-p)
  6923. ;; We will decide later
  6924. nil))
  6925. ;; Get a level string to fall back on.
  6926. (fix-level
  6927. (if (org-before-first-heading-p) "*"
  6928. (save-excursion
  6929. (org-back-to-heading t)
  6930. (when (org-previous-line-empty-p) (setq empty-line-p t))
  6931. (looking-at org-outline-regexp)
  6932. (make-string (1- (length (match-string 0))) ?*))))
  6933. (stars
  6934. (save-excursion
  6935. (condition-case nil
  6936. (if top "* "
  6937. (org-back-to-heading invisible-ok)
  6938. (when (and (not on-heading)
  6939. (featurep 'org-inlinetask)
  6940. (integerp org-inlinetask-min-level)
  6941. (>= (length (match-string 0))
  6942. org-inlinetask-min-level))
  6943. ;; Find a heading level before the inline
  6944. ;; task.
  6945. (while (and (setq level (org-up-heading-safe))
  6946. (>= level org-inlinetask-min-level)))
  6947. (if (org-at-heading-p)
  6948. (org-back-to-heading invisible-ok)
  6949. (error "This should not happen")))
  6950. (unless (and (save-excursion
  6951. (save-match-data
  6952. (org-backward-heading-same-level
  6953. 1 invisible-ok))
  6954. (= (point) (match-beginning 0)))
  6955. (not (org-next-line-empty-p)))
  6956. (setq empty-line-p (or empty-line-p
  6957. (org-previous-line-empty-p))))
  6958. (match-string 0))
  6959. (error (or fix-level "* ")))))
  6960. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  6961. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  6962. ;; If we insert after content, move there and clean up
  6963. ;; whitespace.
  6964. (when (and respect-content
  6965. (not (looking-at-p org-outline-regexp-bol)))
  6966. (if (not (org-before-first-heading-p))
  6967. (org-end-of-subtree nil t)
  6968. (re-search-forward org-outline-regexp-bol)
  6969. (beginning-of-line 0))
  6970. (skip-chars-backward " \r\t\n")
  6971. (and (not (looking-back "^\\*+" (line-beginning-position)))
  6972. (looking-at "[ \t]+") (replace-match ""))
  6973. (unless (eobp) (forward-char 1))
  6974. (when (looking-at "^\\*")
  6975. (unless (bobp) (backward-char 1))
  6976. (insert "\n")))
  6977. ;; If we are splitting, grab the text that should be moved
  6978. ;; to the new headline.
  6979. (when may-split
  6980. (if (org-at-heading-p)
  6981. ;; This is a heading: split intelligently (keeping
  6982. ;; tags).
  6983. (let ((pos (point)))
  6984. (beginning-of-line)
  6985. (unless (looking-at org-complex-heading-regexp)
  6986. (error "This should not happen"))
  6987. (when (and (match-beginning 4)
  6988. (> pos (match-beginning 4))
  6989. (< pos (match-end 4)))
  6990. (setq initial-content (buffer-substring pos (match-end 4)))
  6991. (goto-char pos)
  6992. (delete-region (point) (match-end 4))
  6993. (if (looking-at "[ \t]*$")
  6994. (replace-match "")
  6995. (insert (make-string (length initial-content) ?\s)))
  6996. (setq initial-content (org-trim initial-content)))
  6997. (goto-char pos))
  6998. ;; A normal line.
  6999. (setq initial-content
  7000. (org-trim
  7001. (delete-and-extract-region (point) (line-end-position))))))
  7002. ;; If we are at the beginning of the line, insert before it.
  7003. ;; Otherwise, after it.
  7004. (cond
  7005. ((and (bolp) (looking-at "[ \t]*$")))
  7006. ((bolp) (save-excursion (insert "\n")))
  7007. (t (end-of-line)
  7008. (insert "\n")))
  7009. ;; Insert the new heading
  7010. (insert stars)
  7011. (just-one-space)
  7012. (insert initial-content)
  7013. (unless (and blank (org-previous-line-empty-p))
  7014. (org-N-empty-lines-before-current (if blank 1 0)))
  7015. ;; Adjust visibility, which may be messed up if we removed
  7016. ;; blank lines while previous entry was hidden.
  7017. (let ((bol (line-beginning-position)))
  7018. (dolist (o (overlays-at (1- bol)))
  7019. (when (and (eq (overlay-get o 'invisible) 'outline)
  7020. (eq (overlay-end o) bol))
  7021. (move-overlay o (overlay-start o) (1- bol)))))
  7022. (run-hooks 'org-insert-heading-hook)))))))
  7023. (defun org-N-empty-lines-before-current (N)
  7024. "Make the number of empty lines before current exactly N.
  7025. So this will delete or add empty lines."
  7026. (save-excursion
  7027. (beginning-of-line)
  7028. (let ((p (point)))
  7029. (skip-chars-backward " \r\t\n")
  7030. (unless (bolp) (forward-line))
  7031. (delete-region (point) p))
  7032. (when (> N 0) (insert (make-string N ?\n)))))
  7033. (defun org-get-heading (&optional no-tags no-todo)
  7034. "Return the heading of the current entry, without the stars.
  7035. When NO-TAGS is non-nil, don't include tags.
  7036. When NO-TODO is non-nil, don't include TODO keywords."
  7037. (save-excursion
  7038. (org-back-to-heading t)
  7039. (let ((case-fold-search nil))
  7040. (cond
  7041. ((and no-tags no-todo)
  7042. (looking-at org-complex-heading-regexp)
  7043. (match-string 4))
  7044. (no-tags
  7045. (looking-at (concat org-outline-regexp
  7046. "\\(.*?\\)"
  7047. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7048. (match-string 1))
  7049. (no-todo
  7050. (looking-at org-todo-line-regexp)
  7051. (match-string 3))
  7052. (t (looking-at org-heading-regexp)
  7053. (match-string 2))))))
  7054. (defvar orgstruct-mode) ; defined below
  7055. (defun org-heading-components ()
  7056. "Return the components of the current heading.
  7057. This is a list with the following elements:
  7058. - the level as an integer
  7059. - the reduced level, different if `org-odd-levels-only' is set.
  7060. - the TODO keyword, or nil
  7061. - the priority character, like ?A, or nil if no priority is given
  7062. - the headline text itself, or the tags string if no headline text
  7063. - the tags string, or nil."
  7064. (save-excursion
  7065. (org-back-to-heading t)
  7066. (when (let (case-fold-search)
  7067. (looking-at
  7068. (if orgstruct-mode
  7069. org-heading-regexp
  7070. org-complex-heading-regexp)))
  7071. (if orgstruct-mode
  7072. (list (length (match-string 1))
  7073. (org-reduced-level (length (match-string 1)))
  7074. nil
  7075. nil
  7076. (match-string 2)
  7077. nil)
  7078. (list (length (match-string 1))
  7079. (org-reduced-level (length (match-string 1)))
  7080. (match-string-no-properties 2)
  7081. (and (match-end 3) (aref (match-string 3) 2))
  7082. (match-string-no-properties 4)
  7083. (match-string-no-properties 5))))))
  7084. (defun org-get-entry ()
  7085. "Get the entry text, after heading, entire subtree."
  7086. (save-excursion
  7087. (org-back-to-heading t)
  7088. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7089. (defun org-edit-headline (&optional heading)
  7090. "Edit the current headline.
  7091. Set it to HEADING when provided."
  7092. (interactive)
  7093. (org-with-wide-buffer
  7094. (org-back-to-heading t)
  7095. (when (looking-at org-complex-heading-regexp)
  7096. (let* ((old (match-string-no-properties 4))
  7097. (new (save-match-data
  7098. (org-trim (or heading (read-string "Edit: " old))))))
  7099. (unless (equal old new)
  7100. (if old (replace-match new t t nil 4)
  7101. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7102. (insert " " new))
  7103. (org-set-tags nil t)
  7104. (when (looking-at "[ \t]*$") (replace-match "")))))))
  7105. (defun org-insert-heading-after-current ()
  7106. "Insert a new heading with same level as current, after current subtree."
  7107. (interactive)
  7108. (org-back-to-heading)
  7109. (org-insert-heading)
  7110. (org-move-subtree-down)
  7111. (end-of-line 1))
  7112. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7113. "Insert heading with `org-insert-heading-respect-content' set to t."
  7114. (interactive)
  7115. (org-insert-heading '(4) invisible-ok))
  7116. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7117. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7118. (interactive)
  7119. (org-insert-todo-heading force-state '(4)))
  7120. (defun org-insert-todo-heading (arg &optional force-heading)
  7121. "Insert a new heading with the same level and TODO state as current heading.
  7122. If the heading has no TODO state, or if the state is DONE, use the first
  7123. state (TODO by default). Also with one prefix arg, force first state. With
  7124. two prefix args, force inserting at the end of the parent subtree."
  7125. (interactive "P")
  7126. (when (or force-heading (not (org-insert-item 'checkbox)))
  7127. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7128. force-heading))
  7129. (save-excursion
  7130. (org-back-to-heading)
  7131. (outline-previous-heading)
  7132. (looking-at org-todo-line-regexp))
  7133. (let*
  7134. ((new-mark-x
  7135. (if (or (equal arg '(4))
  7136. (not (match-beginning 2))
  7137. (member (match-string 2) org-done-keywords))
  7138. (car org-todo-keywords-1)
  7139. (match-string 2)))
  7140. (new-mark
  7141. (or
  7142. (run-hook-with-args-until-success
  7143. 'org-todo-get-default-hook new-mark-x nil)
  7144. new-mark-x)))
  7145. (beginning-of-line 1)
  7146. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7147. (if org-treat-insert-todo-heading-as-state-change
  7148. (org-todo new-mark)
  7149. (insert new-mark " "))))
  7150. (when org-provide-todo-statistics
  7151. (org-update-parent-todo-statistics))))
  7152. (defun org-insert-subheading (arg)
  7153. "Insert a new subheading and demote it.
  7154. Works for outline headings and for plain lists alike."
  7155. (interactive "P")
  7156. (org-insert-heading arg)
  7157. (cond
  7158. ((org-at-heading-p) (org-do-demote))
  7159. ((org-at-item-p) (org-indent-item))))
  7160. (defun org-insert-todo-subheading (arg)
  7161. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7162. Works for outline headings and for plain lists alike."
  7163. (interactive "P")
  7164. (org-insert-todo-heading arg)
  7165. (cond
  7166. ((org-at-heading-p) (org-do-demote))
  7167. ((org-at-item-p) (org-indent-item))))
  7168. ;;; Promotion and Demotion
  7169. (defvar org-after-demote-entry-hook nil
  7170. "Hook run after an entry has been demoted.
  7171. The cursor will be at the beginning of the entry.
  7172. When a subtree is being demoted, the hook will be called for each node.")
  7173. (defvar org-after-promote-entry-hook nil
  7174. "Hook run after an entry has been promoted.
  7175. The cursor will be at the beginning of the entry.
  7176. When a subtree is being promoted, the hook will be called for each node.")
  7177. (defun org-promote-subtree ()
  7178. "Promote the entire subtree.
  7179. See also `org-promote'."
  7180. (interactive)
  7181. (save-excursion
  7182. (org-with-limited-levels (org-map-tree 'org-promote)))
  7183. (org-fix-position-after-promote))
  7184. (defun org-demote-subtree ()
  7185. "Demote the entire subtree.
  7186. See `org-demote' and `org-promote'."
  7187. (interactive)
  7188. (save-excursion
  7189. (org-with-limited-levels (org-map-tree 'org-demote)))
  7190. (org-fix-position-after-promote))
  7191. (defun org-do-promote ()
  7192. "Promote the current heading higher up the tree.
  7193. If the region is active in `transient-mark-mode', promote all
  7194. headings in the region."
  7195. (interactive)
  7196. (save-excursion
  7197. (if (org-region-active-p)
  7198. (org-map-region 'org-promote (region-beginning) (region-end))
  7199. (org-promote)))
  7200. (org-fix-position-after-promote))
  7201. (defun org-do-demote ()
  7202. "Demote the current heading lower down the tree.
  7203. If the region is active in `transient-mark-mode', demote all
  7204. headings in the region."
  7205. (interactive)
  7206. (save-excursion
  7207. (if (org-region-active-p)
  7208. (org-map-region 'org-demote (region-beginning) (region-end))
  7209. (org-demote)))
  7210. (org-fix-position-after-promote))
  7211. (defun org-fix-position-after-promote ()
  7212. "Fix cursor position and indentation after demoting/promoting."
  7213. (let ((pos (point)))
  7214. (when (save-excursion
  7215. (beginning-of-line 1)
  7216. (looking-at org-todo-line-regexp)
  7217. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7218. (cond ((eobp) (insert " "))
  7219. ((eolp) (insert " "))
  7220. ((equal (char-after) ?\ ) (forward-char 1))))))
  7221. (defun org-current-level ()
  7222. "Return the level of the current entry, or nil if before the first headline.
  7223. The level is the number of stars at the beginning of the
  7224. headline. Use `org-reduced-level' to remove the effect of
  7225. `org-odd-levels'. Unlike to `org-outline-level', this function
  7226. ignores inlinetasks."
  7227. (let ((level (org-with-limited-levels (org-outline-level))))
  7228. (and (> level 0) level)))
  7229. (defun org-get-previous-line-level ()
  7230. "Return the outline depth of the last headline before the current line.
  7231. Returns 0 for the first headline in the buffer, and nil if before the
  7232. first headline."
  7233. (and (org-current-level)
  7234. (or (and (/= (line-beginning-position) (point-min))
  7235. (save-excursion (beginning-of-line 0) (org-current-level)))
  7236. 0)))
  7237. (defun org-reduced-level (l)
  7238. "Compute the effective level of a heading.
  7239. This takes into account the setting of `org-odd-levels-only'."
  7240. (cond
  7241. ((zerop l) 0)
  7242. (org-odd-levels-only (1+ (floor (/ l 2))))
  7243. (t l)))
  7244. (defun org-level-increment ()
  7245. "Return the number of stars that will be added or removed at a
  7246. time to headlines when structure editing, based on the value of
  7247. `org-odd-levels-only'."
  7248. (if org-odd-levels-only 2 1))
  7249. (defun org-get-valid-level (level &optional change)
  7250. "Rectify a level change under the influence of `org-odd-levels-only'
  7251. LEVEL is a current level, CHANGE is by how much the level should be
  7252. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7253. even level numbers will become the next higher odd number."
  7254. (if org-odd-levels-only
  7255. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7256. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7257. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7258. (max 1 (+ level (or change 0)))))
  7259. (defun org-promote ()
  7260. "Promote the current heading higher up the tree."
  7261. (org-with-wide-buffer
  7262. (org-back-to-heading t)
  7263. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7264. after-change-functions))
  7265. (level (save-match-data (funcall outline-level)))
  7266. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7267. (diff (abs (- level (length up-head) -1))))
  7268. (cond
  7269. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7270. (replace-match "# " nil t))
  7271. ((= level 1)
  7272. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7273. (t (replace-match up-head nil t)))
  7274. (unless (= level 1)
  7275. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7276. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7277. (run-hooks 'org-after-promote-entry-hook))))
  7278. (defun org-demote ()
  7279. "Demote the current heading lower down the tree."
  7280. (org-with-wide-buffer
  7281. (org-back-to-heading t)
  7282. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7283. after-change-functions))
  7284. (level (save-match-data (funcall outline-level)))
  7285. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7286. (diff (abs (- level (length down-head) -1))))
  7287. (replace-match down-head nil t)
  7288. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7289. (when org-adapt-indentation (org-fixup-indentation diff))
  7290. (run-hooks 'org-after-demote-entry-hook))))
  7291. (defun org-cycle-level ()
  7292. "Cycle the level of an empty headline through possible states.
  7293. This goes first to child, then to parent, level, then up the hierarchy.
  7294. After top level, it switches back to sibling level."
  7295. (interactive)
  7296. (let ((org-adapt-indentation nil))
  7297. (when (org-point-at-end-of-empty-headline)
  7298. (setq this-command 'org-cycle-level) ; Only needed for caching
  7299. (let ((cur-level (org-current-level))
  7300. (prev-level (org-get-previous-line-level)))
  7301. (cond
  7302. ;; If first headline in file, promote to top-level.
  7303. ((= prev-level 0)
  7304. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7305. do (org-do-promote)))
  7306. ;; If same level as prev, demote one.
  7307. ((= prev-level cur-level)
  7308. (org-do-demote))
  7309. ;; If parent is top-level, promote to top level if not already.
  7310. ((= prev-level 1)
  7311. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7312. do (org-do-promote)))
  7313. ;; If top-level, return to prev-level.
  7314. ((= cur-level 1)
  7315. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7316. do (org-do-demote)))
  7317. ;; If less than prev-level, promote one.
  7318. ((< cur-level prev-level)
  7319. (org-do-promote))
  7320. ;; If deeper than prev-level, promote until higher than
  7321. ;; prev-level.
  7322. ((> cur-level prev-level)
  7323. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7324. do (org-do-promote))))
  7325. t))))
  7326. (defun org-map-tree (fun)
  7327. "Call FUN for every heading underneath the current one."
  7328. (org-back-to-heading)
  7329. (let ((level (funcall outline-level)))
  7330. (save-excursion
  7331. (funcall fun)
  7332. (while (and (progn
  7333. (outline-next-heading)
  7334. (> (funcall outline-level) level))
  7335. (not (eobp)))
  7336. (funcall fun)))))
  7337. (defun org-map-region (fun beg end)
  7338. "Call FUN for every heading between BEG and END."
  7339. (let ((org-ignore-region t))
  7340. (save-excursion
  7341. (setq end (copy-marker end))
  7342. (goto-char beg)
  7343. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7344. (< (point) end))
  7345. (funcall fun))
  7346. (while (and (progn
  7347. (outline-next-heading)
  7348. (< (point) end))
  7349. (not (eobp)))
  7350. (funcall fun)))))
  7351. (defun org-fixup-indentation (diff)
  7352. "Change the indentation in the current entry by DIFF.
  7353. DIFF is an integer. Indentation is done according to the
  7354. following rules:
  7355. - Planning information and property drawers are always indented
  7356. according to the new level of the headline;
  7357. - Footnote definitions and their contents are ignored;
  7358. - Inlinetasks' boundaries are not shifted;
  7359. - Empty lines are ignored;
  7360. - Other lines' indentation are shifted by DIFF columns, unless
  7361. it would introduce a structural change in the document, in
  7362. which case no shifting is done at all.
  7363. Assume point is at a heading or an inlinetask beginning."
  7364. (org-with-wide-buffer
  7365. (narrow-to-region (line-beginning-position)
  7366. (save-excursion
  7367. (if (org-with-limited-levels (org-at-heading-p))
  7368. (org-with-limited-levels (outline-next-heading))
  7369. (org-inlinetask-goto-end))
  7370. (point)))
  7371. (forward-line)
  7372. ;; Indent properly planning info and property drawer.
  7373. (when (looking-at-p org-planning-line-re)
  7374. (org-indent-line)
  7375. (forward-line))
  7376. (when (looking-at org-property-drawer-re)
  7377. (goto-char (match-end 0))
  7378. (forward-line)
  7379. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7380. (catch 'no-shift
  7381. (when (zerop diff) (throw 'no-shift nil))
  7382. ;; If DIFF is negative, first check if a shift is possible at all
  7383. ;; (e.g., it doesn't break structure). This can only happen if
  7384. ;; some contents are not properly indented.
  7385. (let ((case-fold-search t))
  7386. (when (< diff 0)
  7387. (let ((diff (- diff))
  7388. (forbidden-re (concat org-outline-regexp
  7389. "\\|"
  7390. (substring org-footnote-definition-re 1))))
  7391. (save-excursion
  7392. (while (not (eobp))
  7393. (cond
  7394. ((looking-at-p "[ \t]*$") (forward-line))
  7395. ((and (looking-at-p org-footnote-definition-re)
  7396. (let ((e (org-element-at-point)))
  7397. (and (eq (org-element-type e) 'footnote-definition)
  7398. (goto-char (org-element-property :end e))))))
  7399. ((looking-at-p org-outline-regexp) (forward-line))
  7400. ;; Give up if shifting would move before column 0 or
  7401. ;; if it would introduce a headline or a footnote
  7402. ;; definition.
  7403. (t
  7404. (skip-chars-forward " \t")
  7405. (let ((ind (current-column)))
  7406. (when (or (< ind diff)
  7407. (and (= ind diff) (looking-at-p forbidden-re)))
  7408. (throw 'no-shift nil)))
  7409. ;; Ignore contents of example blocks and source
  7410. ;; blocks if their indentation is meant to be
  7411. ;; preserved. Jump to block's closing line.
  7412. (beginning-of-line)
  7413. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7414. (let ((e (org-element-at-point)))
  7415. (and (memq (org-element-type e)
  7416. '(example-block src-block))
  7417. (or org-src-preserve-indentation
  7418. (org-element-property :preserve-indent e))
  7419. (goto-char (org-element-property :end e))
  7420. (progn (skip-chars-backward " \r\t\n")
  7421. (beginning-of-line)
  7422. t))))
  7423. (forward-line))))))))
  7424. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7425. ;; by DIFF. Also skip contents of source or example blocks
  7426. ;; when indentation is meant to be preserved.
  7427. (while (not (eobp))
  7428. (cond
  7429. ((and (looking-at-p org-footnote-definition-re)
  7430. (let ((e (org-element-at-point)))
  7431. (and (eq (org-element-type e) 'footnote-definition)
  7432. (goto-char (org-element-property :end e))))))
  7433. ((looking-at-p org-outline-regexp) (forward-line))
  7434. ((looking-at-p "[ \t]*$") (forward-line))
  7435. (t
  7436. (indent-line-to (+ (org-get-indentation) diff))
  7437. (beginning-of-line)
  7438. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7439. (let ((e (org-element-at-point)))
  7440. (and (memq (org-element-type e)
  7441. '(example-block src-block))
  7442. (or org-src-preserve-indentation
  7443. (org-element-property :preserve-indent e))
  7444. (goto-char (org-element-property :end e))
  7445. (progn (skip-chars-backward " \r\t\n")
  7446. (beginning-of-line)
  7447. t))))
  7448. (forward-line)))))))))
  7449. (defun org-convert-to-odd-levels ()
  7450. "Convert an org-mode file with all levels allowed to one with odd levels.
  7451. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7452. level 5 etc."
  7453. (interactive)
  7454. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7455. (let ((outline-level 'org-outline-level)
  7456. (org-odd-levels-only nil) n)
  7457. (save-excursion
  7458. (goto-char (point-min))
  7459. (while (re-search-forward "^\\*\\*+ " nil t)
  7460. (setq n (- (length (match-string 0)) 2))
  7461. (while (>= (setq n (1- n)) 0)
  7462. (org-demote))
  7463. (end-of-line 1))))))
  7464. (defun org-convert-to-oddeven-levels ()
  7465. "Convert an org-mode file with only odd levels to one with odd/even levels.
  7466. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7467. file contains a section with an even level, conversion would
  7468. destroy the structure of the file. An error is signaled in this
  7469. case."
  7470. (interactive)
  7471. (goto-char (point-min))
  7472. ;; First check if there are no even levels
  7473. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7474. (org-show-set-visibility 'canonical)
  7475. (error "Not all levels are odd in this file. Conversion not possible"))
  7476. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7477. (let ((outline-regexp org-outline-regexp)
  7478. (outline-level 'org-outline-level)
  7479. (org-odd-levels-only nil) n)
  7480. (save-excursion
  7481. (goto-char (point-min))
  7482. (while (re-search-forward "^\\*\\*+ " nil t)
  7483. (setq n (/ (1- (length (match-string 0))) 2))
  7484. (while (>= (setq n (1- n)) 0)
  7485. (org-promote))
  7486. (end-of-line 1))))))
  7487. (defun org-tr-level (n)
  7488. "Make N odd if required."
  7489. (if org-odd-levels-only (1+ (/ n 2)) n))
  7490. ;;; Vertical tree motion, cutting and pasting of subtrees
  7491. (defun org-move-subtree-up (&optional arg)
  7492. "Move the current subtree up past ARG headlines of the same level."
  7493. (interactive "p")
  7494. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7495. (defun org-move-subtree-down (&optional arg)
  7496. "Move the current subtree down past ARG headlines of the same level."
  7497. (interactive "p")
  7498. (setq arg (prefix-numeric-value arg))
  7499. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7500. 'org-get-last-sibling))
  7501. (ins-point (make-marker))
  7502. (cnt (abs arg))
  7503. (col (current-column))
  7504. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7505. ;; Select the tree
  7506. (org-back-to-heading)
  7507. (setq beg0 (point))
  7508. (save-excursion
  7509. (setq ne-beg (org-back-over-empty-lines))
  7510. (setq beg (point)))
  7511. (save-match-data
  7512. (save-excursion (outline-end-of-heading)
  7513. (setq folded (outline-invisible-p)))
  7514. (progn (org-end-of-subtree nil t)
  7515. (unless (eobp) (backward-char))))
  7516. (outline-next-heading)
  7517. (setq ne-end (org-back-over-empty-lines))
  7518. (setq end (point))
  7519. (goto-char beg0)
  7520. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7521. ;; include less whitespace
  7522. (save-excursion
  7523. (goto-char beg)
  7524. (forward-line (- ne-beg ne-end))
  7525. (setq beg (point))))
  7526. ;; Find insertion point, with error handling
  7527. (while (> cnt 0)
  7528. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7529. (progn (goto-char beg0)
  7530. (user-error "Cannot move past superior level or buffer limit")))
  7531. (setq cnt (1- cnt)))
  7532. (when (> arg 0)
  7533. ;; Moving forward - still need to move over subtree
  7534. (org-end-of-subtree t t)
  7535. (save-excursion
  7536. (org-back-over-empty-lines)
  7537. (or (bolp) (newline))))
  7538. (setq ne-ins (org-back-over-empty-lines))
  7539. (move-marker ins-point (point))
  7540. (setq txt (buffer-substring beg end))
  7541. (org-save-markers-in-region beg end)
  7542. (delete-region beg end)
  7543. (org-remove-empty-overlays-at beg)
  7544. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7545. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7546. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7547. (let ((bbb (point)))
  7548. (insert-before-markers txt)
  7549. (org-reinstall-markers-in-region bbb)
  7550. (move-marker ins-point bbb))
  7551. (or (bolp) (insert "\n"))
  7552. (setq ins-end (point))
  7553. (goto-char ins-point)
  7554. (org-skip-whitespace)
  7555. (when (and (< arg 0)
  7556. (org-first-sibling-p)
  7557. (> ne-ins ne-beg))
  7558. ;; Move whitespace back to beginning
  7559. (save-excursion
  7560. (goto-char ins-end)
  7561. (let ((kill-whole-line t))
  7562. (kill-line (- ne-ins ne-beg)) (point)))
  7563. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7564. (move-marker ins-point nil)
  7565. (if folded
  7566. (outline-hide-subtree)
  7567. (org-show-entry)
  7568. (org-show-children)
  7569. (org-cycle-hide-drawers 'children))
  7570. (org-clean-visibility-after-subtree-move)
  7571. ;; move back to the initial column we were at
  7572. (move-to-column col)))
  7573. (defvar org-subtree-clip ""
  7574. "Clipboard for cut and paste of subtrees.
  7575. This is actually only a copy of the kill, because we use the normal kill
  7576. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7577. (defvar org-subtree-clip-folded nil
  7578. "Was the last copied subtree folded?
  7579. This is used to fold the tree back after pasting.")
  7580. (defun org-cut-subtree (&optional n)
  7581. "Cut the current subtree into the clipboard.
  7582. With prefix arg N, cut this many sequential subtrees.
  7583. This is a short-hand for marking the subtree and then cutting it."
  7584. (interactive "p")
  7585. (org-copy-subtree n 'cut))
  7586. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7587. "Copy the current subtree it in the clipboard.
  7588. With prefix arg N, copy this many sequential subtrees.
  7589. This is a short-hand for marking the subtree and then copying it.
  7590. If CUT is non-nil, actually cut the subtree.
  7591. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7592. of some markers in the region, even if CUT is non-nil. This is
  7593. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7594. (interactive "p")
  7595. (let (beg end folded (beg0 (point)))
  7596. (if (called-interactively-p 'any)
  7597. (org-back-to-heading nil) ; take what looks like a subtree
  7598. (org-back-to-heading t)) ; take what is really there
  7599. (setq beg (point))
  7600. (skip-chars-forward " \t\r\n")
  7601. (save-match-data
  7602. (if nosubtrees
  7603. (outline-next-heading)
  7604. (save-excursion (outline-end-of-heading)
  7605. (setq folded (outline-invisible-p)))
  7606. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7607. (org-end-of-subtree t t)))
  7608. ;; Include the end of an inlinetask
  7609. (when (and (featurep 'org-inlinetask)
  7610. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7611. "END[ \t]*$")))
  7612. (end-of-line))
  7613. (setq end (point))
  7614. (goto-char beg0)
  7615. (when (> end beg)
  7616. (setq org-subtree-clip-folded folded)
  7617. (when (or cut force-store-markers)
  7618. (org-save-markers-in-region beg end))
  7619. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7620. (setq org-subtree-clip (current-kill 0))
  7621. (message "%s: Subtree(s) with %d characters"
  7622. (if cut "Cut" "Copied")
  7623. (length org-subtree-clip)))))
  7624. (defun org-paste-subtree (&optional level tree for-yank remove)
  7625. "Paste the clipboard as a subtree, with modification of headline level.
  7626. The entire subtree is promoted or demoted in order to match a new headline
  7627. level.
  7628. If the cursor is at the beginning of a headline, the same level as
  7629. that headline is used to paste the tree.
  7630. If not, the new level is derived from the *visible* headings
  7631. before and after the insertion point, and taken to be the inferior headline
  7632. level of the two. So if the previous visible heading is level 3 and the
  7633. next is level 4 (or vice versa), level 4 will be used for insertion.
  7634. This makes sure that the subtree remains an independent subtree and does
  7635. not swallow low level entries.
  7636. You can also force a different level, either by using a numeric prefix
  7637. argument, or by inserting the heading marker by hand. For example, if the
  7638. cursor is after \"*****\", then the tree will be shifted to level 5.
  7639. If optional TREE is given, use this text instead of the kill ring.
  7640. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7641. move back over whitespace before inserting, and move point to the end of
  7642. the inserted text when done.
  7643. When REMOVE is non-nil, remove the subtree from the clipboard."
  7644. (interactive "P")
  7645. (setq tree (or tree (and kill-ring (current-kill 0))))
  7646. (unless (org-kill-is-subtree-p tree)
  7647. (user-error "%s"
  7648. (substitute-command-keys
  7649. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7650. (org-with-limited-levels
  7651. (let* ((visp (not (outline-invisible-p)))
  7652. (txt tree)
  7653. (^re_ "\\(\\*+\\)[ \t]*")
  7654. (old-level (if (string-match org-outline-regexp-bol txt)
  7655. (- (match-end 0) (match-beginning 0) 1)
  7656. -1))
  7657. (force-level (cond (level (prefix-numeric-value level))
  7658. ((and (looking-at "[ \t]*$")
  7659. (string-match
  7660. "^\\*+$" (buffer-substring
  7661. (point-at-bol) (point))))
  7662. (- (match-end 0) (match-beginning 0)))
  7663. ((and (bolp)
  7664. (looking-at org-outline-regexp))
  7665. (- (match-end 0) (point) 1))))
  7666. (previous-level (save-excursion
  7667. (condition-case nil
  7668. (progn
  7669. (outline-previous-visible-heading 1)
  7670. (if (looking-at ^re_)
  7671. (- (match-end 0) (match-beginning 0) 1)
  7672. 1))
  7673. (error 1))))
  7674. (next-level (save-excursion
  7675. (condition-case nil
  7676. (progn
  7677. (or (looking-at org-outline-regexp)
  7678. (outline-next-visible-heading 1))
  7679. (if (looking-at ^re_)
  7680. (- (match-end 0) (match-beginning 0) 1)
  7681. 1))
  7682. (error 1))))
  7683. (new-level (or force-level (max previous-level next-level)))
  7684. (shift (if (or (= old-level -1)
  7685. (= new-level -1)
  7686. (= old-level new-level))
  7687. 0
  7688. (- new-level old-level)))
  7689. (delta (if (> shift 0) -1 1))
  7690. (func (if (> shift 0) 'org-demote 'org-promote))
  7691. (org-odd-levels-only nil)
  7692. beg end newend)
  7693. ;; Remove the forced level indicator
  7694. (when force-level
  7695. (delete-region (point-at-bol) (point)))
  7696. ;; Paste
  7697. (beginning-of-line (if (bolp) 1 2))
  7698. (setq beg (point))
  7699. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7700. (insert-before-markers txt)
  7701. (unless (string-match "\n\\'" txt) (insert "\n"))
  7702. (setq newend (point))
  7703. (org-reinstall-markers-in-region beg)
  7704. (setq end (point))
  7705. (goto-char beg)
  7706. (skip-chars-forward " \t\n\r")
  7707. (setq beg (point))
  7708. (when (and (outline-invisible-p) visp)
  7709. (save-excursion (outline-show-heading)))
  7710. ;; Shift if necessary
  7711. (unless (= shift 0)
  7712. (save-restriction
  7713. (narrow-to-region beg end)
  7714. (while (not (= shift 0))
  7715. (org-map-region func (point-min) (point-max))
  7716. (setq shift (+ delta shift)))
  7717. (goto-char (point-min))
  7718. (setq newend (point-max))))
  7719. (when (or (called-interactively-p 'interactive) for-yank)
  7720. (message "Clipboard pasted as level %d subtree" new-level))
  7721. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7722. kill-ring
  7723. (eq org-subtree-clip (current-kill 0))
  7724. org-subtree-clip-folded)
  7725. ;; The tree was folded before it was killed/copied
  7726. (outline-hide-subtree))
  7727. (and for-yank (goto-char newend))
  7728. (and remove (setq kill-ring (cdr kill-ring))))))
  7729. (defun org-kill-is-subtree-p (&optional txt)
  7730. "Check if the current kill is an outline subtree, or a set of trees.
  7731. Returns nil if kill does not start with a headline, or if the first
  7732. headline level is not the largest headline level in the tree.
  7733. So this will actually accept several entries of equal levels as well,
  7734. which is OK for `org-paste-subtree'.
  7735. If optional TXT is given, check this string instead of the current kill."
  7736. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7737. (re (org-get-limited-outline-regexp))
  7738. (^re (concat "^" re))
  7739. (start-level (and kill
  7740. (string-match
  7741. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7742. kill)
  7743. (- (match-end 2) (match-beginning 2) 1)))
  7744. (start (1+ (or (match-beginning 2) -1))))
  7745. (if (not start-level)
  7746. (progn
  7747. nil) ;; does not even start with a heading
  7748. (catch 'exit
  7749. (while (setq start (string-match ^re kill (1+ start)))
  7750. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7751. (throw 'exit nil)))
  7752. t))))
  7753. (defvar org-markers-to-move nil
  7754. "Markers that should be moved with a cut-and-paste operation.
  7755. Those markers are stored together with their positions relative to
  7756. the start of the region.")
  7757. (defun org-save-markers-in-region (beg end)
  7758. "Check markers in region.
  7759. If these markers are between BEG and END, record their position relative
  7760. to BEG, so that after moving the block of text, we can put the markers back
  7761. into place.
  7762. This function gets called just before an entry or tree gets cut from the
  7763. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7764. called immediately, to move the markers with the entries."
  7765. (setq org-markers-to-move nil)
  7766. (when (featurep 'org-clock)
  7767. (org-clock-save-markers-for-cut-and-paste beg end))
  7768. (when (featurep 'org-agenda)
  7769. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7770. (defun org-check-and-save-marker (marker beg end)
  7771. "Check if MARKER is between BEG and END.
  7772. If yes, remember the marker and the distance to BEG."
  7773. (when (and (marker-buffer marker)
  7774. (equal (marker-buffer marker) (current-buffer))
  7775. (>= marker beg) (< marker end))
  7776. (push (cons marker (- marker beg)) org-markers-to-move)))
  7777. (defun org-reinstall-markers-in-region (beg)
  7778. "Move all remembered markers to their position relative to BEG."
  7779. (dolist (x org-markers-to-move)
  7780. (move-marker (car x) (+ beg (cdr x))))
  7781. (setq org-markers-to-move nil))
  7782. (defun org-narrow-to-subtree ()
  7783. "Narrow buffer to the current subtree."
  7784. (interactive)
  7785. (save-excursion
  7786. (save-match-data
  7787. (org-with-limited-levels
  7788. (narrow-to-region
  7789. (progn (org-back-to-heading t) (point))
  7790. (progn (org-end-of-subtree t t)
  7791. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7792. (point)))))))
  7793. (defun org-narrow-to-block ()
  7794. "Narrow buffer to the current block."
  7795. (interactive)
  7796. (let* ((case-fold-search t)
  7797. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7798. "^[ \t]*#\\+end_.*")))
  7799. (if blockp
  7800. (narrow-to-region (car blockp) (cdr blockp))
  7801. (user-error "Not in a block"))))
  7802. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7803. "Clone the task (subtree) at point N times.
  7804. The clones will be inserted as siblings.
  7805. In interactive use, the user will be prompted for the number of
  7806. clones to be produced. If the entry has a timestamp, the user
  7807. will also be prompted for a time shift, which may be a repeater
  7808. as used in time stamps, for example `+3d'. To disable this,
  7809. you can call the function with a universal prefix argument.
  7810. When a valid repeater is given and the entry contains any time
  7811. stamps, the clones will become a sequence in time, with time
  7812. stamps in the subtree shifted for each clone produced. If SHIFT
  7813. is nil or the empty string, time stamps will be left alone. The
  7814. ID property of the original subtree is removed.
  7815. If the original subtree did contain time stamps with a repeater,
  7816. the following will happen:
  7817. - the repeater will be removed in each clone
  7818. - an additional clone will be produced, with the current, unshifted
  7819. date(s) in the entry.
  7820. - the original entry will be placed *after* all the clones, with
  7821. repeater intact.
  7822. - the start days in the repeater in the original entry will be shifted
  7823. to past the last clone.
  7824. In this way you can spell out a number of instances of a repeating task,
  7825. and still retain the repeater to cover future instances of the task.
  7826. As described above, N+1 clones are produced when the original
  7827. subtree has a repeater. Setting N to 0, then, can be used to
  7828. remove the repeater from a subtree and create a shifted clone
  7829. with the original repeater."
  7830. (interactive "nNumber of clones to produce: ")
  7831. (let ((shift
  7832. (or shift
  7833. (if (and (not (equal current-prefix-arg '(4)))
  7834. (save-excursion
  7835. (re-search-forward org-ts-regexp-both
  7836. (save-excursion
  7837. (org-end-of-subtree t)
  7838. (point)) t)))
  7839. (read-from-minibuffer
  7840. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7841. ""))) ;; No time shift
  7842. (n-no-remove -1)
  7843. (drawer-re org-drawer-regexp)
  7844. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7845. beg end template task idprop
  7846. shift-n shift-what doshift nmin nmax)
  7847. (unless (wholenump n)
  7848. (user-error "Invalid number of replications %s" n))
  7849. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7850. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7851. shift)))
  7852. (user-error "Invalid shift specification %s" shift))
  7853. (when doshift
  7854. (setq shift-n (string-to-number (match-string 1 shift))
  7855. shift-what (cdr (assoc (match-string 2 shift)
  7856. '(("d" . day) ("w" . week)
  7857. ("m" . month) ("y" . year))))))
  7858. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  7859. (setq nmin 1 nmax n)
  7860. (org-back-to-heading t)
  7861. (setq beg (point))
  7862. (setq idprop (org-entry-get nil "ID"))
  7863. (org-end-of-subtree t t)
  7864. (or (bolp) (insert "\n"))
  7865. (setq end (point))
  7866. (setq template (buffer-substring beg end))
  7867. (when (and doshift
  7868. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  7869. (delete-region beg end)
  7870. (setq end beg)
  7871. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  7872. (goto-char end)
  7873. (cl-loop for n from nmin to nmax do
  7874. ;; prepare clone
  7875. (with-temp-buffer
  7876. (insert template)
  7877. (org-mode)
  7878. (goto-char (point-min))
  7879. (org-show-subtree)
  7880. (and idprop (if org-clone-delete-id
  7881. (org-entry-delete nil "ID")
  7882. (org-id-get-create t)))
  7883. (unless (= n 0)
  7884. (while (re-search-forward org-clock-re nil t)
  7885. (kill-whole-line))
  7886. (goto-char (point-min))
  7887. (while (re-search-forward drawer-re nil t)
  7888. (org-remove-empty-drawer-at (point))))
  7889. (goto-char (point-min))
  7890. (when doshift
  7891. (while (re-search-forward org-ts-regexp-both nil t)
  7892. (org-timestamp-change (* n shift-n) shift-what))
  7893. (unless (= n n-no-remove)
  7894. (goto-char (point-min))
  7895. (while (re-search-forward org-ts-regexp nil t)
  7896. (save-excursion
  7897. (goto-char (match-beginning 0))
  7898. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7899. (delete-region (match-beginning 1) (match-end 1)))))))
  7900. (setq task (buffer-string)))
  7901. (insert task))
  7902. (goto-char beg)))
  7903. ;;; Outline Sorting
  7904. (defun org-sort (with-case)
  7905. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7906. Optional argument WITH-CASE means sort case-sensitively."
  7907. (interactive "P")
  7908. (cond
  7909. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7910. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7911. (t
  7912. (org-call-with-arg 'org-sort-entries with-case))))
  7913. (defun org-sort-remove-invisible (s)
  7914. "Remove invisible links from string S."
  7915. (remove-text-properties 0 (length s) org-rm-props s)
  7916. (while (string-match org-bracket-link-regexp s)
  7917. (setq s (replace-match (if (match-end 2)
  7918. (match-string 3 s)
  7919. (match-string 1 s))
  7920. t t s)))
  7921. (let ((st (format " %s " s)))
  7922. (while (string-match org-emph-re st)
  7923. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  7924. (setq s (substring st 1 -1)))
  7925. s)
  7926. (defvar org-priority-regexp) ; defined later in the file
  7927. (defvar org-after-sorting-entries-or-items-hook nil
  7928. "Hook that is run after a bunch of entries or items have been sorted.
  7929. When children are sorted, the cursor is in the parent line when this
  7930. hook gets called. When a region or a plain list is sorted, the cursor
  7931. will be in the first entry of the sorted region/list.")
  7932. (defun org-sort-entries
  7933. (&optional with-case sorting-type getkey-func compare-func property)
  7934. "Sort entries on a certain level of an outline tree.
  7935. If there is an active region, the entries in the region are sorted.
  7936. Else, if the cursor is before the first entry, sort the top-level items.
  7937. Else, the children of the entry at point are sorted.
  7938. Sorting can be alphabetically, numerically, by date/time as given by
  7939. a time stamp, by a property, by priority order, or by a custom function.
  7940. The command prompts for the sorting type unless it has been given to the
  7941. function through the SORTING-TYPE argument, which needs to be a character,
  7942. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7943. the precise meaning of each character:
  7944. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7945. c By creation time, which is assumed to be the first inactive time stamp
  7946. at the beginning of a line.
  7947. d By deadline date/time.
  7948. k By clocking time.
  7949. n Numerically, by converting the beginning of the entry/item to a number.
  7950. o By order of TODO keywords.
  7951. p By priority according to the cookie.
  7952. r By the value of a property.
  7953. s By scheduled date/time.
  7954. t By date/time, either the first active time stamp in the entry, or, if
  7955. none exist, by the first inactive one.
  7956. Capital letters will reverse the sort order.
  7957. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7958. called with point at the beginning of the record. It must return either
  7959. a string or a number that should serve as the sorting key for that record.
  7960. Comparing entries ignores case by default. However, with an optional argument
  7961. WITH-CASE, the sorting considers case as well.
  7962. Sorting is done against the visible part of the headlines, it ignores hidden
  7963. links.
  7964. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  7965. (interactive "P")
  7966. (let ((case-func (if with-case 'identity 'downcase))
  7967. (cmstr
  7968. ;; The clock marker is lost when using `sort-subr', let's
  7969. ;; store the clocking string.
  7970. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7971. (save-excursion
  7972. (goto-char org-clock-marker)
  7973. (buffer-substring-no-properties (line-beginning-position)
  7974. (point)))))
  7975. start beg end stars re re2
  7976. txt what tmp)
  7977. ;; Find beginning and end of region to sort
  7978. (cond
  7979. ((org-region-active-p)
  7980. ;; we will sort the region
  7981. (setq end (region-end)
  7982. what "region")
  7983. (goto-char (region-beginning))
  7984. (unless (org-at-heading-p) (outline-next-heading))
  7985. (setq start (point)))
  7986. ((or (org-at-heading-p)
  7987. (ignore-errors (progn (org-back-to-heading) t)))
  7988. ;; we will sort the children of the current headline
  7989. (org-back-to-heading)
  7990. (setq start (point)
  7991. end (progn (org-end-of-subtree t t)
  7992. (or (bolp) (insert "\n"))
  7993. (when (>= (org-back-over-empty-lines) 1)
  7994. (forward-line 1))
  7995. (point))
  7996. what "children")
  7997. (goto-char start)
  7998. (outline-show-subtree)
  7999. (outline-next-heading))
  8000. (t
  8001. ;; we will sort the top-level entries in this file
  8002. (goto-char (point-min))
  8003. (or (org-at-heading-p) (outline-next-heading))
  8004. (setq start (point))
  8005. (goto-char (point-max))
  8006. (beginning-of-line 1)
  8007. (when (looking-at ".*?\\S-")
  8008. ;; File ends in a non-white line
  8009. (end-of-line 1)
  8010. (insert "\n"))
  8011. (setq end (point-max))
  8012. (setq what "top-level")
  8013. (goto-char start)
  8014. (outline-show-all)))
  8015. (setq beg (point))
  8016. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8017. (looking-at "\\(\\*+\\)")
  8018. (setq stars (match-string 1)
  8019. re (concat "^" (regexp-quote stars) " +")
  8020. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8021. txt (buffer-substring beg end))
  8022. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8023. (when (and (not (equal stars "*")) (string-match re2 txt))
  8024. (user-error "Region to sort contains a level above the first entry"))
  8025. (unless sorting-type
  8026. (message
  8027. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8028. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8029. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8030. what)
  8031. (setq sorting-type (read-char-exclusive))
  8032. (unless getkey-func
  8033. (and (= (downcase sorting-type) ?f)
  8034. (setq getkey-func
  8035. (completing-read "Sort using function: "
  8036. obarray 'fboundp t nil nil))
  8037. (setq getkey-func (intern getkey-func))))
  8038. (and (= (downcase sorting-type) ?r)
  8039. (not property)
  8040. (setq property
  8041. (completing-read "Property: "
  8042. (mapcar #'list (org-buffer-property-keys t))
  8043. nil t))))
  8044. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8045. (message "Sorting entries...")
  8046. (save-restriction
  8047. (narrow-to-region start end)
  8048. (let ((dcst (downcase sorting-type))
  8049. (case-fold-search nil)
  8050. (now (current-time)))
  8051. (sort-subr
  8052. (/= dcst sorting-type)
  8053. ;; This function moves to the beginning character of the "record" to
  8054. ;; be sorted.
  8055. (lambda nil
  8056. (if (re-search-forward re nil t)
  8057. (goto-char (match-beginning 0))
  8058. (goto-char (point-max))))
  8059. ;; This function moves to the last character of the "record" being
  8060. ;; sorted.
  8061. (lambda nil
  8062. (save-match-data
  8063. (condition-case nil
  8064. (outline-forward-same-level 1)
  8065. (error
  8066. (goto-char (point-max))))))
  8067. ;; This function returns the value that gets sorted against.
  8068. (lambda nil
  8069. (cond
  8070. ((= dcst ?n)
  8071. (if (looking-at org-complex-heading-regexp)
  8072. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8073. nil))
  8074. ((= dcst ?a)
  8075. (if (looking-at org-complex-heading-regexp)
  8076. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8077. nil))
  8078. ((= dcst ?k)
  8079. (or (get-text-property (point) :org-clock-minutes) 0))
  8080. ((= dcst ?t)
  8081. (let ((end (save-excursion (outline-next-heading) (point))))
  8082. (if (or (re-search-forward org-ts-regexp end t)
  8083. (re-search-forward org-ts-regexp-both end t))
  8084. (org-time-string-to-seconds (match-string 0))
  8085. (float-time now))))
  8086. ((= dcst ?c)
  8087. (let ((end (save-excursion (outline-next-heading) (point))))
  8088. (if (re-search-forward
  8089. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8090. end t)
  8091. (org-time-string-to-seconds (match-string 0))
  8092. (float-time now))))
  8093. ((= dcst ?s)
  8094. (let ((end (save-excursion (outline-next-heading) (point))))
  8095. (if (re-search-forward org-scheduled-time-regexp end t)
  8096. (org-time-string-to-seconds (match-string 1))
  8097. (float-time now))))
  8098. ((= dcst ?d)
  8099. (let ((end (save-excursion (outline-next-heading) (point))))
  8100. (if (re-search-forward org-deadline-time-regexp end t)
  8101. (org-time-string-to-seconds (match-string 1))
  8102. (float-time now))))
  8103. ((= dcst ?p)
  8104. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8105. (string-to-char (match-string 2))
  8106. org-default-priority))
  8107. ((= dcst ?r)
  8108. (or (org-entry-get nil property) ""))
  8109. ((= dcst ?o)
  8110. (when (looking-at org-complex-heading-regexp)
  8111. (let* ((m (match-string 2))
  8112. (s (if (member m org-done-keywords) '- '+)))
  8113. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8114. ((= dcst ?f)
  8115. (if getkey-func
  8116. (progn
  8117. (setq tmp (funcall getkey-func))
  8118. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8119. tmp)
  8120. (error "Invalid key function `%s'" getkey-func)))
  8121. (t (error "Invalid sorting type `%c'" sorting-type))))
  8122. nil
  8123. (cond
  8124. ((= dcst ?a) 'string<)
  8125. ((= dcst ?f) compare-func)
  8126. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8127. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8128. ;; Reset the clock marker if needed
  8129. (when cmstr
  8130. (save-excursion
  8131. (goto-char start)
  8132. (search-forward cmstr nil t)
  8133. (move-marker org-clock-marker (point))))
  8134. (message "Sorting entries...done")))
  8135. ;;; The orgstruct minor mode
  8136. ;; Define a minor mode which can be used in other modes in order to
  8137. ;; integrate the org-mode structure editing commands.
  8138. ;; This is really a hack, because the org-mode structure commands use
  8139. ;; keys which normally belong to the major mode. Here is how it
  8140. ;; works: The minor mode defines all the keys necessary to operate the
  8141. ;; structure commands, but wraps the commands into a function which
  8142. ;; tests if the cursor is currently at a headline or a plain list
  8143. ;; item. If that is the case, the structure command is used,
  8144. ;; temporarily setting many Org-mode variables like regular
  8145. ;; expressions for filling etc. However, when any of those keys is
  8146. ;; used at a different location, function uses `key-binding' to look
  8147. ;; up if the key has an associated command in another currently active
  8148. ;; keymap (minor modes, major mode, global), and executes that
  8149. ;; command. There might be problems if any of the keys is otherwise
  8150. ;; used as a prefix key.
  8151. (defcustom orgstruct-heading-prefix-regexp ""
  8152. "Regexp that matches the custom prefix of Org headlines in
  8153. orgstruct(++)-mode."
  8154. :group 'org
  8155. :version "24.4"
  8156. :package-version '(Org . "8.3")
  8157. :type 'regexp)
  8158. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8159. (defcustom orgstruct-setup-hook nil
  8160. "Hook run after orgstruct-mode-map is filled."
  8161. :group 'org
  8162. :version "24.4"
  8163. :package-version '(Org . "8.0")
  8164. :type 'hook)
  8165. (defvar orgstruct-initialized nil)
  8166. (defvar org-local-vars nil
  8167. "List of local variables, for use by `orgstruct-mode'.")
  8168. ;;;###autoload
  8169. (define-minor-mode orgstruct-mode
  8170. "Toggle the minor mode `orgstruct-mode'.
  8171. This mode is for using Org-mode structure commands in other
  8172. modes. The following keys behave as if Org-mode were active, if
  8173. the cursor is on a headline, or on a plain list item (both as
  8174. defined by Org-mode)."
  8175. nil " OrgStruct" (make-sparse-keymap)
  8176. (funcall (if orgstruct-mode
  8177. 'add-to-invisibility-spec
  8178. 'remove-from-invisibility-spec)
  8179. '(outline . t))
  8180. (when orgstruct-mode
  8181. (org-load-modules-maybe)
  8182. (unless orgstruct-initialized
  8183. (orgstruct-setup)
  8184. (setq orgstruct-initialized t))))
  8185. ;;;###autoload
  8186. (defun turn-on-orgstruct ()
  8187. "Unconditionally turn on `orgstruct-mode'."
  8188. (orgstruct-mode 1))
  8189. (defvar-local orgstruct-is-++ nil
  8190. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8191. (defvar-local org-fb-vars nil)
  8192. (defun orgstruct++-mode (&optional arg)
  8193. "Toggle `orgstruct-mode', the enhanced version of it.
  8194. In addition to setting orgstruct-mode, this also exports all
  8195. indentation and autofilling variables from org-mode into the
  8196. buffer. It will also recognize item context in multiline items."
  8197. (interactive "P")
  8198. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8199. (if (< arg 1)
  8200. (progn (orgstruct-mode -1)
  8201. (dolist (v org-fb-vars)
  8202. (set (make-local-variable (car v))
  8203. (if (eq (car-safe (cadr v)) 'quote)
  8204. (cl-cadadr v)
  8205. (nth 1 v)))))
  8206. (orgstruct-mode 1)
  8207. (setq org-fb-vars nil)
  8208. (unless org-local-vars
  8209. (setq org-local-vars (org-get-local-variables)))
  8210. (let (var val)
  8211. (dolist (x org-local-vars)
  8212. (when (string-match
  8213. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8214. \\|fill-prefix\\|indent-\\)"
  8215. (symbol-name (car x)))
  8216. (setq var (car x) val (nth 1 x))
  8217. (push (list var `(quote ,(eval var))) org-fb-vars)
  8218. (set (make-local-variable var)
  8219. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8220. (setq-local orgstruct-is-++ t))))
  8221. ;;;###autoload
  8222. (defun turn-on-orgstruct++ ()
  8223. "Unconditionally turn on `orgstruct++-mode'."
  8224. (orgstruct++-mode 1))
  8225. (defun orgstruct-error ()
  8226. "Error when there is no default binding for a structure key."
  8227. (interactive)
  8228. (funcall (if (fboundp 'user-error)
  8229. 'user-error
  8230. 'error)
  8231. "This key has no function outside structure elements"))
  8232. (defun orgstruct-setup ()
  8233. "Setup orgstruct keymap."
  8234. (dolist (cell '((org-demote . t)
  8235. (org-metaleft . t)
  8236. (org-metaright . t)
  8237. (org-promote . t)
  8238. (org-shiftmetaleft . t)
  8239. (org-shiftmetaright . t)
  8240. org-backward-element
  8241. org-backward-heading-same-level
  8242. org-ctrl-c-ret
  8243. org-ctrl-c-minus
  8244. org-ctrl-c-star
  8245. org-cycle
  8246. org-force-cycle-archived
  8247. org-forward-heading-same-level
  8248. org-insert-heading
  8249. org-insert-heading-respect-content
  8250. org-kill-note-or-show-branches
  8251. org-mark-subtree
  8252. org-meta-return
  8253. org-metadown
  8254. org-metaup
  8255. org-narrow-to-subtree
  8256. org-promote-subtree
  8257. org-reveal
  8258. org-shiftdown
  8259. org-shiftleft
  8260. org-shiftmetadown
  8261. org-shiftmetaup
  8262. org-shiftright
  8263. org-shifttab
  8264. org-shifttab
  8265. org-shiftup
  8266. org-show-children
  8267. org-show-subtree
  8268. org-sort
  8269. org-up-element
  8270. outline-demote
  8271. outline-next-visible-heading
  8272. outline-previous-visible-heading
  8273. outline-promote
  8274. outline-up-heading))
  8275. (let ((f (or (car-safe cell) cell))
  8276. (disable-when-heading-prefix (cdr-safe cell)))
  8277. (when (fboundp f)
  8278. (let ((new-bindings))
  8279. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8280. (where-is-internal f outline-mode-map)))
  8281. (push binding new-bindings)
  8282. ;; TODO use local-function-key-map
  8283. (dolist (rep '(("<tab>" . "TAB")
  8284. ("<return>" . "RET")
  8285. ("<escape>" . "ESC")
  8286. ("<delete>" . "DEL")))
  8287. (setq binding (read-kbd-macro
  8288. (let ((case-fold-search))
  8289. (replace-regexp-in-string
  8290. (regexp-quote (cdr rep))
  8291. (car rep)
  8292. (key-description binding)))))
  8293. (cl-pushnew binding new-bindings :test 'equal)))
  8294. (dolist (binding new-bindings)
  8295. (let ((key (lookup-key orgstruct-mode-map binding)))
  8296. (when (or (not key) (numberp key))
  8297. (ignore-errors
  8298. (org-defkey orgstruct-mode-map
  8299. binding
  8300. (orgstruct-make-binding
  8301. f binding disable-when-heading-prefix))))))))))
  8302. (run-hooks 'orgstruct-setup-hook))
  8303. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8304. "Create a function for binding in the structure minor mode.
  8305. FUN is the command to call inside a table. KEY is the key that
  8306. should be checked in for a command to execute outside of tables.
  8307. Non-nil `disable-when-heading-prefix' means to disable the command
  8308. if `orgstruct-heading-prefix-regexp' is not empty."
  8309. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8310. (let ((nname name)
  8311. (i 0))
  8312. (while (fboundp (intern nname))
  8313. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8314. (setq name (intern nname)))
  8315. (eval
  8316. (let ((bindings '((org-heading-regexp
  8317. (concat "^"
  8318. orgstruct-heading-prefix-regexp
  8319. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8320. (org-outline-regexp
  8321. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8322. (org-outline-regexp-bol
  8323. (concat "^" org-outline-regexp))
  8324. (outline-regexp org-outline-regexp)
  8325. (outline-heading-end-regexp "\n")
  8326. (outline-level 'org-outline-level)
  8327. (outline-heading-alist))))
  8328. `(defun ,name (arg)
  8329. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8330. "Outside of structure, run the binding of `"
  8331. (key-description key) "'."
  8332. (when disable-when-heading-prefix
  8333. (concat
  8334. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8335. "back to the default binding due to limitations of Org's implementation of\n"
  8336. "`" (symbol-name fun) "'.")))
  8337. (interactive "p")
  8338. (let* ((disable
  8339. ,(and disable-when-heading-prefix
  8340. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8341. (fallback
  8342. (or disable
  8343. (not
  8344. (let* ,bindings
  8345. (org-context-p 'headline 'item
  8346. ,(when (memq fun
  8347. '(org-insert-heading
  8348. org-insert-heading-respect-content
  8349. org-meta-return))
  8350. '(when orgstruct-is-++
  8351. 'item-body))))))))
  8352. (if fallback
  8353. (let* ((orgstruct-mode)
  8354. (binding
  8355. (let ((key ,key))
  8356. (catch 'exit
  8357. (dolist
  8358. (rep
  8359. '(nil
  8360. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8361. ("<\\([^>]*\\)return>" . "\\1RET")
  8362. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8363. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8364. nil)
  8365. (when rep
  8366. (setq key (read-kbd-macro
  8367. (let ((case-fold-search))
  8368. (replace-regexp-in-string
  8369. (car rep)
  8370. (cdr rep)
  8371. (key-description key))))))
  8372. (when (key-binding key)
  8373. (throw 'exit (key-binding key))))))))
  8374. (if (keymapp binding)
  8375. (org-set-transient-map binding)
  8376. (let ((func (or binding
  8377. (unless disable
  8378. 'orgstruct-error))))
  8379. (when func
  8380. (call-interactively func)))))
  8381. (org-run-like-in-org-mode
  8382. (lambda ()
  8383. (interactive)
  8384. (let* ,bindings
  8385. (call-interactively ',fun)))))))))
  8386. name))
  8387. (defun org-contextualize-keys (alist contexts)
  8388. "Return valid elements in ALIST depending on CONTEXTS.
  8389. `org-agenda-custom-commands' or `org-capture-templates' are the
  8390. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8391. or `org-capture-templates-contexts' are the associated contexts
  8392. definitions."
  8393. (let ((contexts
  8394. ;; normalize contexts
  8395. (mapcar
  8396. (lambda(c) (cond ((listp (cadr c))
  8397. (list (car c) (car c) (nth 1 c)))
  8398. ((string= "" (cadr c))
  8399. (list (car c) (car c) (nth 2 c)))
  8400. (t c)))
  8401. contexts))
  8402. (a alist) r s)
  8403. ;; loop over all commands or templates
  8404. (dolist (c a)
  8405. (let (vrules repl)
  8406. (cond
  8407. ((not (assoc (car c) contexts))
  8408. (push c r))
  8409. ((and (assoc (car c) contexts)
  8410. (setq vrules (org-contextualize-validate-key
  8411. (car c) contexts)))
  8412. (mapc (lambda (vr)
  8413. (unless (equal (car vr) (cadr vr))
  8414. (setq repl vr)))
  8415. vrules)
  8416. (if (not repl) (push c r)
  8417. (push (cadr repl) s)
  8418. (push
  8419. (cons (car c)
  8420. (cdr (or (assoc (cadr repl) alist)
  8421. (error "Undefined key `%s' as contextual replacement for `%s'"
  8422. (cadr repl) (car c)))))
  8423. r))))))
  8424. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8425. (delq
  8426. nil
  8427. (delete-dups
  8428. (mapcar (lambda (x)
  8429. (let ((tpl (car x)))
  8430. (unless (delq
  8431. nil
  8432. (mapcar (lambda (y)
  8433. (equal y tpl))
  8434. s))
  8435. x)))
  8436. (reverse r))))))
  8437. (defun org-contextualize-validate-key (key contexts)
  8438. "Check CONTEXTS for agenda or capture KEY."
  8439. (let (res)
  8440. (dolist (r contexts)
  8441. (dolist (rr (car (last r)))
  8442. (when
  8443. (and (equal key (car r))
  8444. (if (functionp rr) (funcall rr)
  8445. (or (and (eq (car rr) 'in-file)
  8446. (buffer-file-name)
  8447. (string-match (cdr rr) (buffer-file-name)))
  8448. (and (eq (car rr) 'in-mode)
  8449. (string-match (cdr rr) (symbol-name major-mode)))
  8450. (and (eq (car rr) 'in-buffer)
  8451. (string-match (cdr rr) (buffer-name)))
  8452. (when (and (eq (car rr) 'not-in-file)
  8453. (buffer-file-name))
  8454. (not (string-match (cdr rr) (buffer-file-name))))
  8455. (when (eq (car rr) 'not-in-mode)
  8456. (not (string-match (cdr rr) (symbol-name major-mode))))
  8457. (when (eq (car rr) 'not-in-buffer)
  8458. (not (string-match (cdr rr) (buffer-name)))))))
  8459. (push r res))))
  8460. (delete-dups (delq nil res))))
  8461. (defun org-context-p (&rest contexts)
  8462. "Check if local context is any of CONTEXTS.
  8463. Possible values in the list of contexts are `table', `headline', and `item'."
  8464. (let ((pos (point)))
  8465. (goto-char (point-at-bol))
  8466. (prog1 (or (and (memq 'table contexts)
  8467. (looking-at "[ \t]*|"))
  8468. (and (memq 'headline contexts)
  8469. (looking-at org-outline-regexp))
  8470. (and (memq 'item contexts)
  8471. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8472. (and (memq 'item-body contexts)
  8473. (org-in-item-p)))
  8474. (goto-char pos))))
  8475. (defconst org-unique-local-variables
  8476. '(org-element--cache
  8477. org-element--cache-objects
  8478. org-element--cache-sync-keys
  8479. org-element--cache-sync-requests
  8480. org-element--cache-sync-timer)
  8481. "List of local variables that cannot be transferred to another buffer.")
  8482. (defun org-get-local-variables ()
  8483. "Return a list of all local variables in an Org mode buffer."
  8484. (delq nil
  8485. (mapcar
  8486. (lambda (x)
  8487. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8488. (name (car binding)))
  8489. (and (not (get name 'org-state))
  8490. (not (memq name org-unique-local-variables))
  8491. (string-match-p
  8492. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8493. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8494. (symbol-name name))
  8495. binding)))
  8496. (with-temp-buffer
  8497. (org-mode)
  8498. (buffer-local-variables)))))
  8499. (defun org-clone-local-variables (from-buffer &optional regexp)
  8500. "Clone local variables from FROM-BUFFER.
  8501. Optional argument REGEXP selects variables to clone."
  8502. (dolist (pair (buffer-local-variables from-buffer))
  8503. (let ((name (car pair)))
  8504. (when (and (symbolp name)
  8505. (not (memq name org-unique-local-variables))
  8506. (or (null regexp) (string-match regexp (symbol-name name))))
  8507. (set (make-local-variable name) (cdr pair))))))
  8508. ;;;###autoload
  8509. (defun org-run-like-in-org-mode (cmd)
  8510. "Run a command, pretending that the current buffer is in Org-mode.
  8511. This will temporarily bind local variables that are typically bound in
  8512. Org-mode to the values they have in Org-mode, and then interactively
  8513. call CMD."
  8514. (org-load-modules-maybe)
  8515. (unless org-local-vars
  8516. (setq org-local-vars (org-get-local-variables)))
  8517. (let (binds)
  8518. (dolist (var org-local-vars)
  8519. (when (or (not (boundp (car var)))
  8520. (eq (symbol-value (car var))
  8521. (default-value (car var))))
  8522. (push (list (car var) `(quote ,(cadr var))) binds)))
  8523. (eval `(let ,binds
  8524. (call-interactively (quote ,cmd))))))
  8525. (defun org-get-category (&optional pos force-refresh)
  8526. "Get the category applying to position POS."
  8527. (save-match-data
  8528. (when force-refresh (org-refresh-category-properties))
  8529. (let ((pos (or pos (point))))
  8530. (or (get-text-property pos 'org-category)
  8531. (progn (org-refresh-category-properties)
  8532. (get-text-property pos 'org-category))))))
  8533. ;;; Refresh properties
  8534. (defun org-refresh-properties (dprop tprop)
  8535. "Refresh buffer text properties.
  8536. DPROP is the drawer property and TPROP is either the
  8537. corresponding text property to set, or an alist with each element
  8538. being a text property (as a symbol) and a function to apply to
  8539. the value of the drawer property."
  8540. (let ((case-fold-search t)
  8541. (inhibit-read-only t))
  8542. (org-with-silent-modifications
  8543. (save-excursion
  8544. (save-restriction
  8545. (widen)
  8546. (goto-char (point-min))
  8547. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8548. (org-refresh-property tprop (match-string-no-properties 1))))))))
  8549. (defun org-refresh-property (tprop p)
  8550. "Refresh the buffer text property TPROP from the drawer property P.
  8551. The refresh happens only for the current tree (not subtree)."
  8552. (unless (org-before-first-heading-p)
  8553. (save-excursion
  8554. (org-back-to-heading t)
  8555. (if (symbolp tprop)
  8556. ;; TPROP is a text property symbol
  8557. (put-text-property
  8558. (point) (or (outline-next-heading) (point-max)) tprop p)
  8559. ;; TPROP is an alist with (properties . function) elements
  8560. (dolist (al tprop)
  8561. (save-excursion
  8562. (put-text-property
  8563. (line-beginning-position) (or (outline-next-heading) (point-max))
  8564. (car al)
  8565. (funcall (cdr al) p))))))))
  8566. (defun org-refresh-category-properties ()
  8567. "Refresh category text properties in the buffer."
  8568. (let ((case-fold-search t)
  8569. (inhibit-read-only t)
  8570. (default-category
  8571. (cond ((null org-category)
  8572. (if buffer-file-name
  8573. (file-name-sans-extension
  8574. (file-name-nondirectory buffer-file-name))
  8575. "???"))
  8576. ((symbolp org-category) (symbol-name org-category))
  8577. (t org-category))))
  8578. (org-with-silent-modifications
  8579. (org-with-wide-buffer
  8580. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8581. ;; This is the default category for the buffer. If none is
  8582. ;; found, fall-back to `org-category' or buffer file name.
  8583. (put-text-property
  8584. (point-min) (point-max)
  8585. 'org-category
  8586. (catch 'buffer-category
  8587. (goto-char (point-max))
  8588. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8589. (let ((element (org-element-at-point)))
  8590. (when (eq (org-element-type element) 'keyword)
  8591. (throw 'buffer-category
  8592. (org-element-property :value element)))))
  8593. default-category))
  8594. ;; Set sub-tree specific categories.
  8595. (goto-char (point-min))
  8596. (let ((regexp (org-re-property "CATEGORY")))
  8597. (while (re-search-forward regexp nil t)
  8598. (let ((value (match-string-no-properties 3)))
  8599. (when (org-at-property-p)
  8600. (put-text-property
  8601. (save-excursion (org-back-to-heading t) (point))
  8602. (save-excursion (org-end-of-subtree t t) (point))
  8603. 'org-category
  8604. value)))))))))
  8605. (defun org-refresh-stats-properties ()
  8606. "Refresh stats text properties in the buffer."
  8607. (let (stats)
  8608. (org-with-silent-modifications
  8609. (save-excursion
  8610. (save-restriction
  8611. (widen)
  8612. (goto-char (point-min))
  8613. (while (re-search-forward
  8614. (concat org-outline-regexp-bol ".*"
  8615. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8616. nil t)
  8617. (setq stats (cond ((equal (match-string 3) "0") 0)
  8618. ((match-string 2)
  8619. (/ (* (string-to-number (match-string 2)) 100)
  8620. (string-to-number (match-string 3))))
  8621. (t (string-to-number (match-string 1)))))
  8622. (org-back-to-heading t)
  8623. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8624. 'org-stats stats)))))))
  8625. (defun org-refresh-effort-properties ()
  8626. "Refresh effort properties"
  8627. (org-refresh-properties
  8628. org-effort-property
  8629. '((effort . identity)
  8630. (effort-minutes . org-duration-string-to-minutes))))
  8631. ;;;; Link Stuff
  8632. ;;; Link abbreviations
  8633. (defun org-link-expand-abbrev (link)
  8634. "Apply replacements as defined in `org-link-abbrev-alist'."
  8635. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8636. (let* ((key (match-string 1 link))
  8637. (as (or (assoc key org-link-abbrev-alist-local)
  8638. (assoc key org-link-abbrev-alist)))
  8639. (tag (and (match-end 2) (match-string 3 link)))
  8640. rpl)
  8641. (if (not as)
  8642. link
  8643. (setq rpl (cdr as))
  8644. (cond
  8645. ((symbolp rpl) (funcall rpl tag))
  8646. ((string-match "%(\\([^)]+\\))" rpl)
  8647. (replace-match
  8648. (save-match-data
  8649. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8650. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8651. ((string-match "%h" rpl)
  8652. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8653. (t (concat rpl tag)))))
  8654. link))
  8655. ;;; Storing and inserting links
  8656. (defvar org-insert-link-history nil
  8657. "Minibuffer history for links inserted with `org-insert-link'.")
  8658. (defvar org-stored-links nil
  8659. "Contains the links stored with `org-store-link'.")
  8660. (defvar org-store-link-plist nil
  8661. "Plist with info about the most recently link created with `org-store-link'.")
  8662. (defvar org-link-protocols nil
  8663. "Link protocols added to Org-mode using `org-add-link-type'.")
  8664. (defvar org-store-link-functions nil
  8665. "List of functions that are called to create and store a link.
  8666. Each function will be called in turn until one returns a non-nil
  8667. value. Each function should check if it is responsible for creating
  8668. this link (for example by looking at the major mode).
  8669. If not, it must exit and return nil.
  8670. If yes, it should return a non-nil value after a calling
  8671. `org-store-link-props' with a list of properties and values.
  8672. Special properties are:
  8673. :type The link prefix, like \"http\". This must be given.
  8674. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8675. This is obligatory as well.
  8676. :description Optional default description for the second pair
  8677. of brackets in an Org-mode link. The user can still change
  8678. this when inserting this link into an Org-mode buffer.
  8679. In addition to these, any additional properties can be specified
  8680. and then used in capture templates.")
  8681. (defun org-add-link-type (type &optional follow export)
  8682. "Add TYPE to the list of `org-link-types'.
  8683. Re-compute all regular expressions depending on `org-link-types'
  8684. FOLLOW and EXPORT are two functions.
  8685. FOLLOW should take the link path as the single argument and do whatever
  8686. is necessary to follow the link, for example find a file or display
  8687. a mail message.
  8688. EXPORT should format the link path for export to one of the export formats.
  8689. It should be a function accepting three arguments:
  8690. path the path of the link, the text after the prefix (like \"http:\")
  8691. desc the description of the link, if any
  8692. format the export format, a symbol like `html' or `latex' or `ascii'.
  8693. The function may use the FORMAT information to return different values
  8694. depending on the format. The return value will be put literally into
  8695. the exported file. If the return value is nil, this means Org should
  8696. do what it normally does with links which do not have EXPORT defined.
  8697. Org mode has a built-in default for exporting links. If you are happy with
  8698. this default, there is no need to define an export function for the link
  8699. type. For a simple example of an export function, see `org-bbdb.el'."
  8700. (add-to-list 'org-link-types type t)
  8701. (org-make-link-regexps)
  8702. (org-element-update-syntax)
  8703. (if (assoc type org-link-protocols)
  8704. (setcdr (assoc type org-link-protocols) (list follow export))
  8705. (push (list type follow export) org-link-protocols)))
  8706. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8707. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8708. ;;;###autoload
  8709. (defun org-store-link (arg)
  8710. "\\<org-mode-map>Store an org-link to the current location.
  8711. This link is added to `org-stored-links' and can later be inserted
  8712. into an Org buffer with \\[org-insert-link].
  8713. For some link types, a prefix ARG is interpreted.
  8714. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8715. For file links, ARG negates `org-context-in-file-links'.
  8716. A double prefix ARG force skipping storing functions that are not
  8717. part of Org's core.
  8718. A triple prefix ARG force storing a link for each line in the
  8719. active region."
  8720. (interactive "P")
  8721. (org-load-modules-maybe)
  8722. (if (and (equal arg '(64)) (org-region-active-p))
  8723. (save-excursion
  8724. (let ((end (region-end)))
  8725. (goto-char (region-beginning))
  8726. (set-mark (point))
  8727. (while (< (point-at-eol) end)
  8728. (move-end-of-line 1) (activate-mark)
  8729. (let (current-prefix-arg)
  8730. (call-interactively 'org-store-link))
  8731. (move-beginning-of-line 2)
  8732. (set-mark (point)))))
  8733. (org-with-limited-levels
  8734. (setq org-store-link-plist nil)
  8735. (let (link cpltxt desc description search
  8736. txt custom-id agenda-link sfuns sfunsn)
  8737. (cond
  8738. ;; Store a link using an external link type
  8739. ((and (not (equal arg '(16)))
  8740. (setq sfuns
  8741. (delq
  8742. nil (mapcar (lambda (f)
  8743. (let (fs) (if (funcall f) (push f fs))))
  8744. org-store-link-functions))
  8745. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8746. (or (and (cdr sfuns)
  8747. (funcall (intern
  8748. (completing-read
  8749. "Which function for creating the link? "
  8750. sfunsn nil t (car sfunsn)))))
  8751. (funcall (caar sfuns)))
  8752. (setq link (plist-get org-store-link-plist :link)
  8753. desc (or (plist-get org-store-link-plist
  8754. :description)
  8755. link))))
  8756. ;; Store a link from a source code buffer.
  8757. ((org-src-edit-buffer-p)
  8758. (cond
  8759. ((save-excursion
  8760. (beginning-of-line)
  8761. (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
  8762. "[ \t]*$")))
  8763. (setq link (format "(%s)" (match-string-no-properties 1))))
  8764. ((called-interactively-p 'any)
  8765. (let (label)
  8766. (while (or (not label)
  8767. (org-with-wide-buffer
  8768. (goto-char (point-min))
  8769. (re-search-forward
  8770. (regexp-quote (format org-coderef-label-format label))
  8771. nil t)))
  8772. (when label (message "Label exists already") (sit-for 2))
  8773. (setq label (read-string "Code line label: " label)))
  8774. (end-of-line)
  8775. (setq link (format org-coderef-label-format label))
  8776. (let ((gc (- 79 (length link))))
  8777. (if (< (current-column) gc) (org-move-to-column gc t)
  8778. (insert " ")))
  8779. (insert link)
  8780. (setq link (concat "(" label ")") desc nil)))
  8781. (t (setq link nil))))
  8782. ;; We are in the agenda, link to referenced location
  8783. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8784. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8785. (get-text-property (point) 'org-marker))))
  8786. (when m
  8787. (org-with-point-at m
  8788. (setq agenda-link
  8789. (if (called-interactively-p 'any)
  8790. (call-interactively 'org-store-link)
  8791. (org-store-link nil)))))))
  8792. ((eq major-mode 'calendar-mode)
  8793. (let ((cd (calendar-cursor-to-date)))
  8794. (setq link
  8795. (format-time-string
  8796. (car org-time-stamp-formats)
  8797. (apply 'encode-time
  8798. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8799. nil nil nil))))
  8800. (org-store-link-props :type "calendar" :date cd)))
  8801. ((eq major-mode 'help-mode)
  8802. (setq link (concat "help:" (save-excursion
  8803. (goto-char (point-min))
  8804. (looking-at "^[^ ]+")
  8805. (match-string 0))))
  8806. (org-store-link-props :type "help"))
  8807. ((eq major-mode 'w3-mode)
  8808. (setq cpltxt (if (and (buffer-name)
  8809. (not (string-match "Untitled" (buffer-name))))
  8810. (buffer-name)
  8811. (url-view-url t))
  8812. link (url-view-url t))
  8813. (org-store-link-props :type "w3" :url (url-view-url t)))
  8814. ((eq major-mode 'image-mode)
  8815. (setq cpltxt (concat "file:"
  8816. (abbreviate-file-name buffer-file-name))
  8817. link cpltxt)
  8818. (org-store-link-props :type "image" :file buffer-file-name))
  8819. ;; In dired, store a link to the file of the current line
  8820. ((derived-mode-p 'dired-mode)
  8821. (let ((file (dired-get-filename nil t)))
  8822. (setq file (if file
  8823. (abbreviate-file-name
  8824. (expand-file-name (dired-get-filename nil t)))
  8825. ;; otherwise, no file so use current directory.
  8826. default-directory))
  8827. (setq cpltxt (concat "file:" file)
  8828. link cpltxt)))
  8829. ((setq search (run-hook-with-args-until-success
  8830. 'org-create-file-search-functions))
  8831. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8832. "::" search))
  8833. (setq cpltxt (or description link)))
  8834. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8835. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8836. (cond
  8837. ;; Store a link using the target at point
  8838. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8839. (setq cpltxt
  8840. (concat "file:"
  8841. (abbreviate-file-name
  8842. (buffer-file-name (buffer-base-buffer)))
  8843. "::" (match-string 1))
  8844. link cpltxt))
  8845. ((and (featurep 'org-id)
  8846. (or (eq org-id-link-to-org-use-id t)
  8847. (and (called-interactively-p 'any)
  8848. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8849. (and (eq org-id-link-to-org-use-id
  8850. 'create-if-interactive-and-no-custom-id)
  8851. (not custom-id))))
  8852. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8853. ;; Store a link using the ID at point
  8854. (setq link (condition-case nil
  8855. (prog1 (org-id-store-link)
  8856. (setq desc (or (plist-get org-store-link-plist
  8857. :description)
  8858. "")))
  8859. (error
  8860. ;; Probably before first headline, link only to file
  8861. (concat "file:"
  8862. (abbreviate-file-name
  8863. (buffer-file-name (buffer-base-buffer))))))))
  8864. (t
  8865. ;; Just link to current headline
  8866. (setq cpltxt (concat "file:"
  8867. (abbreviate-file-name
  8868. (buffer-file-name (buffer-base-buffer)))))
  8869. ;; Add a context search string
  8870. (when (org-xor org-context-in-file-links arg)
  8871. (let* ((element (org-element-at-point))
  8872. (name (org-element-property :name element)))
  8873. (setq txt (cond
  8874. ((org-at-heading-p) nil)
  8875. (name)
  8876. ((org-region-active-p)
  8877. (buffer-substring (region-beginning) (region-end)))))
  8878. (when (or (null txt) (string-match "\\S-" txt))
  8879. (setq cpltxt
  8880. (concat cpltxt "::"
  8881. (condition-case nil
  8882. (org-make-org-heading-search-string txt)
  8883. (error "")))
  8884. desc (or name
  8885. (nth 4 (ignore-errors (org-heading-components)))
  8886. "NONE")))))
  8887. (when (string-match "::\\'" cpltxt)
  8888. (setq cpltxt (substring cpltxt 0 -2)))
  8889. (setq link cpltxt))))
  8890. ((buffer-file-name (buffer-base-buffer))
  8891. ;; Just link to this file here.
  8892. (setq cpltxt (concat "file:"
  8893. (abbreviate-file-name
  8894. (buffer-file-name (buffer-base-buffer)))))
  8895. ;; Add a context string.
  8896. (when (org-xor org-context-in-file-links arg)
  8897. (setq txt (if (org-region-active-p)
  8898. (buffer-substring (region-beginning) (region-end))
  8899. (buffer-substring (point-at-bol) (point-at-eol))))
  8900. ;; Only use search option if there is some text.
  8901. (when (string-match "\\S-" txt)
  8902. (setq cpltxt
  8903. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8904. desc "NONE")))
  8905. (setq link cpltxt))
  8906. ((called-interactively-p 'interactive)
  8907. (user-error "No method for storing a link from this buffer"))
  8908. (t (setq link nil)))
  8909. ;; We're done setting link and desc, clean up
  8910. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8911. (setq link (or link cpltxt)
  8912. desc (or desc cpltxt))
  8913. (cond ((not desc))
  8914. ((equal desc "NONE") (setq desc nil))
  8915. (t (setq desc
  8916. (replace-regexp-in-string
  8917. org-bracket-link-analytic-regexp
  8918. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8919. desc))))
  8920. ;; Return the link
  8921. (if (not (and (or (called-interactively-p 'any)
  8922. executing-kbd-macro)
  8923. link))
  8924. (or agenda-link (and link (org-make-link-string link desc)))
  8925. (push (list link desc) org-stored-links)
  8926. (message "Stored: %s" (or desc link))
  8927. (when custom-id
  8928. (setq link (concat "file:" (abbreviate-file-name
  8929. (buffer-file-name)) "::#" custom-id))
  8930. (push (list link desc) org-stored-links))
  8931. (car org-stored-links))))))
  8932. (defun org-store-link-props (&rest plist)
  8933. "Store link properties, extract names, addresses and dates."
  8934. (let ((x (plist-get plist :from)))
  8935. (when x
  8936. (let ((adr (mail-extract-address-components x)))
  8937. (setq plist (plist-put plist :fromname (car adr)))
  8938. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8939. (let ((x (plist-get plist :to)))
  8940. (when x
  8941. (let ((adr (mail-extract-address-components x)))
  8942. (setq plist (plist-put plist :toname (car adr)))
  8943. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8944. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8945. (when x
  8946. (setq plist (plist-put plist :date-timestamp
  8947. (format-time-string
  8948. (org-time-stamp-format t) x)))
  8949. (setq plist (plist-put plist :date-timestamp-inactive
  8950. (format-time-string
  8951. (org-time-stamp-format t t) x)))))
  8952. (let ((from (plist-get plist :from))
  8953. (to (plist-get plist :to)))
  8954. (when (and from to org-from-is-user-regexp)
  8955. (setq plist
  8956. (plist-put plist :fromto
  8957. (if (string-match org-from-is-user-regexp from)
  8958. (concat "to %t")
  8959. (concat "from %f"))))))
  8960. (setq org-store-link-plist plist))
  8961. (defun org-add-link-props (&rest plist)
  8962. "Add these properties to the link property list."
  8963. (let (key value)
  8964. (while plist
  8965. (setq key (pop plist) value (pop plist))
  8966. (setq org-store-link-plist
  8967. (plist-put org-store-link-plist key value)))))
  8968. (defun org-email-link-description (&optional fmt)
  8969. "Return the description part of an email link.
  8970. This takes information from `org-store-link-plist' and formats it
  8971. according to FMT (default from `org-email-link-description-format')."
  8972. (setq fmt (or fmt org-email-link-description-format))
  8973. (let* ((p org-store-link-plist)
  8974. (to (plist-get p :toaddress))
  8975. (from (plist-get p :fromaddress))
  8976. (table
  8977. (list
  8978. (cons "%c" (plist-get p :fromto))
  8979. (cons "%F" (plist-get p :from))
  8980. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8981. (cons "%T" (plist-get p :to))
  8982. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8983. (cons "%s" (plist-get p :subject))
  8984. (cons "%d" (plist-get p :date))
  8985. (cons "%m" (plist-get p :message-id)))))
  8986. (when (string-match "%c" fmt)
  8987. ;; Check if the user wrote this message
  8988. (if (and org-from-is-user-regexp from to
  8989. (save-match-data (string-match org-from-is-user-regexp from)))
  8990. (setq fmt (replace-match "to %t" t t fmt))
  8991. (setq fmt (replace-match "from %f" t t fmt))))
  8992. (org-replace-escapes fmt table)))
  8993. (defun org-make-org-heading-search-string (&optional string)
  8994. "Make search string for the current headline or STRING."
  8995. (let ((s (or string
  8996. (and (derived-mode-p 'org-mode)
  8997. (save-excursion
  8998. (org-back-to-heading t)
  8999. (org-element-property :raw-value (org-element-at-point))))))
  9000. (lines org-context-in-file-links))
  9001. (or string (setq s (concat "*" s))) ; Add * for headlines
  9002. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9003. (when (and string (integerp lines) (> lines 0))
  9004. (let ((slines (org-split-string s "\n")))
  9005. (when (< lines (length slines))
  9006. (setq s (mapconcat
  9007. 'identity
  9008. (reverse (nthcdr (- (length slines) lines)
  9009. (reverse slines))) "\n")))))
  9010. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9011. (defun org-make-link-string (link &optional description)
  9012. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9013. (unless (org-string-nw-p link) (error "Empty link"))
  9014. (let ((uri (cond ((string-match org-link-types-re link)
  9015. (concat (match-string 1 link)
  9016. (org-link-escape (substring link (match-end 1)))))
  9017. ;; For readability, url-encode internal links only
  9018. ;; when absolutely needed (i.e, when they contain
  9019. ;; square brackets). File links however, are
  9020. ;; encoded since, e.g., spaces are significant.
  9021. ((or (file-name-absolute-p link)
  9022. (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
  9023. (org-link-escape link))
  9024. (t link)))
  9025. (description
  9026. (and (org-string-nw-p description)
  9027. ;; Remove brackets from description, as they are fatal.
  9028. (replace-regexp-in-string
  9029. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9030. (org-trim description)))))
  9031. (format "[[%s]%s]"
  9032. uri
  9033. (if description (format "[%s]" description) ""))))
  9034. (defconst org-link-escape-chars
  9035. ;;%20 %5B %5D %25
  9036. '(?\s ?\[ ?\] ?%)
  9037. "List of characters that should be escaped in a link when stored to Org.
  9038. This is the list that is used for internal purposes.")
  9039. (defun org-link-escape (text &optional table merge)
  9040. "Return percent escaped representation of TEXT.
  9041. TEXT is a string with the text to escape.
  9042. Optional argument TABLE is a list with characters that should be
  9043. escaped. When nil, `org-link-escape-chars' is used.
  9044. If optional argument MERGE is set, merge TABLE into
  9045. `org-link-escape-chars'."
  9046. (let ((characters-to-encode
  9047. (cond ((null table) org-link-escape-chars)
  9048. (merge (append org-link-escape-chars table))
  9049. (t table))))
  9050. (mapconcat
  9051. (lambda (c)
  9052. (if (or (memq c characters-to-encode)
  9053. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9054. (mapconcat (lambda (e) (format "%%%.2X" e))
  9055. (or (encode-coding-char c 'utf-8)
  9056. (error "Unable to percent escape character: %c" c))
  9057. "")
  9058. (char-to-string c)))
  9059. text "")))
  9060. (defun org-link-unescape (str)
  9061. "Unhex hexified Unicode parts in string STR.
  9062. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9063. reciprocal of `org-link-escape', which see."
  9064. (if (org-string-nw-p str)
  9065. (replace-regexp-in-string
  9066. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9067. str))
  9068. (defun org-link-unescape-compound (hex)
  9069. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9070. Note: this function also decodes single byte encodings like
  9071. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9072. (save-match-data
  9073. (let* ((bytes (cdr (split-string hex "%")))
  9074. (ret "")
  9075. (eat 0)
  9076. (sum 0))
  9077. (while bytes
  9078. (let* ((val (string-to-number (pop bytes) 16))
  9079. (shift-xor
  9080. (if (= 0 eat)
  9081. (cond
  9082. ((>= val 252) (cons 6 252))
  9083. ((>= val 248) (cons 5 248))
  9084. ((>= val 240) (cons 4 240))
  9085. ((>= val 224) (cons 3 224))
  9086. ((>= val 192) (cons 2 192))
  9087. (t (cons 0 0)))
  9088. (cons 6 128))))
  9089. (when (>= val 192) (setq eat (car shift-xor)))
  9090. (setq val (logxor val (cdr shift-xor)))
  9091. (setq sum (+ (lsh sum (car shift-xor)) val))
  9092. (when (> eat 0) (setq eat (- eat 1)))
  9093. (cond
  9094. ((= 0 eat) ;multi byte
  9095. (setq ret (concat ret (char-to-string sum)))
  9096. (setq sum 0))
  9097. ((not bytes) ; single byte(s)
  9098. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9099. ret)))
  9100. (defun org-link-unescape-single-byte-sequence (hex)
  9101. "Unhexify hex-encoded single byte character sequences."
  9102. (mapconcat (lambda (byte)
  9103. (char-to-string (string-to-number byte 16)))
  9104. (cdr (split-string hex "%")) ""))
  9105. (defun org-xor (a b)
  9106. "Exclusive or."
  9107. (if a (not b) b))
  9108. (defun org-fixup-message-id-for-http (s)
  9109. "Replace special characters in a message id, so it can be used in an http query."
  9110. (when (string-match "%" s)
  9111. (setq s (mapconcat (lambda (c)
  9112. (if (eq c ?%)
  9113. "%25"
  9114. (char-to-string c)))
  9115. s "")))
  9116. (while (string-match "<" s)
  9117. (setq s (replace-match "%3C" t t s)))
  9118. (while (string-match ">" s)
  9119. (setq s (replace-match "%3E" t t s)))
  9120. (while (string-match "@" s)
  9121. (setq s (replace-match "%40" t t s)))
  9122. s)
  9123. (defun org-link-prettify (link)
  9124. "Return a human-readable representation of LINK.
  9125. The car of LINK must be a raw link.
  9126. The cdr of LINK must be either a link description or nil."
  9127. (let ((desc (or (cadr link) "<no description>")))
  9128. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9129. "<" (car link) ">")))
  9130. ;;;###autoload
  9131. (defun org-insert-link-global ()
  9132. "Insert a link like Org-mode does.
  9133. This command can be called in any mode to insert a link in Org-mode syntax."
  9134. (interactive)
  9135. (org-load-modules-maybe)
  9136. (org-run-like-in-org-mode 'org-insert-link))
  9137. (defun org-insert-all-links (arg &optional pre post)
  9138. "Insert all links in `org-stored-links'.
  9139. When a universal prefix, do not delete the links from `org-stored-links'.
  9140. When `ARG' is a number, insert the last N link(s).
  9141. `PRE' and `POST' are optional arguments to define a string to
  9142. prepend or to append."
  9143. (interactive "P")
  9144. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9145. (links (copy-sequence org-stored-links))
  9146. (pr (or pre "- "))
  9147. (po (or post "\n"))
  9148. (cnt 1) l)
  9149. (if (null org-stored-links)
  9150. (message "No link to insert")
  9151. (while (and (or (listp arg) (>= arg cnt))
  9152. (setq l (if (listp arg)
  9153. (pop links)
  9154. (pop org-stored-links))))
  9155. (setq cnt (1+ cnt))
  9156. (insert pr)
  9157. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9158. (insert po)))))
  9159. (defun org-insert-last-stored-link (arg)
  9160. "Insert the last link stored in `org-stored-links'."
  9161. (interactive "p")
  9162. (org-insert-all-links arg "" "\n"))
  9163. (defun org-link-fontify-links-to-this-file ()
  9164. "Fontify links to the current file in `org-stored-links'."
  9165. (let ((f (buffer-file-name)) a b)
  9166. (setq a (mapcar (lambda(l)
  9167. (let ((ll (car l)))
  9168. (when (and (string-match "^file:\\(.+\\)::" ll)
  9169. (equal f (expand-file-name (match-string 1 ll))))
  9170. ll)))
  9171. org-stored-links))
  9172. (when (featurep 'org-id)
  9173. (setq b (mapcar (lambda(l)
  9174. (let ((ll (car l)))
  9175. (when (and (string-match "^id:\\(.+\\)$" ll)
  9176. (equal f (expand-file-name
  9177. (or (org-id-find-id-file
  9178. (match-string 1 ll)) ""))))
  9179. ll)))
  9180. org-stored-links)))
  9181. (mapcar (lambda(l)
  9182. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9183. (delq nil (append a b)))))
  9184. (defvar org--links-history nil)
  9185. (defun org-insert-link (&optional complete-file link-location default-description)
  9186. "Insert a link. At the prompt, enter the link.
  9187. Completion can be used to insert any of the link protocol prefixes like
  9188. http or ftp in use.
  9189. The history can be used to select a link previously stored with
  9190. `org-store-link'. When the empty string is entered (i.e. if you just
  9191. press RET at the prompt), the link defaults to the most recently
  9192. stored link. As SPC triggers completion in the minibuffer, you need to
  9193. use M-SPC or C-q SPC to force the insertion of a space character.
  9194. You will also be prompted for a description, and if one is given, it will
  9195. be displayed in the buffer instead of the link.
  9196. If there is already a link at point, this command will allow you to edit link
  9197. and description parts.
  9198. With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
  9199. be selected using completion. The path to the file will be relative to the
  9200. current directory if the file is in the current directory or a subdirectory.
  9201. Otherwise, the link will be the absolute path as completed in the minibuffer
  9202. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9203. option `org-link-file-path-type'.
  9204. With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
  9205. the current directory or below.
  9206. With three \\[universal-argument] prefixes, negate the meaning of
  9207. `org-keep-stored-link-after-insertion'.
  9208. If `org-make-link-description-function' is non-nil, this function will be
  9209. called with the link target, and the result will be the default
  9210. link description.
  9211. If the LINK-LOCATION parameter is non-nil, this value will be
  9212. used as the link location instead of reading one interactively.
  9213. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9214. be used as the default description."
  9215. (interactive "P")
  9216. (let* ((wcf (current-window-configuration))
  9217. (origbuf (current-buffer))
  9218. (region (when (org-region-active-p)
  9219. (buffer-substring (region-beginning) (region-end))))
  9220. (remove (and region (list (region-beginning) (region-end))))
  9221. (desc region)
  9222. (link link-location)
  9223. (abbrevs org-link-abbrev-alist-local)
  9224. entry all-prefixes auto-desc)
  9225. (cond
  9226. (link-location) ; specified by arg, just use it.
  9227. ((org-in-regexp org-bracket-link-regexp 1)
  9228. ;; We do have a link at point, and we are going to edit it.
  9229. (setq remove (list (match-beginning 0) (match-end 0)))
  9230. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9231. (setq link (read-string "Link: "
  9232. (org-link-unescape
  9233. (match-string-no-properties 1)))))
  9234. ((or (org-in-regexp org-angle-link-re)
  9235. (org-in-regexp org-plain-link-re))
  9236. ;; Convert to bracket link
  9237. (setq remove (list (match-beginning 0) (match-end 0))
  9238. link (read-string "Link: "
  9239. (org-remove-angle-brackets (match-string 0)))))
  9240. ((member complete-file '((4) (16)))
  9241. ;; Completing read for file names.
  9242. (setq link (org-file-complete-link complete-file)))
  9243. (t
  9244. ;; Read link, with completion for stored links.
  9245. (org-link-fontify-links-to-this-file)
  9246. (org-switch-to-buffer-other-window "*Org Links*")
  9247. (with-current-buffer "*Org Links*"
  9248. (erase-buffer)
  9249. (insert "Insert a link.
  9250. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9251. (when org-stored-links
  9252. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9253. (insert (mapconcat 'org-link-prettify
  9254. (reverse org-stored-links) "\n")))
  9255. (goto-char (point-min)))
  9256. (let ((cw (selected-window)))
  9257. (select-window (get-buffer-window "*Org Links*" 'visible))
  9258. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9259. (unless (pos-visible-in-window-p (point-max))
  9260. (org-fit-window-to-buffer))
  9261. (and (window-live-p cw) (select-window cw)))
  9262. (setq all-prefixes (append (mapcar 'car abbrevs)
  9263. (mapcar 'car org-link-abbrev-alist)
  9264. org-link-types))
  9265. (unwind-protect
  9266. ;; Fake a link history, containing the stored links.
  9267. (let ((org--links-history
  9268. (append (mapcar #'car org-stored-links)
  9269. org-insert-link-history)))
  9270. (setq link
  9271. (org-completing-read
  9272. "Link: "
  9273. (append
  9274. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9275. (mapcar #'car org-stored-links))
  9276. nil nil nil
  9277. 'org--links-history
  9278. (caar org-stored-links)))
  9279. (unless (org-string-nw-p link) (user-error "No link selected"))
  9280. (dolist (l org-stored-links)
  9281. (when (equal link (cadr l))
  9282. (setq link (car l))
  9283. (setq auto-desc t)))
  9284. (when (or (member link all-prefixes)
  9285. (and (equal ":" (substring link -1))
  9286. (member (substring link 0 -1) all-prefixes)
  9287. (setq link (substring link 0 -1))))
  9288. (setq link (with-current-buffer origbuf
  9289. (org-link-try-special-completion link)))))
  9290. (set-window-configuration wcf)
  9291. (kill-buffer "*Org Links*"))
  9292. (setq entry (assoc link org-stored-links))
  9293. (or entry (push link org-insert-link-history))
  9294. (setq desc (or desc (nth 1 entry)))))
  9295. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9296. (not org-keep-stored-link-after-insertion))
  9297. (setq org-stored-links (delq (assoc link org-stored-links)
  9298. org-stored-links)))
  9299. (when (and (string-match org-plain-link-re link)
  9300. (not (string-match org-ts-regexp link)))
  9301. ;; URL-like link, normalize the use of angular brackets.
  9302. (setq link (org-remove-angle-brackets link)))
  9303. ;; Check if we are linking to the current file with a search
  9304. ;; option If yes, simplify the link by using only the search
  9305. ;; option.
  9306. (when (and buffer-file-name
  9307. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9308. (let* ((path (match-string 1 link))
  9309. (case-fold-search nil)
  9310. (search (match-string 2 link)))
  9311. (save-match-data
  9312. (when (equal (file-truename buffer-file-name) (file-truename path))
  9313. ;; We are linking to this same file, with a search option
  9314. (setq link search)))))
  9315. ;; Check if we can/should use a relative path. If yes, simplify the link
  9316. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9317. (let* ((type (match-string 1 link))
  9318. (path (match-string 2 link))
  9319. (origpath path)
  9320. (case-fold-search nil))
  9321. (cond
  9322. ((or (eq org-link-file-path-type 'absolute)
  9323. (equal complete-file '(16)))
  9324. (setq path (abbreviate-file-name (expand-file-name path))))
  9325. ((eq org-link-file-path-type 'noabbrev)
  9326. (setq path (expand-file-name path)))
  9327. ((eq org-link-file-path-type 'relative)
  9328. (setq path (file-relative-name path)))
  9329. (t
  9330. (save-match-data
  9331. (if (string-match (concat "^" (regexp-quote
  9332. (expand-file-name
  9333. (file-name-as-directory
  9334. default-directory))))
  9335. (expand-file-name path))
  9336. ;; We are linking a file with relative path name.
  9337. (setq path (substring (expand-file-name path)
  9338. (match-end 0)))
  9339. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9340. (setq link (concat type path))
  9341. (when (equal desc origpath)
  9342. (setq desc path))))
  9343. (if org-make-link-description-function
  9344. (setq desc
  9345. (or (condition-case nil
  9346. (funcall org-make-link-description-function link desc)
  9347. (error (progn (message "Can't get link description from `%s'"
  9348. (symbol-name org-make-link-description-function))
  9349. (sit-for 2) nil)))
  9350. (read-string "Description: " default-description)))
  9351. (if default-description (setq desc default-description)
  9352. (setq desc (or (and auto-desc desc)
  9353. (read-string "Description: " desc)))))
  9354. (unless (string-match "\\S-" desc) (setq desc nil))
  9355. (when remove (apply 'delete-region remove))
  9356. (insert (org-make-link-string link desc))
  9357. ;; Redisplay so as the new link has proper invisible characters.
  9358. (sit-for 0)))
  9359. (defun org-link-try-special-completion (type)
  9360. "If there is completion support for link type TYPE, offer it."
  9361. (let ((fun (intern (concat "org-" type "-complete-link"))))
  9362. (if (functionp fun)
  9363. (funcall fun)
  9364. (read-string "Link (no completion support): " (concat type ":")))))
  9365. (defun org-file-complete-link (&optional arg)
  9366. "Create a file link using completion."
  9367. (let ((file (read-file-name "File: "))
  9368. (pwd (file-name-as-directory (expand-file-name ".")))
  9369. (pwd1 (file-name-as-directory (abbreviate-file-name
  9370. (expand-file-name ".")))))
  9371. (cond ((equal arg '(16))
  9372. (concat "file:"
  9373. (abbreviate-file-name (expand-file-name file))))
  9374. ((string-match
  9375. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9376. (concat "file:" (match-string 1 file)))
  9377. ((string-match
  9378. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9379. (expand-file-name file))
  9380. (concat "file:"
  9381. (match-string 1 (expand-file-name file))))
  9382. (t (concat "file:" file)))))
  9383. (defun org-completing-read (&rest args)
  9384. "Completing-read with SPACE being a normal character."
  9385. (let ((enable-recursive-minibuffers t)
  9386. (minibuffer-local-completion-map
  9387. (copy-keymap minibuffer-local-completion-map)))
  9388. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9389. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9390. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9391. 'org-time-stamp-inactive)
  9392. (apply #'completing-read args)))
  9393. ;;; Opening/following a link
  9394. (defvar org-link-search-failed nil)
  9395. (defvar org-open-link-functions nil
  9396. "Hook for functions finding a plain text link.
  9397. These functions must take a single argument, the link content.
  9398. They will be called for links that look like [[link text][description]]
  9399. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9400. like a filename (e.g. \"./blue.png\").
  9401. These functions will be called *before* Org attempts to resolve the
  9402. link by doing text searches in the current buffer - so if you want a
  9403. link \"[[target]]\" to still find \"<<target>>\", your function should
  9404. handle this as a special case.
  9405. When the function does handle the link, it must return a non-nil value.
  9406. If it decides that it is not responsible for this link, it must return
  9407. nil to indicate that that Org-mode can continue with other options
  9408. like exact and fuzzy text search.")
  9409. (defun org-next-link (&optional search-backward)
  9410. "Move forward to the next link.
  9411. If the link is in hidden text, expose it."
  9412. (interactive "P")
  9413. (when (and org-link-search-failed (eq this-command last-command))
  9414. (goto-char (point-min))
  9415. (message "Link search wrapped back to beginning of buffer"))
  9416. (setq org-link-search-failed nil)
  9417. (let* ((pos (point))
  9418. (ct (org-context))
  9419. (a (assoc :link ct))
  9420. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9421. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9422. ((looking-at org-any-link-re)
  9423. ;; Don't stay stuck at link without an org-link face
  9424. (forward-char (if search-backward -1 1))))
  9425. (if (funcall srch-fun org-any-link-re nil t)
  9426. (progn
  9427. (goto-char (match-beginning 0))
  9428. (when (outline-invisible-p) (org-show-context)))
  9429. (goto-char pos)
  9430. (setq org-link-search-failed t)
  9431. (message "No further link found"))))
  9432. (defun org-previous-link ()
  9433. "Move backward to the previous link.
  9434. If the link is in hidden text, expose it."
  9435. (interactive)
  9436. (funcall 'org-next-link t))
  9437. (defun org-translate-link (s)
  9438. "Translate a link string if a translation function has been defined."
  9439. (with-temp-buffer
  9440. (insert (org-trim s))
  9441. (org-trim (org-element-interpret-data (org-element-context)))))
  9442. (defun org-translate-link-from-planner (type path)
  9443. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9444. This is still an experimental function, your mileage may vary."
  9445. (cond
  9446. ((member type '("http" "https" "news" "ftp"))
  9447. ;; standard Internet links are the same.
  9448. nil)
  9449. ((and (equal type "irc") (string-match "^//" path))
  9450. ;; Planner has two / at the beginning of an irc link, we have 1.
  9451. ;; We should have zero, actually....
  9452. (setq path (substring path 1)))
  9453. ((and (equal type "lisp") (string-match "^/" path))
  9454. ;; Planner has a slash, we do not.
  9455. (setq type "elisp" path (substring path 1)))
  9456. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9457. ;; A typical message link. Planner has the id after the final slash,
  9458. ;; we separate it with a hash mark
  9459. (setq path (concat (match-string 1 path) "#"
  9460. (org-remove-angle-brackets (match-string 2 path))))))
  9461. (cons type path))
  9462. (defun org-find-file-at-mouse (ev)
  9463. "Open file link or URL at mouse."
  9464. (interactive "e")
  9465. (mouse-set-point ev)
  9466. (org-open-at-point 'in-emacs))
  9467. (defun org-open-at-mouse (ev)
  9468. "Open file link or URL at mouse.
  9469. See the docstring of `org-open-file' for details."
  9470. (interactive "e")
  9471. (mouse-set-point ev)
  9472. (when (eq major-mode 'org-agenda-mode)
  9473. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9474. (org-open-at-point))
  9475. (defvar org-window-config-before-follow-link nil
  9476. "The window configuration before following a link.
  9477. This is saved in case the need arises to restore it.")
  9478. ;;;###autoload
  9479. (defun org-open-at-point-global ()
  9480. "Follow a link or time-stamp like Org mode does.
  9481. This command can be called in any mode to follow an external link
  9482. or a time-stamp that has Org mode syntax. Its behavior is
  9483. undefined when called on internal links (e.g., fuzzy links).
  9484. Raise an error when there is nothing to follow. "
  9485. (interactive)
  9486. (cond ((org-in-regexp org-any-link-re)
  9487. (org-open-link-from-string (match-string-no-properties 0)))
  9488. ((or (org-in-regexp org-ts-regexp-both nil t)
  9489. (org-in-regexp org-tsr-regexp-both nil t))
  9490. (org-follow-timestamp-link))
  9491. (t (user-error "No link found"))))
  9492. ;;;###autoload
  9493. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9494. "Open a link in the string S, as if it was in Org-mode."
  9495. (interactive "sLink: \nP")
  9496. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9497. (with-temp-buffer
  9498. (let ((org-inhibit-startup (not reference-buffer)))
  9499. (org-mode)
  9500. (insert s)
  9501. (goto-char (point-min))
  9502. (when reference-buffer
  9503. (setq org-link-abbrev-alist-local
  9504. (with-current-buffer reference-buffer
  9505. org-link-abbrev-alist-local)))
  9506. (org-open-at-point arg reference-buffer)))))
  9507. (defvar org-open-at-point-functions nil
  9508. "Hook that is run when following a link at point.
  9509. Functions in this hook must return t if they identify and follow
  9510. a link at point. If they don't find anything interesting at point,
  9511. they must return nil.")
  9512. (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
  9513. (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
  9514. (defun org-open-at-point (&optional arg reference-buffer)
  9515. "Open link, timestamp, footnote or tags at point.
  9516. When point is on a link, follow it. Normally, files will be
  9517. opened by an appropriate application. If the optional prefix
  9518. argument ARG is non-nil, Emacs will visit the file. With
  9519. a double prefix argument, try to open outside of Emacs, in the
  9520. application the system uses for this file type.
  9521. When point is on a timestamp, open the agenda at the day
  9522. specified.
  9523. When point is a footnote definition, move to the first reference
  9524. found. If it is on a reference, move to the associated
  9525. definition.
  9526. When point is on a headline, display a list of every link in the
  9527. entry, so it is possible to pick one, or all, of them. If point
  9528. is on a tag, call `org-tags-view' instead.
  9529. When optional argument REFERENCE-BUFFER is non-nil, it should
  9530. specify a buffer from where the link search should happen. This
  9531. is used internally by `org-open-link-from-string'.
  9532. On top of syntactically correct links, this function will open
  9533. the link at point in comments or comment blocks and the first
  9534. link in a property drawer line."
  9535. (interactive "P")
  9536. ;; On a code block, open block's results.
  9537. (unless (call-interactively 'org-babel-open-src-block-result)
  9538. (org-load-modules-maybe)
  9539. (setq org-window-config-before-follow-link (current-window-configuration))
  9540. (org-remove-occur-highlights nil nil t)
  9541. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9542. (let* ((context
  9543. ;; Only consider supported types, even if they are not
  9544. ;; the closest one.
  9545. (org-element-lineage
  9546. (org-element-context)
  9547. '(clock comment comment-block footnote-definition
  9548. footnote-reference headline inlinetask keyword link
  9549. node-property timestamp)
  9550. t))
  9551. (type (org-element-type context))
  9552. (value (org-element-property :value context)))
  9553. (cond
  9554. ((not context) (user-error "No link found"))
  9555. ;; Exception: open timestamps and links in properties
  9556. ;; drawers, keywords and comments.
  9557. ((memq type '(comment comment-block keyword node-property))
  9558. (call-interactively #'org-open-at-point-global))
  9559. ;; On a headline or an inlinetask, but not on a timestamp,
  9560. ;; a link, a footnote reference or on tags.
  9561. ((and (memq type '(headline inlinetask))
  9562. ;; Not on tags.
  9563. (progn (save-excursion (beginning-of-line)
  9564. (looking-at org-complex-heading-regexp))
  9565. (or (not (match-beginning 5))
  9566. (< (point) (match-beginning 5)))))
  9567. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9568. (links (car data))
  9569. (links-end (cdr data)))
  9570. (if links
  9571. (dolist (link (if (stringp links) (list links) links))
  9572. (search-forward link nil links-end)
  9573. (goto-char (match-beginning 0))
  9574. (org-open-at-point))
  9575. (require 'org-attach)
  9576. (org-attach-reveal 'if-exists))))
  9577. ;; On a clock line, make sure point is on the timestamp
  9578. ;; before opening it.
  9579. ((and (eq type 'clock)
  9580. value
  9581. (>= (point) (org-element-property :begin value))
  9582. (<= (point) (org-element-property :end value)))
  9583. (org-follow-timestamp-link))
  9584. ;; Do nothing on white spaces after an object.
  9585. ((>= (point)
  9586. (save-excursion
  9587. (goto-char (org-element-property :end context))
  9588. (skip-chars-backward " \t")
  9589. (point)))
  9590. (user-error "No link found"))
  9591. ((eq type 'timestamp) (org-follow-timestamp-link))
  9592. ;; On tags within a headline or an inlinetask.
  9593. ((and (memq type '(headline inlinetask))
  9594. (progn (save-excursion (beginning-of-line)
  9595. (looking-at org-complex-heading-regexp))
  9596. (and (match-beginning 5)
  9597. (>= (point) (match-beginning 5)))))
  9598. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9599. ((eq type 'link)
  9600. ;; When link is located within the description of another
  9601. ;; link (e.g., an inline image), always open the parent
  9602. ;; link.
  9603. (let*((link (let ((up (org-element-property :parent context)))
  9604. (if (eq (org-element-type up) 'link) up context)))
  9605. (type (org-element-property :type link))
  9606. (path (org-link-unescape (org-element-property :path link))))
  9607. ;; Switch back to REFERENCE-BUFFER needed when called in
  9608. ;; a temporary buffer through `org-open-link-from-string'.
  9609. (with-current-buffer (or reference-buffer (current-buffer))
  9610. (cond
  9611. ((equal type "file")
  9612. (if (string-match "[*?{]" (file-name-nondirectory path))
  9613. (dired path)
  9614. ;; Look into `org-link-protocols' in order to find
  9615. ;; a DEDICATED-FUNCTION to open file. The function
  9616. ;; will be applied on raw link instead of parsed
  9617. ;; link due to the limitation in `org-add-link-type'
  9618. ;; ("open" function called with a single argument).
  9619. ;; If no such function is found, fallback to
  9620. ;; `org-open-file'.
  9621. ;;
  9622. ;; Note : "file+emacs" and "file+sys" types are
  9623. ;; hard-coded in order to escape the previous
  9624. ;; limitation.
  9625. (let* ((option (org-element-property :search-option link))
  9626. (app (org-element-property :application link))
  9627. (dedicated-function
  9628. (nth 1 (assoc app org-link-protocols))))
  9629. (if dedicated-function
  9630. (funcall dedicated-function
  9631. (concat path
  9632. (and option (concat "::" option))))
  9633. (apply #'org-open-file
  9634. path
  9635. (cond (arg)
  9636. ((equal app "emacs") 'emacs)
  9637. ((equal app "sys") 'system))
  9638. (cond ((not option) nil)
  9639. ((org-string-match-p "\\`[0-9]+\\'" option)
  9640. (list (string-to-number option)))
  9641. (t (list nil
  9642. (org-link-unescape option)))))))))
  9643. ((assoc type org-link-protocols)
  9644. (funcall (nth 1 (assoc type org-link-protocols)) path))
  9645. ((equal type "help")
  9646. (let ((f-or-v (intern path)))
  9647. (cond ((fboundp f-or-v) (describe-function f-or-v))
  9648. ((boundp f-or-v) (describe-variable f-or-v))
  9649. (t (error "Not a known function or variable")))))
  9650. ((member type '("http" "https" "ftp" "mailto" "news"))
  9651. (browse-url (url-encode-url (concat type ":" path))))
  9652. ((equal type "doi")
  9653. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9654. ((equal type "message") (browse-url (concat type ":" path)))
  9655. ((equal type "shell")
  9656. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9657. (cmd path))
  9658. (if (or (and (org-string-nw-p
  9659. org-confirm-shell-link-not-regexp)
  9660. (string-match
  9661. org-confirm-shell-link-not-regexp cmd))
  9662. (not org-confirm-shell-link-function)
  9663. (funcall org-confirm-shell-link-function
  9664. (format "Execute \"%s\" in shell? "
  9665. (org-add-props cmd nil
  9666. 'face 'org-warning))))
  9667. (progn
  9668. (message "Executing %s" cmd)
  9669. (shell-command cmd buf)
  9670. (when (featurep 'midnight)
  9671. (setq clean-buffer-list-kill-buffer-names
  9672. (cons (buffer-name buf)
  9673. clean-buffer-list-kill-buffer-names))))
  9674. (user-error "Abort"))))
  9675. ((equal type "elisp")
  9676. (let ((cmd path))
  9677. (if (or (and (org-string-nw-p
  9678. org-confirm-elisp-link-not-regexp)
  9679. (org-string-match-p
  9680. org-confirm-elisp-link-not-regexp cmd))
  9681. (not org-confirm-elisp-link-function)
  9682. (funcall org-confirm-elisp-link-function
  9683. (format "Execute \"%s\" as elisp? "
  9684. (org-add-props cmd nil
  9685. 'face 'org-warning))))
  9686. (message "%s => %s" cmd
  9687. (if (eq (string-to-char cmd) ?\()
  9688. (eval (read cmd))
  9689. (call-interactively (read cmd))))
  9690. (user-error "Abort"))))
  9691. ((equal type "id")
  9692. (require 'org-id)
  9693. (funcall (nth 1 (assoc "id" org-link-protocols)) path))
  9694. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9695. (unless (run-hook-with-args-until-success
  9696. 'org-open-link-functions path)
  9697. (if (not arg) (org-mark-ring-push)
  9698. (switch-to-buffer-other-window
  9699. (org-get-buffer-for-internal-link (current-buffer))))
  9700. (let ((destination
  9701. (org-with-wide-buffer
  9702. (if (equal type "radio")
  9703. (org-search-radio-target
  9704. (org-element-property :path link))
  9705. (org-link-search
  9706. (if (member type '("custom-id" "coderef"))
  9707. (org-element-property :raw-link link)
  9708. path)
  9709. ;; Prevent fuzzy links from matching
  9710. ;; themselves.
  9711. (and (equal type "fuzzy")
  9712. (+ 2 (org-element-property :begin link)))))
  9713. (point))))
  9714. (unless (and (<= (point-min) destination)
  9715. (>= (point-max) destination))
  9716. (widen))
  9717. (goto-char destination))))
  9718. (t (browse-url-at-point))))))
  9719. ;; On a footnote reference or at a footnote definition's label.
  9720. ((or (eq type 'footnote-reference)
  9721. (and (eq type 'footnote-definition)
  9722. (save-excursion
  9723. ;; Do not validate action when point is on the
  9724. ;; spaces right after the footnote label, in
  9725. ;; order to be on par with behaviour on links.
  9726. (skip-chars-forward " \t")
  9727. (let ((begin
  9728. (org-element-property :contents-begin context)))
  9729. (if begin (< (point) begin)
  9730. (= (org-element-property :post-affiliated context)
  9731. (line-beginning-position)))))))
  9732. (org-footnote-action))
  9733. (t (user-error "No link found")))))
  9734. (run-hook-with-args 'org-follow-link-hook)))
  9735. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9736. "Offer links in the current entry and return the selected link.
  9737. If there is only one link, return it.
  9738. If NTH is an integer, return the NTH link found.
  9739. If ZERO is a string, check also this string for a link, and if
  9740. there is one, return it."
  9741. (with-current-buffer buffer
  9742. (save-excursion
  9743. (save-restriction
  9744. (widen)
  9745. (goto-char marker)
  9746. (let ((cnt ?0)
  9747. have-zero end links link c)
  9748. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9749. (push (match-string 0 zero) links)
  9750. (setq cnt (1- cnt) have-zero t))
  9751. (save-excursion
  9752. (org-back-to-heading t)
  9753. (setq end (save-excursion (outline-next-heading) (point)))
  9754. (while (re-search-forward org-any-link-re end t)
  9755. (push (match-string 0) links))
  9756. (setq links (org-uniquify (reverse links))))
  9757. (cond
  9758. ((null links)
  9759. (message "No links"))
  9760. ((equal (length links) 1)
  9761. (setq link (car links)))
  9762. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9763. (setq link (nth (if have-zero nth (1- nth)) links)))
  9764. (t ; we have to select a link
  9765. (save-excursion
  9766. (save-window-excursion
  9767. (delete-other-windows)
  9768. (with-output-to-temp-buffer "*Select Link*"
  9769. (dolist (l links)
  9770. (cond
  9771. ((not (string-match org-bracket-link-regexp l))
  9772. (princ (format "[%c] %s\n" (cl-incf cnt)
  9773. (org-remove-angle-brackets l))))
  9774. ((match-end 3)
  9775. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9776. (match-string 3 l) (match-string 1 l))))
  9777. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9778. (match-string 1 l)))))))
  9779. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9780. (message "Select link to open, RET to open all:")
  9781. (setq c (read-char-exclusive))
  9782. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9783. (when (equal c ?q) (user-error "Abort"))
  9784. (if (equal c ?\C-m)
  9785. (setq link links)
  9786. (setq nth (- c ?0))
  9787. (when have-zero (setq nth (1+ nth)))
  9788. (unless (and (integerp nth) (>= (length links) nth))
  9789. (user-error "Invalid link selection"))
  9790. (setq link (nth (1- nth) links)))))
  9791. (cons link end))))))
  9792. ;; TODO: These functions are deprecated since `org-open-at-point'
  9793. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9794. (defun org-open-file-with-system (path)
  9795. "Open file at PATH using the system way of opening it."
  9796. (org-open-file path 'system))
  9797. (defun org-open-file-with-emacs (path)
  9798. "Open file at PATH in Emacs."
  9799. (org-open-file path 'emacs))
  9800. ;;; File search
  9801. (defvar org-create-file-search-functions nil
  9802. "List of functions to construct the right search string for a file link.
  9803. These functions are called in turn with point at the location to
  9804. which the link should point.
  9805. A function in the hook should first test if it would like to
  9806. handle this file type, for example by checking the `major-mode'
  9807. or the file extension. If it decides not to handle this file, it
  9808. should just return nil to give other functions a chance. If it
  9809. does handle the file, it must return the search string to be used
  9810. when following the link. The search string will be part of the
  9811. file link, given after a double colon, and `org-open-at-point'
  9812. will automatically search for it. If special measures must be
  9813. taken to make the search successful, another function should be
  9814. added to the companion hook `org-execute-file-search-functions',
  9815. which see.
  9816. A function in this hook may also use `setq' to set the variable
  9817. `description' to provide a suggestion for the descriptive text to
  9818. be used for this link when it gets inserted into an Org-mode
  9819. buffer with \\[org-insert-link].")
  9820. (defvar org-execute-file-search-functions nil
  9821. "List of functions to execute a file search triggered by a link.
  9822. Functions added to this hook must accept a single argument, the
  9823. search string that was part of the file link, the part after the
  9824. double colon. The function must first check if it would like to
  9825. handle this search, for example by checking the `major-mode' or
  9826. the file extension. If it decides not to handle this search, it
  9827. should just return nil to give other functions a chance. If it
  9828. does handle the search, it must return a non-nil value to keep
  9829. other functions from trying.
  9830. Each function can access the current prefix argument through the
  9831. variable `current-prefix-arg'. Note that a single prefix is used
  9832. to force opening a link in Emacs, so it may be good to only use a
  9833. numeric or double prefix to guide the search function.
  9834. In case this is needed, a function in this hook can also restore
  9835. the window configuration before `org-open-at-point' was called using:
  9836. \(set-window-configuration org-window-config-before-follow-link)")
  9837. (defun org-search-radio-target (target)
  9838. "Search a radio target matching TARGET in current buffer.
  9839. White spaces are not significant."
  9840. (let ((re (format "<<<%s>>>"
  9841. (mapconcat #'regexp-quote
  9842. (org-split-string target "[ \t\n]+")
  9843. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9844. (origin (point)))
  9845. (goto-char (point-min))
  9846. (catch :radio-match
  9847. (while (re-search-forward re nil t)
  9848. (backward-char)
  9849. (let ((object (org-element-context)))
  9850. (when (eq (org-element-type object) 'radio-target)
  9851. (goto-char (org-element-property :begin object))
  9852. (org-show-context 'link-search)
  9853. (throw :radio-match nil))))
  9854. (goto-char origin)
  9855. (user-error "No match for radio target: %s" target))))
  9856. (defun org-link-search (s &optional avoid-pos stealth)
  9857. "Search for a search string S.
  9858. If S starts with \"#\", it triggers a custom ID search.
  9859. If S is enclosed within parenthesis, it initiates a coderef
  9860. search.
  9861. If S is surrounded by forward slashes, it is interpreted as
  9862. a regular expression. In Org mode files, this will create an
  9863. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9864. to list matches. If the current buffer is in `dired-mode', grep
  9865. will be used to search in all files.
  9866. When AVOID-POS is given, ignore matches near that position.
  9867. When optional argument STEALTH is non-nil, do not modify
  9868. visibility around point, thus ignoring `org-show-context-detail'
  9869. variable.
  9870. Search is case-insensitive and ignores white spaces. Return type
  9871. of matched result, with is either `dedicated' or `fuzzy'."
  9872. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9873. (let* ((case-fold-search t)
  9874. (origin (point))
  9875. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9876. (words (org-split-string s "[ \t\n]+"))
  9877. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9878. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9879. type)
  9880. (cond
  9881. ;; Check if there are any special search functions.
  9882. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9883. ((eq (string-to-char s) ?#)
  9884. ;; Look for a custom ID S if S starts with "#".
  9885. (let* ((id (substring normalized 1))
  9886. (match (org-find-property "CUSTOM_ID" id)))
  9887. (if match (progn (goto-char match) (setf type 'dedicated))
  9888. (error "No match for custom ID: %s" id))))
  9889. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9890. ;; Look for coderef targets if S is enclosed within parenthesis.
  9891. (let ((coderef (match-string-no-properties 1 normalized))
  9892. (re (substring s-single-re 1 -1)))
  9893. (goto-char (point-min))
  9894. (catch :coderef-match
  9895. (while (re-search-forward re nil t)
  9896. (let ((element (org-element-at-point)))
  9897. (when (and (memq (org-element-type element)
  9898. '(example-block src-block))
  9899. ;; Build proper regexp according to current
  9900. ;; block's label format.
  9901. (let ((label-fmt
  9902. (regexp-quote
  9903. (or (org-element-property :label-fmt element)
  9904. org-coderef-label-format))))
  9905. (save-excursion
  9906. (beginning-of-line)
  9907. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9908. (format label-fmt coderef))))))
  9909. (setq type 'dedicated)
  9910. (goto-char (match-beginning 1))
  9911. (throw :coderef-match nil))))
  9912. (goto-char origin)
  9913. (error "No match for coderef: %s" coderef))))
  9914. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9915. ;; Look for a regular expression.
  9916. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9917. (match-string 1 s)))
  9918. ;; Fuzzy links.
  9919. (t
  9920. (let ((starred (eq (string-to-char normalized) ?*)))
  9921. (cond
  9922. ;; Look for targets, only if not in a headline search.
  9923. ((and (not starred)
  9924. (let ((target (format "<<%s>>" s-multi-re)))
  9925. (catch :target-match
  9926. (goto-char (point-min))
  9927. (while (re-search-forward target nil t)
  9928. (backward-char)
  9929. (let ((context (org-element-context)))
  9930. (when (eq (org-element-type context) 'target)
  9931. (setq type 'dedicated)
  9932. (goto-char (org-element-property :begin context))
  9933. (throw :target-match t))))
  9934. nil))))
  9935. ;; Look for elements named after S, only if not in a headline
  9936. ;; search.
  9937. ((and (not starred)
  9938. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9939. (catch :name-match
  9940. (goto-char (point-min))
  9941. (while (re-search-forward name nil t)
  9942. (let ((element (org-element-at-point)))
  9943. (when (equal (org-split-string
  9944. (org-element-property :name element)
  9945. "[ \t]+")
  9946. words)
  9947. (setq type 'dedicated)
  9948. (beginning-of-line)
  9949. (throw :name-match t))))
  9950. nil))))
  9951. ;; Regular text search. Prefer headlines in Org mode
  9952. ;; buffers.
  9953. ((and (derived-mode-p 'org-mode)
  9954. (let* ((wspace "[ \t]")
  9955. (wspaceopt (concat wspace "*"))
  9956. (cookie (concat "\\(?:"
  9957. wspaceopt
  9958. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  9959. wspaceopt
  9960. "\\)"))
  9961. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  9962. (re (concat
  9963. org-outline-regexp-bol
  9964. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  9965. "\\(?:\\[#.\\][ \t]+\\)?"
  9966. "\\(?:" org-comment-string "[ \t]+\\)?"
  9967. sep "?"
  9968. (let ((title (mapconcat #'regexp-quote
  9969. words
  9970. sep)))
  9971. (if starred (substring title 1) title))
  9972. sep "?"
  9973. "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
  9974. "[ \t]*$")))
  9975. (goto-char (point-min))
  9976. (re-search-forward re nil t)))
  9977. (goto-char (match-beginning 0))
  9978. (setq type 'dedicated))
  9979. ;; Offer to create non-existent headline depending on
  9980. ;; `org-link-search-must-match-exact-headline'.
  9981. ((and (derived-mode-p 'org-mode)
  9982. (not org-link-search-inhibit-query)
  9983. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9984. (yes-or-no-p "No match - create this as a new heading? "))
  9985. (goto-char (point-max))
  9986. (unless (bolp) (newline))
  9987. (org-insert-heading nil t t)
  9988. (insert s "\n")
  9989. (beginning-of-line 0))
  9990. ;; Only headlines are looked after. No need to process
  9991. ;; further: throw an error.
  9992. ((and (derived-mode-p 'org-mode)
  9993. (or starred org-link-search-must-match-exact-headline))
  9994. (goto-char origin)
  9995. (error "No match for fuzzy expression: %s" normalized))
  9996. ;; Regular text search.
  9997. ((catch :fuzzy-match
  9998. (goto-char (point-min))
  9999. (while (re-search-forward s-multi-re nil t)
  10000. ;; Skip match if it contains AVOID-POS or it is included
  10001. ;; in a link with a description but outside the
  10002. ;; description.
  10003. (unless (or (and avoid-pos
  10004. (<= (match-beginning 0) avoid-pos)
  10005. (> (match-end 0) avoid-pos))
  10006. (and (save-match-data
  10007. (org-in-regexp org-bracket-link-regexp))
  10008. (match-beginning 3)
  10009. (or (> (match-beginning 3) (point))
  10010. (<= (match-end 3) (point)))
  10011. (org-element-lineage
  10012. (save-match-data (org-element-context))
  10013. '(link) t)))
  10014. (goto-char (match-beginning 0))
  10015. (setq type 'fuzzy)
  10016. (throw :fuzzy-match t)))
  10017. nil))
  10018. ;; All failed. Throw an error.
  10019. (t (goto-char origin)
  10020. (error "No match for fuzzy expression: %s" normalized))))))
  10021. ;; Disclose surroundings of match, if appropriate.
  10022. (when (and (derived-mode-p 'org-mode) (not stealth))
  10023. (org-show-context 'link-search))
  10024. type))
  10025. (defun org-get-buffer-for-internal-link (buffer)
  10026. "Return a buffer to be used for displaying the link target of internal links."
  10027. (cond
  10028. ((not org-display-internal-link-with-indirect-buffer)
  10029. buffer)
  10030. ((string-match "(Clone)$" (buffer-name buffer))
  10031. (message "Buffer is already a clone, not making another one")
  10032. ;; we also do not modify visibility in this case
  10033. buffer)
  10034. (t ; make a new indirect buffer for displaying the link
  10035. (let* ((bn (buffer-name buffer))
  10036. (ibn (concat bn "(Clone)"))
  10037. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10038. (with-current-buffer ib (org-overview))
  10039. ib))))
  10040. (defun org-do-occur (regexp &optional cleanup)
  10041. "Call the Emacs command `occur'.
  10042. If CLEANUP is non-nil, remove the printout of the regular expression
  10043. in the *Occur* buffer. This is useful if the regex is long and not useful
  10044. to read."
  10045. (occur regexp)
  10046. (when cleanup
  10047. (let ((cwin (selected-window)) win beg end)
  10048. (when (setq win (get-buffer-window "*Occur*"))
  10049. (select-window win))
  10050. (goto-char (point-min))
  10051. (when (re-search-forward "match[a-z]+" nil t)
  10052. (setq beg (match-end 0))
  10053. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10054. (setq end (1- (match-beginning 0)))))
  10055. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10056. (goto-char (point-min))
  10057. (select-window cwin))))
  10058. ;;; The mark ring for links jumps
  10059. (defvar org-mark-ring nil
  10060. "Mark ring for positions before jumps in Org-mode.")
  10061. (defvar org-mark-ring-last-goto nil
  10062. "Last position in the mark ring used to go back.")
  10063. ;; Fill and close the ring
  10064. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10065. (dotimes (_ org-mark-ring-length)
  10066. (push (make-marker) org-mark-ring))
  10067. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10068. org-mark-ring)
  10069. (defun org-mark-ring-push (&optional pos buffer)
  10070. "Put the current position or POS into the mark ring and rotate it."
  10071. (interactive)
  10072. (setq pos (or pos (point)))
  10073. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10074. (move-marker (car org-mark-ring)
  10075. (or pos (point))
  10076. (or buffer (current-buffer)))
  10077. (message "%s"
  10078. (substitute-command-keys
  10079. "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
  10080. (defun org-mark-ring-goto (&optional n)
  10081. "Jump to the previous position in the mark ring.
  10082. With prefix arg N, jump back that many stored positions. When
  10083. called several times in succession, walk through the entire ring.
  10084. Org-mode commands jumping to a different position in the current file,
  10085. or to another Org-mode file, automatically push the old position
  10086. onto the ring."
  10087. (interactive "p")
  10088. (let (p m)
  10089. (if (eq last-command this-command)
  10090. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10091. (setq p org-mark-ring))
  10092. (setq org-mark-ring-last-goto p)
  10093. (setq m (car p))
  10094. (pop-to-buffer-same-window (marker-buffer m))
  10095. (goto-char m)
  10096. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10097. ;;; TODO: Use string-remove-prefix and -suffix once we only support
  10098. ;;; Emacs 24.4+
  10099. (defun org-remove-angle-brackets (s)
  10100. (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
  10101. (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
  10102. s)
  10103. (defun org-add-angle-brackets (s)
  10104. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10105. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10106. s)
  10107. (defun org-remove-double-quotes (s)
  10108. (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
  10109. (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
  10110. s)
  10111. ;;; Following specific links
  10112. (defvar org-agenda-buffer-tmp-name)
  10113. (defvar org-agenda-start-on-weekday)
  10114. (defun org-follow-timestamp-link ()
  10115. "Open an agenda view for the time-stamp date/range at point."
  10116. (cond
  10117. ((org-at-date-range-p t)
  10118. (let ((org-agenda-start-on-weekday)
  10119. (t1 (match-string 1))
  10120. (t2 (match-string 2)) tt1 tt2)
  10121. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10122. tt2 (time-to-days (org-time-string-to-time t2)))
  10123. (let ((org-agenda-buffer-tmp-name
  10124. (format "*Org Agenda(a:%s)"
  10125. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10126. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10127. ((org-at-timestamp-p t)
  10128. (let ((org-agenda-buffer-tmp-name
  10129. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10130. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10131. (substring (match-string 1) 0 10)))
  10132. 1)))
  10133. (t (error "This should not happen"))))
  10134. ;;; Following file links
  10135. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10136. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10137. (declare-function mailcap-mime-info
  10138. "mailcap" (string &optional request no-decode))
  10139. (defvar org-wait nil)
  10140. (defun org-open-file (path &optional in-emacs line search)
  10141. "Open the file at PATH.
  10142. First, this expands any special file name abbreviations. Then the
  10143. configuration variable `org-file-apps' is checked if it contains an
  10144. entry for this file type, and if yes, the corresponding command is launched.
  10145. If no application is found, Emacs simply visits the file.
  10146. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10147. With a double \\[universal-argument] \\[universal-argument] \
  10148. prefix arg, Org tries to avoid opening in Emacs
  10149. and to use an external application to visit the file.
  10150. Optional LINE specifies a line to go to, optional SEARCH a string
  10151. to search for. If LINE or SEARCH is given, the file will be
  10152. opened in Emacs, unless an entry from org-file-apps that makes
  10153. use of groups in a regexp matches.
  10154. If you want to change the way frames are used when following a
  10155. link, please customize `org-link-frame-setup'.
  10156. If the file does not exist, an error is thrown."
  10157. (let* ((file (if (equal path "")
  10158. buffer-file-name
  10159. (substitute-in-file-name (expand-file-name path))))
  10160. (file-apps (append org-file-apps (org-default-apps)))
  10161. (apps (cl-remove-if
  10162. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10163. (apps-dlink (cl-remove-if-not
  10164. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10165. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10166. (dirp (unless remp (file-directory-p file)))
  10167. (file (if (and dirp org-open-directory-means-index-dot-org)
  10168. (concat (file-name-as-directory file) "index.org")
  10169. file))
  10170. (a-m-a-p (assq 'auto-mode apps))
  10171. (dfile (downcase file))
  10172. ;; Reconstruct the original link from the PATH, LINE and
  10173. ;; SEARCH args.
  10174. (link (cond (line (concat file "::" (number-to-string line)))
  10175. (search (concat file "::" search))
  10176. (t file)))
  10177. (dlink (downcase link))
  10178. (old-buffer (current-buffer))
  10179. (old-pos (point))
  10180. (old-mode major-mode)
  10181. (ext
  10182. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10183. (match-string 1 dfile)))
  10184. cmd link-match-data)
  10185. (cond
  10186. ((member in-emacs '((16) system))
  10187. (setq cmd (cdr (assq 'system apps))))
  10188. (in-emacs (setq cmd 'emacs))
  10189. (t
  10190. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10191. (and dirp (cdr (assq 'directory apps)))
  10192. ;; First, try matching against apps-dlink if we
  10193. ;; get a match here, store the match data for
  10194. ;; later.
  10195. (let ((match (assoc-default dlink apps-dlink
  10196. 'string-match)))
  10197. (if match
  10198. (progn (setq link-match-data (match-data))
  10199. match)
  10200. (progn (setq in-emacs (or in-emacs line search))
  10201. nil))) ; if we have no match in apps-dlink,
  10202. ; always open the file in emacs if line or search
  10203. ; is given (for backwards compatibility)
  10204. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10205. 'string-match)
  10206. (cdr (assoc ext apps))
  10207. (cdr (assq t apps))))))
  10208. (when (eq cmd 'system)
  10209. (setq cmd (cdr (assoc 'system apps))))
  10210. (when (eq cmd 'default)
  10211. (setq cmd (cdr (assoc t apps))))
  10212. (when (eq cmd 'mailcap)
  10213. (require 'mailcap)
  10214. (mailcap-parse-mailcaps)
  10215. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10216. (command (mailcap-mime-info mime-type)))
  10217. (if (stringp command)
  10218. (setq cmd command)
  10219. (setq cmd 'emacs))))
  10220. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10221. (not (file-exists-p file))
  10222. (not org-open-non-existing-files))
  10223. (user-error "No such file: %s" file))
  10224. (cond
  10225. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10226. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10227. (while (string-match "['\"]%s['\"]" cmd)
  10228. (setq cmd (replace-match "%s" t t cmd)))
  10229. (while (string-match "%s" cmd)
  10230. (setq cmd (replace-match
  10231. (save-match-data
  10232. (shell-quote-argument
  10233. (convert-standard-filename file)))
  10234. t t cmd)))
  10235. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10236. (save-match-data
  10237. (let ((match-index 1)
  10238. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10239. (set-match-data link-match-data)
  10240. (while (<= match-index number-of-groups)
  10241. (let ((regex (concat "%" (number-to-string match-index)))
  10242. (replace-with (match-string match-index dlink)))
  10243. (while (string-match regex cmd)
  10244. (setq cmd (replace-match replace-with t t cmd))))
  10245. (setq match-index (+ match-index 1)))))
  10246. (save-window-excursion
  10247. (message "Running %s...done" cmd)
  10248. (start-process-shell-command cmd nil cmd)
  10249. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10250. ((or (stringp cmd)
  10251. (eq cmd 'emacs))
  10252. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10253. (widen)
  10254. (cond (line (org-goto-line line)
  10255. (when (derived-mode-p 'org-mode) (org-reveal)))
  10256. (search (org-link-search search))))
  10257. ((functionp cmd)
  10258. (save-match-data
  10259. (set-match-data link-match-data)
  10260. (condition-case nil
  10261. (funcall cmd file link)
  10262. ;; FIXME: Remove this check when most default installations
  10263. ;; of Emacs have at least Org 9.0.
  10264. ((debug wrong-number-of-arguments wrong-type-argument
  10265. invalid-function)
  10266. (user-error "Please see Org News for version 9.0 about \
  10267. `org-file-apps'--Lisp error: %S" cmd)))))
  10268. ((consp cmd)
  10269. ;; FIXME: Remove this check when most default installations of
  10270. ;; Emacs have at least Org 9.0.
  10271. ;; Heads-up instead of silently fall back to
  10272. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10273. ;; with sexp instead of a function for `cmd'.
  10274. (user-error "Please see Org News for version 9.0 about \
  10275. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10276. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10277. (and (derived-mode-p 'org-mode)
  10278. (eq old-mode 'org-mode)
  10279. (or (not (eq old-buffer (current-buffer)))
  10280. (not (eq old-pos (point))))
  10281. (org-mark-ring-push old-pos old-buffer))))
  10282. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10283. "This function returns non-nil if `entry' uses a regular
  10284. expression which should be matched against the whole link by
  10285. org-open-file.
  10286. It assumes that is the case when the entry uses a regular
  10287. expression which has at least one grouping construct and the
  10288. action is either a lisp form or a command string containing
  10289. `%1', i.e. using at least one subexpression match as a
  10290. parameter."
  10291. (let ((selector (car entry))
  10292. (action (cdr entry)))
  10293. (if (stringp selector)
  10294. (and (> (regexp-opt-depth selector) 0)
  10295. (or (and (stringp action)
  10296. (string-match "%[0-9]" action))
  10297. (consp action)))
  10298. nil)))
  10299. (defun org-default-apps ()
  10300. "Return the default applications for this operating system."
  10301. (cond
  10302. ((eq system-type 'darwin)
  10303. org-file-apps-defaults-macosx)
  10304. ((eq system-type 'windows-nt)
  10305. org-file-apps-defaults-windowsnt)
  10306. (t org-file-apps-defaults-gnu)))
  10307. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10308. "Convert extensions to regular expressions in the cars of LIST.
  10309. Also, weed out any non-string entries, because the return value is used
  10310. only for regexp matching.
  10311. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10312. point to the symbol `emacs', indicating that the file should
  10313. be opened in Emacs."
  10314. (append
  10315. (delq nil
  10316. (mapcar (lambda (x)
  10317. (unless (not (stringp (car x)))
  10318. (if (string-match "\\W" (car x))
  10319. x
  10320. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10321. list))
  10322. (when add-auto-mode
  10323. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10324. (defvar ange-ftp-name-format)
  10325. (defun org-file-remote-p (file)
  10326. "Test whether FILE specifies a location on a remote system.
  10327. Return non-nil if the location is indeed remote.
  10328. For example, the filename \"/user@host:/foo\" specifies a location
  10329. on the system \"/user@host:\"."
  10330. (cond ((fboundp 'file-remote-p)
  10331. (file-remote-p file))
  10332. ((fboundp 'tramp-handle-file-remote-p)
  10333. (tramp-handle-file-remote-p file))
  10334. ((and (boundp 'ange-ftp-name-format)
  10335. (string-match (car ange-ftp-name-format) file))
  10336. t)))
  10337. ;;;; Refiling
  10338. (defun org-get-org-file ()
  10339. "Read a filename, with default directory `org-directory'."
  10340. (let ((default (or org-default-notes-file remember-data-file)))
  10341. (read-file-name (format "File name [%s]: " default)
  10342. (file-name-as-directory org-directory)
  10343. default)))
  10344. (defun org-notes-order-reversed-p ()
  10345. "Check if the current file should receive notes in reversed order."
  10346. (cond
  10347. ((not org-reverse-note-order) nil)
  10348. ((eq t org-reverse-note-order) t)
  10349. ((not (listp org-reverse-note-order)) nil)
  10350. (t (catch 'exit
  10351. (dolist (entry org-reverse-note-order)
  10352. (when (string-match (car entry) buffer-file-name)
  10353. (throw 'exit (cdr entry))))))))
  10354. (defvar org-refile-target-table nil
  10355. "The list of refile targets, created by `org-refile'.")
  10356. (defvar org-agenda-new-buffers nil
  10357. "Buffers created to visit agenda files.")
  10358. (defvar org-refile-cache nil
  10359. "Cache for refile targets.")
  10360. (defvar org-refile-markers nil
  10361. "All the markers used for caching refile locations.")
  10362. (defun org-refile-marker (pos)
  10363. "Get a new refile marker, but only if caching is in use."
  10364. (if (not org-refile-use-cache)
  10365. pos
  10366. (let ((m (make-marker)))
  10367. (move-marker m pos)
  10368. (push m org-refile-markers)
  10369. m)))
  10370. (defun org-refile-cache-clear ()
  10371. "Clear the refile cache and disable all the markers."
  10372. (dolist (m org-refile-markers) (move-marker m nil))
  10373. (setq org-refile-markers nil)
  10374. (setq org-refile-cache nil)
  10375. (message "Refile cache has been cleared"))
  10376. (defun org-refile-cache-check-set (set)
  10377. "Check if all the markers in the cache still have live buffers."
  10378. (let (marker)
  10379. (catch 'exit
  10380. (while (and set (setq marker (nth 3 (pop set))))
  10381. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10382. (when (and marker (null (marker-buffer marker)))
  10383. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10384. (sit-for 3)
  10385. (throw 'exit nil)))
  10386. t)))
  10387. (defun org-refile-cache-put (set &rest identifiers)
  10388. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10389. (let* ((key (sha1 (prin1-to-string identifiers)))
  10390. (entry (assoc key org-refile-cache)))
  10391. (if entry
  10392. (setcdr entry set)
  10393. (push (cons key set) org-refile-cache))))
  10394. (defun org-refile-cache-get (&rest identifiers)
  10395. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10396. (cond
  10397. ((not org-refile-cache) nil)
  10398. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10399. (t
  10400. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10401. org-refile-cache))))
  10402. (and set (org-refile-cache-check-set set) set)))))
  10403. (defvar org-outline-path-cache nil
  10404. "Alist between buffer positions and outline paths.
  10405. It value is an alist (POSITION . PATH) where POSITION is the
  10406. buffer position at the beginning of an entry and PATH is a list
  10407. of strings describing the outline path for that entry, in reverse
  10408. order.")
  10409. (defun org-refile-get-targets (&optional default-buffer)
  10410. "Produce a table with refile targets."
  10411. (let ((case-fold-search nil)
  10412. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10413. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10414. targets tgs files desc descre)
  10415. (message "Getting targets...")
  10416. (with-current-buffer (or default-buffer (current-buffer))
  10417. (dolist (entry entries)
  10418. (setq files (car entry) desc (cdr entry))
  10419. (cond
  10420. ((null files) (setq files (list (current-buffer))))
  10421. ((eq files 'org-agenda-files)
  10422. (setq files (org-agenda-files 'unrestricted)))
  10423. ((and (symbolp files) (fboundp files))
  10424. (setq files (funcall files)))
  10425. ((and (symbolp files) (boundp files))
  10426. (setq files (symbol-value files))))
  10427. (when (stringp files) (setq files (list files)))
  10428. (cond
  10429. ((eq (car desc) :tag)
  10430. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10431. ((eq (car desc) :todo)
  10432. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10433. ((eq (car desc) :regexp)
  10434. (setq descre (cdr desc)))
  10435. ((eq (car desc) :level)
  10436. (setq descre (concat "^\\*\\{" (number-to-string
  10437. (if org-odd-levels-only
  10438. (1- (* 2 (cdr desc)))
  10439. (cdr desc)))
  10440. "\\}[ \t]")))
  10441. ((eq (car desc) :maxlevel)
  10442. (setq descre (concat "^\\*\\{1," (number-to-string
  10443. (if org-odd-levels-only
  10444. (1- (* 2 (cdr desc)))
  10445. (cdr desc)))
  10446. "\\}[ \t]")))
  10447. (t (error "Bad refiling target description %s" desc)))
  10448. (dolist (f files)
  10449. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10450. (or
  10451. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10452. (progn
  10453. (when (bufferp f)
  10454. (setq f (buffer-file-name (buffer-base-buffer f))))
  10455. (setq f (and f (expand-file-name f)))
  10456. (when (eq org-refile-use-outline-path 'file)
  10457. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10458. (org-with-wide-buffer
  10459. (goto-char (point-min))
  10460. (setq org-outline-path-cache nil)
  10461. (while (re-search-forward descre nil t)
  10462. (beginning-of-line)
  10463. (looking-at org-complex-heading-regexp)
  10464. (let ((begin (point))
  10465. (heading (match-string-no-properties 4)))
  10466. (unless (or (and
  10467. org-refile-target-verify-function
  10468. (not
  10469. (funcall org-refile-target-verify-function)))
  10470. (not heading))
  10471. (let ((re (format org-complex-heading-regexp-format
  10472. (regexp-quote heading)))
  10473. (target
  10474. (if (not org-refile-use-outline-path) heading
  10475. (mapconcat
  10476. #'org-protect-slash
  10477. (append
  10478. (pcase org-refile-use-outline-path
  10479. (`file (list (file-name-nondirectory
  10480. (buffer-file-name
  10481. (buffer-base-buffer)))))
  10482. (`full-file-path
  10483. (list (buffer-file-name
  10484. (buffer-base-buffer))))
  10485. (_ nil))
  10486. (org-get-outline-path t t))
  10487. "/"))))
  10488. (push (list target f re (org-refile-marker (point)))
  10489. tgs)))
  10490. (when (= (point) begin)
  10491. ;; Verification function has not moved point.
  10492. (end-of-line)))))))
  10493. (when org-refile-use-cache
  10494. (org-refile-cache-put tgs (buffer-file-name) descre))
  10495. (setq targets (append tgs targets))))))
  10496. (message "Getting targets...done")
  10497. (nreverse targets)))
  10498. (defun org-protect-slash (s)
  10499. (while (string-match "/" s)
  10500. (setq s (replace-match "\\" t t s)))
  10501. s)
  10502. (defun org--get-outline-path-1 (&optional use-cache)
  10503. "Return outline path to current headline.
  10504. Outline path is a list of strings, in reverse order. When
  10505. optional argument USE-CACHE is non-nil, make use of a cache. See
  10506. `org-get-outline-path' for details.
  10507. Assume buffer is widened and point is on a headline."
  10508. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10509. (let ((p (point))
  10510. (heading (progn
  10511. (looking-at org-complex-heading-regexp)
  10512. (if (not (match-end 4)) ""
  10513. ;; Remove statistics cookies.
  10514. (org-trim
  10515. (org-link-display-format
  10516. (replace-regexp-in-string
  10517. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10518. (match-string-no-properties 4))))))))
  10519. (if (org-up-heading-safe)
  10520. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10521. (when use-cache
  10522. (push (cons p path) org-outline-path-cache))
  10523. path)
  10524. ;; This is a new root node. Since we assume we are moving
  10525. ;; forward, we can drop previous cache so as to limit number
  10526. ;; of associations there.
  10527. (let ((path (list heading)))
  10528. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10529. path)))))
  10530. (defun org-get-outline-path (&optional with-self use-cache)
  10531. "Return the outline path to the current entry.
  10532. An outline path is a list of ancestors for current headline, as
  10533. a list of strings. Statistics cookies are removed and links are
  10534. replaced with their description, if any, or their path otherwise.
  10535. When optional argument WITH-SELF is non-nil, the path also
  10536. includes the current headline.
  10537. When optional argument USE-CACHE is non-nil, cache outline paths
  10538. between calls to this function so as to avoid backtracking. This
  10539. argument is useful when planning to find more than one outline
  10540. path in the same document. In that case, there are two
  10541. conditions to satisfy:
  10542. - `org-outline-path-cache' is set to nil before starting the
  10543. process;
  10544. - outline paths are computed by increasing buffer positions."
  10545. (org-with-wide-buffer
  10546. (and (or (and with-self (org-back-to-heading t))
  10547. (org-up-heading-safe))
  10548. (reverse (org--get-outline-path-1 use-cache)))))
  10549. (defun org-format-outline-path (path &optional width prefix separator)
  10550. "Format the outline path PATH for display.
  10551. WIDTH is the maximum number of characters that is available.
  10552. PREFIX is a prefix to be included in the returned string,
  10553. such as the file name.
  10554. SEPARATOR is inserted between the different parts of the path,
  10555. the default is \"/\"."
  10556. (setq width (or width 79))
  10557. (setq path (delq nil path))
  10558. (unless (> width 0)
  10559. (user-error "Argument `width' must be positive"))
  10560. (setq separator (or separator "/"))
  10561. (let* ((org-odd-levels-only nil)
  10562. (fpath (concat
  10563. prefix (and prefix path separator)
  10564. (mapconcat
  10565. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10566. (cl-loop for head in path
  10567. for n from 0
  10568. collect (org-add-props
  10569. head nil 'face
  10570. (nth (% n org-n-level-faces) org-level-faces)))
  10571. separator))))
  10572. (when (> (length fpath) width)
  10573. (if (< width 7)
  10574. ;; It's unlikely that `width' will be this small, but don't
  10575. ;; waste characters by adding ".." if it is.
  10576. (setq fpath (substring fpath 0 width))
  10577. (setf (substring fpath (- width 2)) "..")))
  10578. fpath))
  10579. (defun org-display-outline-path (&optional file current separator just-return-string)
  10580. "Display the current outline path in the echo area.
  10581. If FILE is non-nil, prepend the output with the file name.
  10582. If CURRENT is non-nil, append the current heading to the output.
  10583. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10584. the different parts of the path and defaults to \"/\".
  10585. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10586. (interactive "P")
  10587. (let* (case-fold-search
  10588. (bfn (buffer-file-name (buffer-base-buffer)))
  10589. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10590. res)
  10591. (when current (setq path (append path
  10592. (save-excursion
  10593. (org-back-to-heading t)
  10594. (when (looking-at org-complex-heading-regexp)
  10595. (list (match-string 4)))))))
  10596. (setq res
  10597. (org-format-outline-path
  10598. path
  10599. (1- (frame-width))
  10600. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10601. separator))
  10602. (if just-return-string
  10603. (org-no-properties res)
  10604. (org-unlogged-message "%s" res))))
  10605. (defvar org-refile-history nil
  10606. "History for refiling operations.")
  10607. (defvar org-after-refile-insert-hook nil
  10608. "Hook run after `org-refile' has inserted its stuff at the new location.
  10609. Note that this is still *before* the stuff will be removed from
  10610. the *old* location.")
  10611. (defvar org-capture-last-stored-marker)
  10612. (defvar org-refile-keep nil
  10613. "Non-nil means `org-refile' will copy instead of refile.")
  10614. (defun org-copy ()
  10615. "Like `org-refile', but copy."
  10616. (interactive)
  10617. (let ((org-refile-keep t))
  10618. (funcall 'org-refile nil nil nil "Copy")))
  10619. (defun org-refile (&optional arg default-buffer rfloc msg)
  10620. "Move the entry or entries at point to another heading.
  10621. The list of target headings is compiled using the information in
  10622. `org-refile-targets', which see.
  10623. At the target location, the entry is filed as a subitem of the
  10624. target heading. Depending on `org-reverse-note-order', the new
  10625. subitem will either be the first or the last subitem.
  10626. If there is an active region, all entries in that region will be
  10627. refiled. However, the region must fulfill the requirement that
  10628. the first heading sets the top-level of the moved text.
  10629. With prefix arg ARG, the command will only visit the target
  10630. location and not actually move anything.
  10631. With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
  10632. refiling operation has put the subtree.
  10633. With a numeric prefix argument of `2', refile to the running clock.
  10634. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10635. being set to t and copy to the target location, don't move it.
  10636. Beware that keeping refiled entries may result in duplicated ID
  10637. properties.
  10638. RFLOC can be a refile location obtained in a different way.
  10639. MSG is a string to replace \"Refile\" in the default prompt with
  10640. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10641. See also `org-refile-use-outline-path'.
  10642. If you are using target caching (see `org-refile-use-cache'), you
  10643. have to clear the target cache in order to find new targets.
  10644. This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
  10645. prefix argument (`C-u C-u C-u C-c C-w')."
  10646. (interactive "P")
  10647. (if (member arg '(0 (64)))
  10648. (org-refile-cache-clear)
  10649. (let* ((actionmsg (cond (msg msg)
  10650. ((equal arg 3) "Refile (and keep)")
  10651. (t "Refile")))
  10652. (regionp (org-region-active-p))
  10653. (region-start (and regionp (region-beginning)))
  10654. (region-end (and regionp (region-end)))
  10655. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10656. pos it nbuf file level reversed)
  10657. (setq last-command nil)
  10658. (when regionp
  10659. (goto-char region-start)
  10660. (or (bolp) (goto-char (point-at-bol)))
  10661. (setq region-start (point))
  10662. (unless (or (org-kill-is-subtree-p
  10663. (buffer-substring region-start region-end))
  10664. (prog1 org-refile-active-region-within-subtree
  10665. (let ((s (point-at-eol)))
  10666. (org-toggle-heading)
  10667. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10668. (user-error "The region is not a (sequence of) subtree(s)")))
  10669. (if (equal arg '(16))
  10670. (org-refile-goto-last-stored)
  10671. (when (or
  10672. (and (equal arg 2)
  10673. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10674. (prog1
  10675. (setq it (list (or org-clock-heading "running clock")
  10676. (buffer-file-name
  10677. (marker-buffer org-clock-hd-marker))
  10678. ""
  10679. (marker-position org-clock-hd-marker)))
  10680. (setq arg nil)))
  10681. (setq it
  10682. (or rfloc
  10683. (let (heading-text)
  10684. (save-excursion
  10685. (unless (and arg (listp arg))
  10686. (org-back-to-heading t)
  10687. (setq heading-text
  10688. (replace-regexp-in-string
  10689. org-bracket-link-regexp
  10690. "\\3"
  10691. (or (nth 4 (org-heading-components))
  10692. ""))))
  10693. (org-refile-get-location
  10694. (cond ((and arg (listp arg)) "Goto")
  10695. (regionp (concat actionmsg " region to"))
  10696. (t (concat actionmsg " subtree \""
  10697. heading-text "\" to")))
  10698. default-buffer
  10699. (and (not (equal '(4) arg))
  10700. org-refile-allow-creating-parent-nodes)))))))
  10701. (setq file (nth 1 it)
  10702. pos (nth 3 it))
  10703. (when (and (not arg)
  10704. pos
  10705. (equal (buffer-file-name) file)
  10706. (if regionp
  10707. (and (>= pos region-start)
  10708. (<= pos region-end))
  10709. (and (>= pos (point))
  10710. (< pos (save-excursion
  10711. (org-end-of-subtree t t))))))
  10712. (error "Cannot refile to position inside the tree or region"))
  10713. (setq nbuf (or (find-buffer-visiting file)
  10714. (find-file-noselect file)))
  10715. (if (and arg (not (equal arg 3)))
  10716. (progn
  10717. (pop-to-buffer-same-window nbuf)
  10718. (goto-char pos)
  10719. (org-show-context 'org-goto))
  10720. (if regionp
  10721. (progn
  10722. (org-kill-new (buffer-substring region-start region-end))
  10723. (org-save-markers-in-region region-start region-end))
  10724. (org-copy-subtree 1 nil t))
  10725. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10726. (find-file-noselect file)))
  10727. (setq reversed (org-notes-order-reversed-p))
  10728. (save-excursion
  10729. (save-restriction
  10730. (widen)
  10731. (if pos
  10732. (progn
  10733. (goto-char pos)
  10734. (looking-at org-outline-regexp)
  10735. (setq level (org-get-valid-level (funcall outline-level) 1))
  10736. (goto-char
  10737. (if reversed
  10738. (or (outline-next-heading) (point-max))
  10739. (or (save-excursion (org-get-next-sibling))
  10740. (org-end-of-subtree t t)
  10741. (point-max)))))
  10742. (setq level 1)
  10743. (if (not reversed)
  10744. (goto-char (point-max))
  10745. (goto-char (point-min))
  10746. (or (outline-next-heading) (goto-char (point-max)))))
  10747. (unless (bolp) (newline))
  10748. (org-paste-subtree level nil nil t)
  10749. (when org-log-refile
  10750. (org-add-log-setup 'refile nil nil org-log-refile)
  10751. (unless (eq org-log-refile 'note)
  10752. (save-excursion (org-add-log-note))))
  10753. (and org-auto-align-tags
  10754. (let ((org-loop-over-headlines-in-active-region nil))
  10755. (org-set-tags nil t)))
  10756. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10757. :last-refile)))
  10758. (when bookmark-name
  10759. (with-demoted-errors
  10760. (bookmark-set bookmark-name))))
  10761. ;; If we are refiling for capture, make sure that the
  10762. ;; last-capture pointers point here
  10763. (when (bound-and-true-p org-capture-is-refiling)
  10764. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10765. :last-capture-marker)))
  10766. (when bookmark-name
  10767. (with-demoted-errors
  10768. (bookmark-set bookmark-name))))
  10769. (move-marker org-capture-last-stored-marker (point)))
  10770. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10771. (run-hooks 'org-after-refile-insert-hook))))
  10772. (unless org-refile-keep
  10773. (if regionp
  10774. (delete-region (point) (+ (point) (- region-end region-start)))
  10775. (delete-region
  10776. (and (org-back-to-heading t) (point))
  10777. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10778. (when (featurep 'org-inlinetask)
  10779. (org-inlinetask-remove-END-maybe))
  10780. (setq org-markers-to-move nil)
  10781. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10782. (defun org-refile-goto-last-stored ()
  10783. "Go to the location where the last refile was stored."
  10784. (interactive)
  10785. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10786. (message "This is the location of the last refile"))
  10787. (defun org-refile--get-location (refloc tbl)
  10788. "When user refile to REFLOC, find the associated target in TBL.
  10789. Also check `org-refile-target-table'."
  10790. (car (delq
  10791. nil
  10792. (mapcar
  10793. (lambda (r) (or (assoc r tbl)
  10794. (assoc r org-refile-target-table)))
  10795. (list (replace-regexp-in-string "/$" "" refloc)
  10796. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10797. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10798. "Prompt the user for a refile location, using PROMPT.
  10799. PROMPT should not be suffixed with a colon and a space, because
  10800. this function appends the default value from
  10801. `org-refile-history' automatically, if that is not empty."
  10802. (let ((org-refile-targets org-refile-targets)
  10803. (org-refile-use-outline-path org-refile-use-outline-path))
  10804. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10805. (unless org-refile-target-table
  10806. (user-error "No refile targets"))
  10807. (let* ((cbuf (current-buffer))
  10808. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10809. (cfunc (if (and org-refile-use-outline-path
  10810. org-outline-path-complete-in-steps)
  10811. #'org-olpath-completing-read
  10812. #'completing-read))
  10813. (extra (if org-refile-use-outline-path "/" ""))
  10814. (cbnex (concat (buffer-name) extra))
  10815. (filename (and cfn (expand-file-name cfn)))
  10816. (tbl (mapcar
  10817. (lambda (x)
  10818. (if (and (not (member org-refile-use-outline-path
  10819. '(file full-file-path)))
  10820. (not (equal filename (nth 1 x))))
  10821. (cons (concat (car x) extra " ("
  10822. (file-name-nondirectory (nth 1 x)) ")")
  10823. (cdr x))
  10824. (cons (concat (car x) extra) (cdr x))))
  10825. org-refile-target-table))
  10826. (completion-ignore-case t)
  10827. cdef
  10828. (prompt (concat prompt
  10829. (or (and (car org-refile-history)
  10830. (concat " (default " (car org-refile-history) ")"))
  10831. (and (assoc cbnex tbl) (setq cdef cbnex)
  10832. (concat " (default " cbnex ")"))) ": "))
  10833. pa answ parent-target child parent old-hist)
  10834. (setq old-hist org-refile-history)
  10835. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10836. nil 'org-refile-history (or cdef (car org-refile-history))))
  10837. (if (setq pa (org-refile--get-location answ tbl))
  10838. (progn
  10839. (org-refile-check-position pa)
  10840. (when (or (not org-refile-history)
  10841. (not (eq old-hist org-refile-history))
  10842. (not (equal (car pa) (car org-refile-history))))
  10843. (setq org-refile-history
  10844. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10845. org-refile-history
  10846. (cdr org-refile-history))))
  10847. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10848. (pop org-refile-history)))
  10849. pa)
  10850. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10851. (progn
  10852. (setq parent (match-string 1 answ)
  10853. child (match-string 2 answ))
  10854. (setq parent-target (org-refile--get-location parent tbl))
  10855. (when (and parent-target
  10856. (or (eq new-nodes t)
  10857. (and (eq new-nodes 'confirm)
  10858. (y-or-n-p (format "Create new node \"%s\"? "
  10859. child)))))
  10860. (org-refile-new-child parent-target child)))
  10861. (user-error "Invalid target location")))))
  10862. (declare-function org-string-nw-p "org-macs" (s))
  10863. (defun org-refile-check-position (refile-pointer)
  10864. "Check if the refile pointer matches the headline to which it points."
  10865. (let* ((file (nth 1 refile-pointer))
  10866. (re (nth 2 refile-pointer))
  10867. (pos (nth 3 refile-pointer))
  10868. buffer)
  10869. (if (and (not (markerp pos)) (not file))
  10870. (user-error "Please indicate a target file in the refile path")
  10871. (when (org-string-nw-p re)
  10872. (setq buffer (if (markerp pos)
  10873. (marker-buffer pos)
  10874. (or (find-buffer-visiting file)
  10875. (find-file-noselect file))))
  10876. (with-current-buffer buffer
  10877. (save-excursion
  10878. (save-restriction
  10879. (widen)
  10880. (goto-char pos)
  10881. (beginning-of-line 1)
  10882. (unless (looking-at-p re)
  10883. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
  10884. (defun org-refile-new-child (parent-target child)
  10885. "Use refile target PARENT-TARGET to add new CHILD below it."
  10886. (unless parent-target
  10887. (error "Cannot find parent for new node"))
  10888. (let ((file (nth 1 parent-target))
  10889. (pos (nth 3 parent-target))
  10890. level)
  10891. (with-current-buffer (or (find-buffer-visiting file)
  10892. (find-file-noselect file))
  10893. (save-excursion
  10894. (save-restriction
  10895. (widen)
  10896. (if pos
  10897. (goto-char pos)
  10898. (goto-char (point-max))
  10899. (unless (bolp) (newline)))
  10900. (when (looking-at org-outline-regexp)
  10901. (setq level (funcall outline-level))
  10902. (org-end-of-subtree t t))
  10903. (org-back-over-empty-lines)
  10904. (insert "\n" (make-string
  10905. (if pos (org-get-valid-level level 1) 1) ?*)
  10906. " " child "\n")
  10907. (beginning-of-line 0)
  10908. (list (concat (car parent-target) "/" child) file "" (point)))))))
  10909. (defun org-olpath-completing-read (prompt collection &rest args)
  10910. "Read an outline path like a file name."
  10911. (let ((thetable collection))
  10912. (apply #'completing-read
  10913. prompt
  10914. (lambda (string predicate &optional flag)
  10915. (cond
  10916. ((eq flag nil) (try-completion string thetable))
  10917. ((eq flag t)
  10918. (let ((l (length string)))
  10919. (mapcar (lambda (x)
  10920. (let ((r (substring x l))
  10921. (f (if (string-match " ([^)]*)$" x)
  10922. (match-string 0 x)
  10923. "")))
  10924. (if (string-match "/" r)
  10925. (concat string (substring r 0 (match-end 0)) f)
  10926. x)))
  10927. (all-completions string thetable predicate))))
  10928. ;; Exact match?
  10929. ((eq flag 'lambda) (assoc string thetable))))
  10930. args)))
  10931. ;;;; Dynamic blocks
  10932. (defun org-find-dblock (name)
  10933. "Find the first dynamic block with name NAME in the buffer.
  10934. If not found, stay at current position and return nil."
  10935. (let ((case-fold-search t) pos)
  10936. (save-excursion
  10937. (goto-char (point-min))
  10938. (setq pos (and (re-search-forward
  10939. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10940. (match-beginning 0))))
  10941. (when pos (goto-char pos))
  10942. pos))
  10943. (defun org-create-dblock (plist)
  10944. "Create a dynamic block section, with parameters taken from PLIST.
  10945. PLIST must contain a :name entry which is used as the name of the block."
  10946. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10947. (end-of-line 1)
  10948. (newline))
  10949. (let ((col (current-column))
  10950. (name (plist-get plist :name)))
  10951. (insert "#+BEGIN: " name)
  10952. (while plist
  10953. (if (eq (car plist) :name)
  10954. (setq plist (cddr plist))
  10955. (insert " " (prin1-to-string (pop plist)))))
  10956. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10957. (beginning-of-line -2)))
  10958. (defun org-prepare-dblock ()
  10959. "Prepare dynamic block for refresh.
  10960. This empties the block, puts the cursor at the insert position and returns
  10961. the property list including an extra property :name with the block name."
  10962. (unless (looking-at org-dblock-start-re)
  10963. (user-error "Not at a dynamic block"))
  10964. (let* ((begdel (1+ (match-end 0)))
  10965. (name (org-no-properties (match-string 1)))
  10966. (params (append (list :name name)
  10967. (read (concat "(" (match-string 3) ")")))))
  10968. (save-excursion
  10969. (beginning-of-line 1)
  10970. (skip-chars-forward " \t")
  10971. (setq params (plist-put params :indentation-column (current-column))))
  10972. (unless (re-search-forward org-dblock-end-re nil t)
  10973. (error "Dynamic block not terminated"))
  10974. (setq params
  10975. (append params
  10976. (list :content (buffer-substring
  10977. begdel (match-beginning 0)))))
  10978. (delete-region begdel (match-beginning 0))
  10979. (goto-char begdel)
  10980. (open-line 1)
  10981. params))
  10982. (defun org-map-dblocks (&optional command)
  10983. "Apply COMMAND to all dynamic blocks in the current buffer.
  10984. If COMMAND is not given, use `org-update-dblock'."
  10985. (let ((cmd (or command 'org-update-dblock)))
  10986. (save-excursion
  10987. (goto-char (point-min))
  10988. (while (re-search-forward org-dblock-start-re nil t)
  10989. (goto-char (match-beginning 0))
  10990. (save-excursion
  10991. (condition-case nil
  10992. (funcall cmd)
  10993. (error (message "Error during update of dynamic block"))))
  10994. (unless (re-search-forward org-dblock-end-re nil t)
  10995. (error "Dynamic block not terminated"))))))
  10996. (defun org-dblock-update (&optional arg)
  10997. "User command for updating dynamic blocks.
  10998. Update the dynamic block at point. With prefix ARG, update all dynamic
  10999. blocks in the buffer."
  11000. (interactive "P")
  11001. (if arg
  11002. (org-update-all-dblocks)
  11003. (or (looking-at org-dblock-start-re)
  11004. (org-beginning-of-dblock))
  11005. (org-update-dblock)))
  11006. (defun org-update-dblock ()
  11007. "Update the dynamic block at point.
  11008. This means to empty the block, parse for parameters and then call
  11009. the correct writing function."
  11010. (interactive)
  11011. (save-excursion
  11012. (let* ((win (selected-window))
  11013. (pos (point))
  11014. (line (org-current-line))
  11015. (params (org-prepare-dblock))
  11016. (name (plist-get params :name))
  11017. (indent (plist-get params :indentation-column))
  11018. (cmd (intern (concat "org-dblock-write:" name))))
  11019. (message "Updating dynamic block `%s' at line %d..." name line)
  11020. (funcall cmd params)
  11021. (message "Updating dynamic block `%s' at line %d...done" name line)
  11022. (goto-char pos)
  11023. (when (and indent (> indent 0))
  11024. (setq indent (make-string indent ?\ ))
  11025. (save-excursion
  11026. (select-window win)
  11027. (org-beginning-of-dblock)
  11028. (forward-line 1)
  11029. (while (not (looking-at org-dblock-end-re))
  11030. (insert indent)
  11031. (beginning-of-line 2))
  11032. (when (looking-at org-dblock-end-re)
  11033. (and (looking-at "[ \t]+")
  11034. (replace-match ""))
  11035. (insert indent)))))))
  11036. (defun org-beginning-of-dblock ()
  11037. "Find the beginning of the dynamic block at point.
  11038. Error if there is no such block at point."
  11039. (let ((pos (point))
  11040. beg)
  11041. (end-of-line 1)
  11042. (if (and (re-search-backward org-dblock-start-re nil t)
  11043. (setq beg (match-beginning 0))
  11044. (re-search-forward org-dblock-end-re nil t)
  11045. (> (match-end 0) pos))
  11046. (goto-char beg)
  11047. (goto-char pos)
  11048. (error "Not in a dynamic block"))))
  11049. (defun org-update-all-dblocks ()
  11050. "Update all dynamic blocks in the buffer.
  11051. This function can be used in a hook."
  11052. (interactive)
  11053. (when (derived-mode-p 'org-mode)
  11054. (org-map-dblocks 'org-update-dblock)))
  11055. ;;;; Completion
  11056. (declare-function org-export-backend-options "ox" (cl-x) t)
  11057. (defun org-get-export-keywords ()
  11058. "Return a list of all currently understood export keywords.
  11059. Export keywords include options, block names, attributes and
  11060. keywords relative to each registered export back-end."
  11061. (let (keywords)
  11062. (dolist (backend
  11063. (bound-and-true-p org-export-registered-backends)
  11064. (delq nil keywords))
  11065. ;; Back-end name (for keywords, like #+LATEX:)
  11066. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11067. (dolist (option-entry (org-export-backend-options backend))
  11068. ;; Back-end options.
  11069. (push (nth 1 option-entry) keywords)))))
  11070. (defconst org-options-keywords
  11071. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11072. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11073. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11074. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11075. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11076. (defcustom org-structure-template-alist
  11077. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11078. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11079. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11080. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11081. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11082. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11083. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11084. ("L" "#+LaTeX: ")
  11085. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11086. ("H" "#+HTML: ")
  11087. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11088. ("A" "#+ASCII: ")
  11089. ("i" "#+INDEX: ?")
  11090. ("I" "#+INCLUDE: %file ?"))
  11091. "Structure completion elements.
  11092. This is a list of abbreviation keys and values. The value gets inserted
  11093. if you type `<' followed by the key and then press the completion key,
  11094. usually `TAB'. %file will be replaced by a file name after prompting
  11095. for the file using completion. The cursor will be placed at the position
  11096. of the `?' in the template.
  11097. There are two templates for each key, the first uses the original Org syntax,
  11098. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11099. the default when the /org-mtags.el/ module has been loaded. See also the
  11100. variable `org-mtags-prefer-muse-templates'."
  11101. :group 'org-completion
  11102. :type '(repeat
  11103. (list
  11104. (string :tag "Key")
  11105. (string :tag "Template")))
  11106. :version "25.1"
  11107. :package-version '(Org . "8.3"))
  11108. (defun org-try-structure-completion ()
  11109. "Try to complete a structure template before point.
  11110. This looks for strings like \"<e\" on an otherwise empty line and
  11111. expands them."
  11112. (let ((l (buffer-substring (point-at-bol) (point)))
  11113. a)
  11114. (when (and (looking-at "[ \t]*$")
  11115. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11116. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11117. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11118. (match-beginning 1)) a)
  11119. t)))
  11120. (defun org-complete-expand-structure-template (start cell)
  11121. "Expand a structure template."
  11122. (let ((rpl (nth 1 cell))
  11123. (ind ""))
  11124. (delete-region start (point))
  11125. (when (string-match "\\`[ \t]*#\\+" rpl)
  11126. (cond
  11127. ((bolp))
  11128. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11129. (setq ind (buffer-substring (point-at-bol) (point))))
  11130. (t (newline))))
  11131. (setq start (point))
  11132. (when (string-match "%file" rpl)
  11133. (setq rpl (replace-match
  11134. (concat
  11135. "\""
  11136. (save-match-data
  11137. (abbreviate-file-name (read-file-name "Include file: ")))
  11138. "\"")
  11139. t t rpl)))
  11140. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11141. (concat "\n" ind)))
  11142. (insert rpl)
  11143. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11144. ;;;; TODO, DEADLINE, Comments
  11145. (defun org-toggle-comment ()
  11146. "Change the COMMENT state of an entry."
  11147. (interactive)
  11148. (save-excursion
  11149. (org-back-to-heading)
  11150. (looking-at org-complex-heading-regexp)
  11151. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11152. (skip-chars-forward " \t")
  11153. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11154. (if (org-in-commented-heading-p t)
  11155. (delete-region (point)
  11156. (progn (search-forward " " (line-end-position) 'move)
  11157. (skip-chars-forward " \t")
  11158. (point)))
  11159. (insert org-comment-string)
  11160. (unless (eolp) (insert " ")))))
  11161. (defvar org-last-todo-state-is-todo nil
  11162. "This is non-nil when the last TODO state change led to a TODO state.
  11163. If the last change removed the TODO tag or switched to DONE, then
  11164. this is nil.")
  11165. (defvar org-setting-tags nil) ; dynamically skipped
  11166. (defvar org-todo-setup-filter-hook nil
  11167. "Hook for functions that pre-filter todo specs.
  11168. Each function takes a todo spec and returns either nil or the spec
  11169. transformed into canonical form." )
  11170. (defvar org-todo-get-default-hook nil
  11171. "Hook for functions that get a default item for todo.
  11172. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11173. nil or a string to be used for the todo mark." )
  11174. (defvar org-agenda-headline-snapshot-before-repeat)
  11175. (defun org-current-effective-time ()
  11176. "Return current time adjusted for `org-extend-today-until' variable."
  11177. (let* ((ct (org-current-time))
  11178. (dct (decode-time ct))
  11179. (ct1
  11180. (cond
  11181. (org-use-last-clock-out-time-as-effective-time
  11182. (or (org-clock-get-last-clock-out-time) ct))
  11183. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11184. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11185. (t ct))))
  11186. ct1))
  11187. (defun org-todo-yesterday (&optional arg)
  11188. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11189. (interactive "P")
  11190. (if (eq major-mode 'org-agenda-mode)
  11191. (apply 'org-agenda-todo-yesterday arg)
  11192. (let* ((org-use-effective-time t)
  11193. (hour (nth 2 (decode-time (org-current-time))))
  11194. (org-extend-today-until (1+ hour)))
  11195. (org-todo arg))))
  11196. (defvar org-block-entry-blocking ""
  11197. "First entry preventing the TODO state change.")
  11198. (defun org-cancel-repeater ()
  11199. "Cancel a repeater by setting its numeric value to zero."
  11200. (interactive)
  11201. (save-excursion
  11202. (org-back-to-heading t)
  11203. (let ((bound1 (point))
  11204. (bound0 (save-excursion (outline-next-heading) (point))))
  11205. (when (and (re-search-forward
  11206. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11207. org-deadline-time-regexp "\\)\\|\\("
  11208. org-ts-regexp "\\)")
  11209. bound0 t)
  11210. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11211. bound1 t))
  11212. (replace-match "0" t nil nil 1)))))
  11213. (defvar org-state) ;; dynamically scoped into this function
  11214. (defun org-todo (&optional arg)
  11215. "Change the TODO state of an item.
  11216. The state of an item is given by a keyword at the start of the heading,
  11217. like
  11218. *** TODO Write paper
  11219. *** DONE Call mom
  11220. The different keywords are specified in the variable `org-todo-keywords'.
  11221. By default the available states are \"TODO\" and \"DONE\".
  11222. So for this example: when the item starts with TODO, it is changed to DONE.
  11223. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11224. DONE are present, add TODO at the beginning of the heading.
  11225. With \\[universal-argument] prefix arg, use completion to determine the new \
  11226. state.
  11227. With numeric prefix arg, switch to that state.
  11228. With a double \\[universal-argument] prefix, switch to the next set of TODO \
  11229. keywords (nextset).
  11230. With a triple \\[universal-argument] prefix, circumvent any state blocking.
  11231. With a numeric prefix arg of 0, inhibit note taking for the change.
  11232. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11233. When called through ELisp, arg is also interpreted in the following way:
  11234. `none' -> empty state
  11235. \"\"(empty string) -> switch to empty state
  11236. `done' -> switch to DONE
  11237. `nextset' -> switch to the next set of keywords
  11238. `previousset' -> switch to the previous set of keywords
  11239. \"WAITING\" -> switch to the specified keyword, but only if it
  11240. really is a member of `org-todo-keywords'."
  11241. (interactive "P")
  11242. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11243. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11244. 'region-start-level 'region))
  11245. org-loop-over-headlines-in-active-region)
  11246. (org-map-entries
  11247. `(org-todo ,arg)
  11248. org-loop-over-headlines-in-active-region
  11249. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11250. (when (equal arg '(16)) (setq arg 'nextset))
  11251. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11252. (let ((org-blocker-hook org-blocker-hook)
  11253. commentp
  11254. case-fold-search)
  11255. (when (equal arg '(64))
  11256. (setq arg nil org-blocker-hook nil))
  11257. (when (and org-blocker-hook
  11258. (or org-inhibit-blocking
  11259. (org-entry-get nil "NOBLOCKING")))
  11260. (setq org-blocker-hook nil))
  11261. (save-excursion
  11262. (catch 'exit
  11263. (org-back-to-heading t)
  11264. (when (org-in-commented-heading-p t)
  11265. (org-toggle-comment)
  11266. (setq commentp t))
  11267. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11268. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11269. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11270. (let* ((match-data (match-data))
  11271. (startpos (point-at-bol))
  11272. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11273. (org-log-done org-log-done)
  11274. (org-log-repeat org-log-repeat)
  11275. (org-todo-log-states org-todo-log-states)
  11276. (org-inhibit-logging
  11277. (if (equal arg 0)
  11278. (progn (setq arg nil) 'note) org-inhibit-logging))
  11279. (this (match-string 1))
  11280. (hl-pos (match-beginning 0))
  11281. (head (org-get-todo-sequence-head this))
  11282. (ass (assoc head org-todo-kwd-alist))
  11283. (interpret (nth 1 ass))
  11284. (done-word (nth 3 ass))
  11285. (final-done-word (nth 4 ass))
  11286. (org-last-state (or this ""))
  11287. (completion-ignore-case t)
  11288. (member (member this org-todo-keywords-1))
  11289. (tail (cdr member))
  11290. (org-state (cond
  11291. ((and org-todo-key-trigger
  11292. (or (and (equal arg '(4))
  11293. (eq org-use-fast-todo-selection 'prefix))
  11294. (and (not arg) org-use-fast-todo-selection
  11295. (not (eq org-use-fast-todo-selection
  11296. 'prefix)))))
  11297. ;; Use fast selection
  11298. (org-fast-todo-selection))
  11299. ((and (equal arg '(4))
  11300. (or (not org-use-fast-todo-selection)
  11301. (not org-todo-key-trigger)))
  11302. ;; Read a state with completion
  11303. (completing-read
  11304. "State: " (mapcar #'list org-todo-keywords-1)
  11305. nil t))
  11306. ((eq arg 'right)
  11307. (if this
  11308. (if tail (car tail) nil)
  11309. (car org-todo-keywords-1)))
  11310. ((eq arg 'left)
  11311. (unless (equal member org-todo-keywords-1)
  11312. (if this
  11313. (nth (- (length org-todo-keywords-1)
  11314. (length tail) 2)
  11315. org-todo-keywords-1)
  11316. (org-last org-todo-keywords-1))))
  11317. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11318. (setq arg nil))) ; hack to fall back to cycling
  11319. (arg
  11320. ;; user or caller requests a specific state
  11321. (cond
  11322. ((equal arg "") nil)
  11323. ((eq arg 'none) nil)
  11324. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11325. ((eq arg 'nextset)
  11326. (or (car (cdr (member head org-todo-heads)))
  11327. (car org-todo-heads)))
  11328. ((eq arg 'previousset)
  11329. (let ((org-todo-heads (reverse org-todo-heads)))
  11330. (or (car (cdr (member head org-todo-heads)))
  11331. (car org-todo-heads))))
  11332. ((car (member arg org-todo-keywords-1)))
  11333. ((stringp arg)
  11334. (user-error "State `%s' not valid in this file" arg))
  11335. ((nth (1- (prefix-numeric-value arg))
  11336. org-todo-keywords-1))))
  11337. ((null member) (or head (car org-todo-keywords-1)))
  11338. ((equal this final-done-word) nil) ;; -> make empty
  11339. ((null tail) nil) ;; -> first entry
  11340. ((memq interpret '(type priority))
  11341. (if (eq this-command last-command)
  11342. (car tail)
  11343. (if (> (length tail) 0)
  11344. (or done-word (car org-done-keywords))
  11345. nil)))
  11346. (t
  11347. (car tail))))
  11348. (org-state (or
  11349. (run-hook-with-args-until-success
  11350. 'org-todo-get-default-hook org-state org-last-state)
  11351. org-state))
  11352. (next (if org-state (concat " " org-state " ") " "))
  11353. (change-plist (list :type 'todo-state-change :from this :to org-state
  11354. :position startpos))
  11355. dolog now-done-p)
  11356. (when org-blocker-hook
  11357. (setq org-last-todo-state-is-todo
  11358. (not (member this org-done-keywords)))
  11359. (unless (save-excursion
  11360. (save-match-data
  11361. (org-with-wide-buffer
  11362. (run-hook-with-args-until-failure
  11363. 'org-blocker-hook change-plist))))
  11364. (if (called-interactively-p 'interactive)
  11365. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11366. this org-state org-block-entry-blocking)
  11367. ;; fail silently
  11368. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11369. this org-state org-block-entry-blocking)
  11370. (throw 'exit nil))))
  11371. (store-match-data match-data)
  11372. (replace-match next t t)
  11373. (cond ((equal this org-state)
  11374. (message "TODO state was already %s" (org-trim next)))
  11375. ((pos-visible-in-window-p hl-pos)
  11376. (message "TODO state changed to %s" (org-trim next))))
  11377. (unless head
  11378. (setq head (org-get-todo-sequence-head org-state)
  11379. ass (assoc head org-todo-kwd-alist)
  11380. interpret (nth 1 ass)
  11381. done-word (nth 3 ass)
  11382. final-done-word (nth 4 ass)))
  11383. (when (memq arg '(nextset previousset))
  11384. (message "Keyword-Set %d/%d: %s"
  11385. (- (length org-todo-sets) -1
  11386. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11387. (length org-todo-sets)
  11388. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11389. (setq org-last-todo-state-is-todo
  11390. (not (member org-state org-done-keywords)))
  11391. (setq now-done-p (and (member org-state org-done-keywords)
  11392. (not (member this org-done-keywords))))
  11393. (and logging (org-local-logging logging))
  11394. (when (and (or org-todo-log-states org-log-done)
  11395. (not (eq org-inhibit-logging t))
  11396. (not (memq arg '(nextset previousset))))
  11397. ;; we need to look at recording a time and note
  11398. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11399. (nth 2 (assoc this org-todo-log-states))))
  11400. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11401. (setq dolog 'time))
  11402. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11403. (and org-state
  11404. (member org-state org-not-done-keywords)
  11405. (not (member this org-not-done-keywords))))
  11406. ;; This is now a todo state and was not one before
  11407. ;; If there was a CLOSED time stamp, get rid of it.
  11408. (org-add-planning-info nil nil 'closed))
  11409. (when (and now-done-p org-log-done)
  11410. ;; It is now done, and it was not done before
  11411. (org-add-planning-info 'closed (org-current-effective-time))
  11412. (when (and (not dolog) (eq 'note org-log-done))
  11413. (org-add-log-setup 'done org-state this 'note)))
  11414. (when (and org-state dolog)
  11415. ;; This is a non-nil state, and we need to log it
  11416. (org-add-log-setup 'state org-state this dolog)))
  11417. ;; Fixup tag positioning
  11418. (org-todo-trigger-tag-changes org-state)
  11419. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11420. (when org-provide-todo-statistics
  11421. (org-update-parent-todo-statistics))
  11422. (run-hooks 'org-after-todo-state-change-hook)
  11423. (when (and arg (not (member org-state org-done-keywords)))
  11424. (setq head (org-get-todo-sequence-head org-state)))
  11425. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11426. ;; Do we need to trigger a repeat?
  11427. (when now-done-p
  11428. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11429. ;; This is for the agenda, take a snapshot of the headline.
  11430. (save-match-data
  11431. (setq org-agenda-headline-snapshot-before-repeat
  11432. (org-get-heading))))
  11433. (org-auto-repeat-maybe org-state))
  11434. ;; Fixup cursor location if close to the keyword
  11435. (when (and (outline-on-heading-p)
  11436. (not (bolp))
  11437. (save-excursion (beginning-of-line 1)
  11438. (looking-at org-todo-line-regexp))
  11439. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11440. (goto-char (or (match-end 2) (match-end 1)))
  11441. (and (looking-at " ") (just-one-space)))
  11442. (when org-trigger-hook
  11443. (save-excursion
  11444. (run-hook-with-args 'org-trigger-hook change-plist)))
  11445. (when commentp (org-toggle-comment))))))))
  11446. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11447. "Block turning an entry into a TODO, using the hierarchy.
  11448. This checks whether the current task should be blocked from state
  11449. changes. Such blocking occurs when:
  11450. 1. The task has children which are not all in a completed state.
  11451. 2. A task has a parent with the property :ORDERED:, and there
  11452. are siblings prior to the current task with incomplete
  11453. status.
  11454. 3. The parent of the task is blocked because it has siblings that should
  11455. be done first, or is child of a block grandparent TODO entry."
  11456. (if (not org-enforce-todo-dependencies)
  11457. t ; if locally turned off don't block
  11458. (catch 'dont-block
  11459. ;; If this is not a todo state change, or if this entry is already DONE,
  11460. ;; do not block
  11461. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11462. (member (plist-get change-plist :from)
  11463. (cons 'done org-done-keywords))
  11464. (member (plist-get change-plist :to)
  11465. (cons 'todo org-not-done-keywords))
  11466. (not (plist-get change-plist :to)))
  11467. (throw 'dont-block t))
  11468. ;; If this task has children, and any are undone, it's blocked
  11469. (save-excursion
  11470. (org-back-to-heading t)
  11471. (let ((this-level (funcall outline-level)))
  11472. (outline-next-heading)
  11473. (let ((child-level (funcall outline-level)))
  11474. (while (and (not (eobp))
  11475. (> child-level this-level))
  11476. ;; this todo has children, check whether they are all
  11477. ;; completed
  11478. (when (and (not (org-entry-is-done-p))
  11479. (org-entry-is-todo-p))
  11480. (setq org-block-entry-blocking (org-get-heading))
  11481. (throw 'dont-block nil))
  11482. (outline-next-heading)
  11483. (setq child-level (funcall outline-level))))))
  11484. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11485. ;; any previous siblings are undone, it's blocked
  11486. (save-excursion
  11487. (org-back-to-heading t)
  11488. (let* ((pos (point))
  11489. (parent-pos (and (org-up-heading-safe) (point))))
  11490. (unless parent-pos (throw 'dont-block t)) ; no parent
  11491. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11492. (forward-line 1)
  11493. (re-search-forward org-not-done-heading-regexp pos t))
  11494. (setq org-block-entry-blocking (match-string 0))
  11495. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11496. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11497. (while t
  11498. (goto-char parent-pos)
  11499. (unless (looking-at org-not-done-heading-regexp)
  11500. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11501. (setq pos (point))
  11502. (setq parent-pos (and (org-up-heading-safe) (point)))
  11503. (unless parent-pos (throw 'dont-block t)) ; no parent
  11504. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11505. (forward-line 1)
  11506. (re-search-forward org-not-done-heading-regexp pos t)
  11507. (setq org-block-entry-blocking (org-get-heading)))
  11508. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11509. (defcustom org-track-ordered-property-with-tag nil
  11510. "Should the ORDERED property also be shown as a tag?
  11511. The ORDERED property decides if an entry should require subtasks to be
  11512. completed in sequence. Since a property is not very visible, setting
  11513. this option means that toggling the ORDERED property with the command
  11514. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11515. not relevant for the behavior, but it makes things more visible.
  11516. Note that toggling the tag with tags commands will not change the property
  11517. and therefore not influence behavior!
  11518. This can be t, meaning the tag ORDERED should be used, It can also be a
  11519. string to select a different tag for this task."
  11520. :group 'org-todo
  11521. :type '(choice
  11522. (const :tag "No tracking" nil)
  11523. (const :tag "Track with ORDERED tag" t)
  11524. (string :tag "Use other tag")))
  11525. (defun org-toggle-ordered-property ()
  11526. "Toggle the ORDERED property of the current entry.
  11527. For better visibility, you can track the value of this property with a tag.
  11528. See variable `org-track-ordered-property-with-tag'."
  11529. (interactive)
  11530. (let* ((t1 org-track-ordered-property-with-tag)
  11531. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11532. (save-excursion
  11533. (org-back-to-heading)
  11534. (if (org-entry-get nil "ORDERED")
  11535. (progn
  11536. (org-delete-property "ORDERED")
  11537. (and tag (org-toggle-tag tag 'off))
  11538. (message "Subtasks can be completed in arbitrary order"))
  11539. (org-entry-put nil "ORDERED" "t")
  11540. (and tag (org-toggle-tag tag 'on))
  11541. (message "Subtasks must be completed in sequence")))))
  11542. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11543. (defun org-block-todo-from-checkboxes (change-plist)
  11544. "Block turning an entry into a TODO, using checkboxes.
  11545. This checks whether the current task should be blocked from state
  11546. changes because there are unchecked boxes in this entry."
  11547. (if (not org-enforce-todo-checkbox-dependencies)
  11548. t ; if locally turned off don't block
  11549. (catch 'dont-block
  11550. ;; If this is not a todo state change, or if this entry is already DONE,
  11551. ;; do not block
  11552. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11553. (member (plist-get change-plist :from)
  11554. (cons 'done org-done-keywords))
  11555. (member (plist-get change-plist :to)
  11556. (cons 'todo org-not-done-keywords))
  11557. (not (plist-get change-plist :to)))
  11558. (throw 'dont-block t))
  11559. ;; If this task has checkboxes that are not checked, it's blocked
  11560. (save-excursion
  11561. (org-back-to-heading t)
  11562. (let ((beg (point)) end)
  11563. (outline-next-heading)
  11564. (setq end (point))
  11565. (goto-char beg)
  11566. (when (org-list-search-forward
  11567. (concat (org-item-beginning-re)
  11568. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11569. "\\[[- ]\\]")
  11570. end t)
  11571. (when (boundp 'org-blocked-by-checkboxes)
  11572. (setq org-blocked-by-checkboxes t))
  11573. (throw 'dont-block nil))))
  11574. t))) ; do not block
  11575. (defun org-entry-blocked-p ()
  11576. "Non-nil if entry at point is blocked."
  11577. (and (not (org-entry-get nil "NOBLOCKING"))
  11578. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11579. (not (run-hook-with-args-until-failure
  11580. 'org-blocker-hook
  11581. (list :type 'todo-state-change
  11582. :position (point)
  11583. :from 'todo
  11584. :to 'done)))))
  11585. (defun org-update-statistics-cookies (all)
  11586. "Update the statistics cookie, either from TODO or from checkboxes.
  11587. This should be called with the cursor in a line with a statistics cookie."
  11588. (interactive "P")
  11589. (if all
  11590. (progn
  11591. (org-update-checkbox-count 'all)
  11592. (org-map-entries 'org-update-parent-todo-statistics))
  11593. (if (not (org-at-heading-p))
  11594. (org-update-checkbox-count)
  11595. (let ((pos (point-marker))
  11596. end l1 l2)
  11597. (ignore-errors (org-back-to-heading t))
  11598. (if (not (org-at-heading-p))
  11599. (org-update-checkbox-count)
  11600. (setq l1 (org-outline-level))
  11601. (setq end (save-excursion
  11602. (outline-next-heading)
  11603. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11604. (point)))
  11605. (if (and (save-excursion
  11606. (re-search-forward
  11607. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11608. (not (save-excursion (re-search-forward
  11609. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11610. (org-update-checkbox-count)
  11611. (if (and l2 (> l2 l1))
  11612. (progn
  11613. (goto-char end)
  11614. (org-update-parent-todo-statistics))
  11615. (goto-char pos)
  11616. (beginning-of-line 1)
  11617. (while (re-search-forward
  11618. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11619. (point-at-eol) t)
  11620. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11621. (goto-char pos)
  11622. (move-marker pos nil)))))
  11623. (defvar org-entry-property-inherited-from) ;; defined below
  11624. (defun org-update-parent-todo-statistics ()
  11625. "Update any statistics cookie in the parent of the current headline.
  11626. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11627. the entire subtree and this will travel up the hierarchy and update
  11628. statistics everywhere."
  11629. (let* ((prop (save-excursion (org-up-heading-safe)
  11630. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11631. (recursive (or (not org-hierarchical-todo-statistics)
  11632. (and prop (string-match "\\<recursive\\>" prop))))
  11633. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11634. 0))
  11635. (first t)
  11636. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11637. level ltoggle l1 new ndel
  11638. (cnt-all 0) (cnt-done 0) is-percent kwd
  11639. checkbox-beg ov ovs ove cookie-present)
  11640. (catch 'exit
  11641. (save-excursion
  11642. (beginning-of-line 1)
  11643. (setq ltoggle (funcall outline-level))
  11644. ;; Three situations are to consider:
  11645. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11646. ;; to the top-level ancestor on the headline;
  11647. ;; 2. If parent has "recursive" property, repeat up to the
  11648. ;; headline setting that property, taking inheritance into
  11649. ;; account;
  11650. ;; 3. Else, move up to direct parent and proceed only once.
  11651. (while (and (setq level (org-up-heading-safe))
  11652. (or recursive first)
  11653. (>= (point) lim))
  11654. (setq first nil cookie-present nil)
  11655. (unless (and level
  11656. (not (string-match
  11657. "\\<checkbox\\>"
  11658. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11659. "")))))
  11660. (throw 'exit nil))
  11661. (while (re-search-forward box-re (point-at-eol) t)
  11662. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11663. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11664. (save-match-data
  11665. (unless (outline-next-heading) (throw 'exit nil))
  11666. (while (and (looking-at org-complex-heading-regexp)
  11667. (> (setq l1 (length (match-string 1))) level))
  11668. (setq kwd (and (or recursive (= l1 ltoggle))
  11669. (match-string 2)))
  11670. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11671. (and (eq org-provide-todo-statistics t)
  11672. (or (member kwd org-done-keywords)))
  11673. (and (listp org-provide-todo-statistics)
  11674. (stringp (car org-provide-todo-statistics))
  11675. (or (member kwd org-provide-todo-statistics)
  11676. (member kwd org-done-keywords)))
  11677. (and (listp org-provide-todo-statistics)
  11678. (listp (car org-provide-todo-statistics))
  11679. (or (member kwd (car org-provide-todo-statistics))
  11680. (and (member kwd org-done-keywords)
  11681. (member kwd (cadr org-provide-todo-statistics))))))
  11682. (setq cnt-all (1+ cnt-all))
  11683. (and (eq org-provide-todo-statistics t)
  11684. kwd
  11685. (setq cnt-all (1+ cnt-all))))
  11686. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11687. (member kwd org-done-keywords))
  11688. (and (listp org-provide-todo-statistics)
  11689. (listp (car org-provide-todo-statistics))
  11690. (member kwd org-done-keywords)
  11691. (member kwd (cadr org-provide-todo-statistics)))
  11692. (and (listp org-provide-todo-statistics)
  11693. (stringp (car org-provide-todo-statistics))
  11694. (member kwd org-done-keywords)))
  11695. (setq cnt-done (1+ cnt-done)))
  11696. (outline-next-heading)))
  11697. (setq new
  11698. (if is-percent
  11699. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11700. (max 1 cnt-all)))
  11701. (format "[%d/%d]" cnt-done cnt-all))
  11702. ndel (- (match-end 0) checkbox-beg))
  11703. ;; handle overlays when updating cookie from column view
  11704. (when (setq ov (car (overlays-at checkbox-beg)))
  11705. (setq ovs (overlay-start ov) ove (overlay-end ov))
  11706. (delete-overlay ov))
  11707. (goto-char checkbox-beg)
  11708. (insert new)
  11709. (delete-region (point) (+ (point) ndel))
  11710. (when org-auto-align-tags (org-fix-tags-on-the-fly))
  11711. (when ov (move-overlay ov ovs ove)))
  11712. (when cookie-present
  11713. (run-hook-with-args 'org-after-todo-statistics-hook
  11714. cnt-done (- cnt-all cnt-done))))))
  11715. (run-hooks 'org-todo-statistics-hook)))
  11716. (defvar org-after-todo-statistics-hook nil
  11717. "Hook that is called after a TODO statistics cookie has been updated.
  11718. Each function is called with two arguments: the number of not-done entries
  11719. and the number of done entries.
  11720. For example, the following function, when added to this hook, will switch
  11721. an entry to DONE when all children are done, and back to TODO when new
  11722. entries are set to a TODO status. Note that this hook is only called
  11723. when there is a statistics cookie in the headline!
  11724. \(defun org-summary-todo (n-done n-not-done)
  11725. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11726. \(let (org-log-done org-log-states) ; turn off logging
  11727. \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11728. ")
  11729. (defvar org-todo-statistics-hook nil
  11730. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11731. This hook runs even if there is no statistics cookie present, in which case
  11732. `org-after-todo-statistics-hook' would not run.")
  11733. (defun org-todo-trigger-tag-changes (state)
  11734. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11735. (let ((l org-todo-state-tags-triggers)
  11736. changes)
  11737. (when (or (not state) (equal state ""))
  11738. (setq changes (append changes (cdr (assoc "" l)))))
  11739. (when (and (stringp state) (> (length state) 0))
  11740. (setq changes (append changes (cdr (assoc state l)))))
  11741. (when (member state org-not-done-keywords)
  11742. (setq changes (append changes (cdr (assoc 'todo l)))))
  11743. (when (member state org-done-keywords)
  11744. (setq changes (append changes (cdr (assoc 'done l)))))
  11745. (dolist (c changes)
  11746. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11747. (defun org-local-logging (value)
  11748. "Get logging settings from a property VALUE."
  11749. ;; Directly set the variables, they are already local.
  11750. (setq org-log-done nil
  11751. org-log-repeat nil
  11752. org-todo-log-states nil)
  11753. (dolist (w (org-split-string value))
  11754. (let (a)
  11755. (cond
  11756. ((setq a (assoc w org-startup-options))
  11757. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11758. (set (nth 1 a) (nth 2 a))))
  11759. ((setq a (org-extract-log-state-settings w))
  11760. (and (member (car a) org-todo-keywords-1)
  11761. (push a org-todo-log-states)))))))
  11762. (defun org-get-todo-sequence-head (kwd)
  11763. "Return the head of the TODO sequence to which KWD belongs.
  11764. If KWD is not set, check if there is a text property remembering the
  11765. right sequence."
  11766. (let (p)
  11767. (cond
  11768. ((not kwd)
  11769. (or (get-text-property (point-at-bol) 'org-todo-head)
  11770. (progn
  11771. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11772. nil (point-at-eol)))
  11773. (get-text-property p 'org-todo-head))))
  11774. ((not (member kwd org-todo-keywords-1))
  11775. (car org-todo-keywords-1))
  11776. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11777. (defun org-fast-todo-selection ()
  11778. "Fast TODO keyword selection with single keys.
  11779. Returns the new TODO keyword, or nil if no state change should occur."
  11780. (let* ((fulltable org-todo-key-alist)
  11781. (done-keywords org-done-keywords) ;; needed for the faces.
  11782. (maxlen (apply 'max (mapcar
  11783. (lambda (x)
  11784. (if (stringp (car x)) (string-width (car x)) 0))
  11785. fulltable)))
  11786. (expert nil)
  11787. (fwidth (+ maxlen 3 1 3))
  11788. (ncol (/ (- (window-width) 4) fwidth))
  11789. tg cnt e c tbl
  11790. groups ingroup)
  11791. (save-excursion
  11792. (save-window-excursion
  11793. (if expert
  11794. (set-buffer (get-buffer-create " *Org todo*"))
  11795. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11796. (erase-buffer)
  11797. (setq-local org-done-keywords done-keywords)
  11798. (setq tbl fulltable cnt 0)
  11799. (while (setq e (pop tbl))
  11800. (cond
  11801. ((equal e '(:startgroup))
  11802. (push '() groups) (setq ingroup t)
  11803. (unless (= cnt 0)
  11804. (setq cnt 0)
  11805. (insert "\n"))
  11806. (insert "{ "))
  11807. ((equal e '(:endgroup))
  11808. (setq ingroup nil cnt 0)
  11809. (insert "}\n"))
  11810. ((equal e '(:newline))
  11811. (unless (= cnt 0)
  11812. (setq cnt 0)
  11813. (insert "\n")
  11814. (setq e (car tbl))
  11815. (while (equal (car tbl) '(:newline))
  11816. (insert "\n")
  11817. (setq tbl (cdr tbl)))))
  11818. (t
  11819. (setq tg (car e) c (cdr e))
  11820. (when ingroup (push tg (car groups)))
  11821. (setq tg (org-add-props tg nil 'face
  11822. (org-get-todo-face tg)))
  11823. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11824. (insert "[" c "] " tg (make-string
  11825. (- fwidth 4 (length tg)) ?\ ))
  11826. (when (= (setq cnt (1+ cnt)) ncol)
  11827. (insert "\n")
  11828. (when ingroup (insert " "))
  11829. (setq cnt 0)))))
  11830. (insert "\n")
  11831. (goto-char (point-min))
  11832. (unless expert (org-fit-window-to-buffer))
  11833. (message "[a-z..]:Set [SPC]:clear")
  11834. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11835. (cond
  11836. ((or (= c ?\C-g)
  11837. (and (= c ?q) (not (rassoc c fulltable))))
  11838. (setq quit-flag t))
  11839. ((= c ?\ ) nil)
  11840. ((setq e (rassoc c fulltable) tg (car e))
  11841. tg)
  11842. (t (setq quit-flag t)))))))
  11843. (defun org-entry-is-todo-p ()
  11844. (member (org-get-todo-state) org-not-done-keywords))
  11845. (defun org-entry-is-done-p ()
  11846. (member (org-get-todo-state) org-done-keywords))
  11847. (defun org-get-todo-state ()
  11848. "Return the TODO keyword of the current subtree."
  11849. (save-excursion
  11850. (org-back-to-heading t)
  11851. (and (looking-at org-todo-line-regexp)
  11852. (match-end 2)
  11853. (match-string 2))))
  11854. (defun org-at-date-range-p (&optional inactive-ok)
  11855. "Non-nil if point is inside a date range.
  11856. When optional argument INACTIVE-OK is non-nil, also consider
  11857. inactive time ranges.
  11858. When this function returns a non-nil value, match data is set
  11859. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11860. on INACTIVE-OK."
  11861. (interactive)
  11862. (save-excursion
  11863. (catch 'exit
  11864. (let ((pos (point)))
  11865. (skip-chars-backward "^[<\r\n")
  11866. (skip-chars-backward "<[")
  11867. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11868. (>= (match-end 0) pos)
  11869. (throw 'exit t))
  11870. (skip-chars-backward "^<[\r\n")
  11871. (skip-chars-backward "<[")
  11872. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11873. (>= (match-end 0) pos)
  11874. (throw 'exit t)))
  11875. nil)))
  11876. (defun org-get-repeat (&optional tagline)
  11877. "Check if there is a deadline/schedule with repeater in this entry."
  11878. (save-match-data
  11879. (save-excursion
  11880. (org-back-to-heading t)
  11881. (and (re-search-forward (if tagline
  11882. (concat tagline "\\s-*" org-repeat-re)
  11883. org-repeat-re)
  11884. (org-entry-end-position) t)
  11885. (match-string-no-properties 1)))))
  11886. (defvar org-last-changed-timestamp)
  11887. (defvar org-last-inserted-timestamp)
  11888. (defvar org-log-post-message)
  11889. (defvar org-log-note-purpose)
  11890. (defvar org-log-note-how nil)
  11891. (defvar org-log-note-extra)
  11892. (defun org-auto-repeat-maybe (done-word)
  11893. "Check if the current headline contains a repeated time-stamp.
  11894. If yes, set TODO state back to what it was and change the base date
  11895. of repeating deadline/scheduled time stamps to new date.
  11896. This function is run automatically after each state change to a DONE state."
  11897. (let* ((repeat (org-get-repeat))
  11898. (aa (assoc org-last-state org-todo-kwd-alist))
  11899. (interpret (nth 1 aa))
  11900. (head (nth 2 aa))
  11901. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11902. (msg "Entry repeats: ")
  11903. (org-log-done nil)
  11904. (org-todo-log-states nil))
  11905. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11906. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11907. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11908. org-todo-repeat-to-state)))
  11909. (unless (and to-state (member to-state org-todo-keywords-1))
  11910. (setq to-state (if (eq interpret 'type) org-last-state head)))
  11911. (org-todo to-state))
  11912. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11913. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11914. (org-time-stamp-format t t))))
  11915. (when org-log-repeat
  11916. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11917. (memq 'org-add-log-note post-command-hook))
  11918. ;; We are already setup for some record.
  11919. (when (eq org-log-repeat 'note)
  11920. ;; Make sure we take a note, not only a time stamp.
  11921. (setq org-log-note-how 'note))
  11922. ;; Set up for taking a record.
  11923. (org-add-log-setup 'state
  11924. (or done-word (car org-done-keywords))
  11925. org-last-state
  11926. org-log-repeat)))
  11927. (org-back-to-heading t)
  11928. (org-add-planning-info nil nil 'closed)
  11929. (let ((end (save-excursion (outline-next-heading) (point))))
  11930. (while (re-search-forward org-ts-regexp end t)
  11931. (when (save-match-data
  11932. (or (org-at-planning-p)
  11933. (org-at-property-p)
  11934. (eq (org-element-type (save-excursion
  11935. (backward-char)
  11936. (org-element-context)))
  11937. 'timestamp)))
  11938. (let ((type (cond ((match-end 1) org-scheduled-string)
  11939. ((match-end 3) org-deadline-string)
  11940. (t "Plain:")))
  11941. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  11942. (cond
  11943. ((not
  11944. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11945. ;; Time-stamps without a repeater are usually skipped.
  11946. ;; However, a SCHEDULED time-stamp without one is
  11947. ;; removed, as it is considered as no longer relevant.
  11948. (when (equal type org-scheduled-string)
  11949. (org-remove-timestamp-with-keyword type)))
  11950. (t
  11951. (let ((n (string-to-number (match-string 2 ts)))
  11952. (what (match-string 3 ts)))
  11953. (when (equal what "w") (setq n (* n 7) what "d"))
  11954. (when (and (equal what "h")
  11955. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11956. ts)))
  11957. (user-error
  11958. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11959. has been set"
  11960. n))
  11961. ;; Preparation, see if we need to modify the start
  11962. ;; date for the change.
  11963. (when (match-end 1)
  11964. (let ((time (save-match-data (org-time-string-to-time ts))))
  11965. (cond
  11966. ((equal (match-string 1 ts) ".")
  11967. ;; Shift starting date to today
  11968. (org-timestamp-change
  11969. (- (org-today) (time-to-days time))
  11970. 'day))
  11971. ((equal (match-string 1 ts) "+")
  11972. (let ((nshiftmax 10)
  11973. (nshift 0))
  11974. (while (or (= nshift 0)
  11975. (not (time-less-p (current-time) time)))
  11976. (when (= (cl-incf nshift) nshiftmax)
  11977. (or (y-or-n-p
  11978. (format "%d repeater intervals were not \
  11979. enough to shift date past today. Continue? "
  11980. nshift))
  11981. (user-error "Abort")))
  11982. (org-timestamp-change n (cdr (assoc what whata)))
  11983. (org-at-timestamp-p t)
  11984. (setq ts (match-string 1))
  11985. (setq time
  11986. (save-match-data
  11987. (org-time-string-to-time ts)))))
  11988. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11989. ;; Rematch, so that we have everything in
  11990. ;; place for the real shift.
  11991. (org-at-timestamp-p t)
  11992. (setq ts (match-string 1))
  11993. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11994. ts)))))
  11995. (save-excursion
  11996. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11997. (setq msg
  11998. (concat
  11999. msg type " " org-last-changed-timestamp " ")))))))))
  12000. (setq org-log-post-message msg)
  12001. (message "%s" msg))))
  12002. (defun org-show-todo-tree (arg)
  12003. "Make a compact tree which shows all headlines marked with TODO.
  12004. The tree will show the lines where the regexp matches, and all higher
  12005. headlines above the match.
  12006. With a \\[universal-argument] prefix, prompt for a regexp to match.
  12007. With a numeric prefix N, construct a sparse tree for the Nth element
  12008. of `org-todo-keywords-1'."
  12009. (interactive "P")
  12010. (let ((case-fold-search nil)
  12011. (kwd-re
  12012. (cond ((null arg) org-not-done-regexp)
  12013. ((equal arg '(4))
  12014. (let ((kwd
  12015. (completing-read "Keyword (or KWD1|KWD2|...): "
  12016. (mapcar #'list org-todo-keywords-1))))
  12017. (concat "\\("
  12018. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12019. "\\)\\>")))
  12020. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12021. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12022. org-todo-keywords-1)))
  12023. (t (user-error "Invalid prefix argument: %s" arg)))))
  12024. (message "%d TODO entries found"
  12025. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12026. (defun org-deadline (arg &optional time)
  12027. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12028. With one universal prefix argument, remove any deadline from the item.
  12029. With two universal prefix arguments, prompt for a warning delay.
  12030. With argument TIME, set the deadline at the corresponding date. TIME
  12031. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12032. (interactive "P")
  12033. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12034. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12035. 'region-start-level 'region))
  12036. org-loop-over-headlines-in-active-region)
  12037. (org-map-entries
  12038. `(org-deadline ',arg ,time)
  12039. org-loop-over-headlines-in-active-region
  12040. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12041. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12042. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12043. (repeater (and old-date
  12044. (string-match
  12045. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12046. old-date)
  12047. (match-string 1 old-date))))
  12048. (cond
  12049. ((equal arg '(4))
  12050. (when (and old-date org-log-redeadline)
  12051. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12052. (org-remove-timestamp-with-keyword org-deadline-string)
  12053. (message "Item no longer has a deadline."))
  12054. ((equal arg '(16))
  12055. (save-excursion
  12056. (org-back-to-heading t)
  12057. (if (re-search-forward
  12058. org-deadline-time-regexp
  12059. (save-excursion (outline-next-heading) (point)) t)
  12060. (let* ((rpl0 (match-string 1))
  12061. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12062. (replace-match
  12063. (concat org-deadline-string
  12064. " <" rpl
  12065. (format " -%dd"
  12066. (abs
  12067. (- (time-to-days
  12068. (save-match-data
  12069. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12070. (time-to-days old-date-time))))
  12071. ">") t t))
  12072. (user-error "No deadline information to update"))))
  12073. (t
  12074. (org-add-planning-info 'deadline time 'closed)
  12075. (when (and old-date
  12076. org-log-redeadline
  12077. (not (equal old-date org-last-inserted-timestamp)))
  12078. (org-add-log-setup
  12079. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12080. (when repeater
  12081. (save-excursion
  12082. (org-back-to-heading t)
  12083. (when (re-search-forward (concat org-deadline-string " "
  12084. org-last-inserted-timestamp)
  12085. (save-excursion
  12086. (outline-next-heading) (point)) t)
  12087. (goto-char (1- (match-end 0)))
  12088. (insert " " repeater)
  12089. (setq org-last-inserted-timestamp
  12090. (concat (substring org-last-inserted-timestamp 0 -1)
  12091. " " repeater
  12092. (substring org-last-inserted-timestamp -1))))))
  12093. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12094. (defun org-schedule (arg &optional time)
  12095. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12096. With one universal prefix argument, remove any scheduling date from the item.
  12097. With two universal prefix arguments, prompt for a delay cookie.
  12098. With argument TIME, scheduled at the corresponding date. TIME can
  12099. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12100. (interactive "P")
  12101. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12102. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12103. 'region-start-level 'region))
  12104. org-loop-over-headlines-in-active-region)
  12105. (org-map-entries
  12106. `(org-schedule ',arg ,time)
  12107. org-loop-over-headlines-in-active-region
  12108. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12109. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12110. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12111. (repeater (and old-date
  12112. (string-match
  12113. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12114. old-date)
  12115. (match-string 1 old-date))))
  12116. (cond
  12117. ((equal arg '(4))
  12118. (progn
  12119. (when (and old-date org-log-reschedule)
  12120. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12121. (org-remove-timestamp-with-keyword org-scheduled-string)
  12122. (message "Item is no longer scheduled.")))
  12123. ((equal arg '(16))
  12124. (save-excursion
  12125. (org-back-to-heading t)
  12126. (if (re-search-forward
  12127. org-scheduled-time-regexp
  12128. (save-excursion (outline-next-heading) (point)) t)
  12129. (let* ((rpl0 (match-string 1))
  12130. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12131. (replace-match
  12132. (concat org-scheduled-string
  12133. " <" rpl
  12134. (format " -%dd"
  12135. (abs
  12136. (- (time-to-days
  12137. (save-match-data
  12138. (org-read-date nil t nil "Delay until" old-date-time)))
  12139. (time-to-days old-date-time))))
  12140. ">") t t))
  12141. (user-error "No scheduled information to update"))))
  12142. (t
  12143. (org-add-planning-info 'scheduled time 'closed)
  12144. (when (and old-date
  12145. org-log-reschedule
  12146. (not (equal old-date org-last-inserted-timestamp)))
  12147. (org-add-log-setup
  12148. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12149. (when repeater
  12150. (save-excursion
  12151. (org-back-to-heading t)
  12152. (when (re-search-forward (concat org-scheduled-string " "
  12153. org-last-inserted-timestamp)
  12154. (save-excursion
  12155. (outline-next-heading) (point)) t)
  12156. (goto-char (1- (match-end 0)))
  12157. (insert " " repeater)
  12158. (setq org-last-inserted-timestamp
  12159. (concat (substring org-last-inserted-timestamp 0 -1)
  12160. " " repeater
  12161. (substring org-last-inserted-timestamp -1))))))
  12162. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12163. (defun org-get-scheduled-time (pom &optional inherit)
  12164. "Get the scheduled time as a time tuple, of a format suitable
  12165. for calling org-schedule with, or if there is no scheduling,
  12166. returns nil."
  12167. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12168. (when time
  12169. (apply 'encode-time (org-parse-time-string time)))))
  12170. (defun org-get-deadline-time (pom &optional inherit)
  12171. "Get the deadline as a time tuple, of a format suitable for
  12172. calling org-deadline with, or if there is no scheduling, returns
  12173. nil."
  12174. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12175. (when time
  12176. (apply 'encode-time (org-parse-time-string time)))))
  12177. (defun org-remove-timestamp-with-keyword (keyword)
  12178. "Remove all time stamps with KEYWORD in the current entry."
  12179. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12180. beg)
  12181. (save-excursion
  12182. (org-back-to-heading t)
  12183. (setq beg (point))
  12184. (outline-next-heading)
  12185. (while (re-search-backward re beg t)
  12186. (replace-match "")
  12187. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12188. (equal (char-before) ?\ ))
  12189. (backward-delete-char 1)
  12190. (when (string-match "^[ \t]*$" (buffer-substring
  12191. (point-at-bol) (point-at-eol)))
  12192. (delete-region (point-at-bol)
  12193. (min (point-max) (1+ (point-at-eol))))))))))
  12194. (defvar org-time-was-given) ; dynamically scoped parameter
  12195. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12196. (defun org-at-planning-p ()
  12197. "Non-nil when point is on a planning info line."
  12198. ;; This is as accurate and faster than `org-element-at-point' since
  12199. ;; planning info location is fixed in the section.
  12200. (org-with-wide-buffer
  12201. (beginning-of-line)
  12202. (and (looking-at-p org-planning-line-re)
  12203. (eq (point)
  12204. (ignore-errors
  12205. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12206. (org-back-to-heading t)
  12207. (org-with-limited-levels (org-back-to-heading t)))
  12208. (line-beginning-position 2))))))
  12209. (defun org-add-planning-info (what &optional time &rest remove)
  12210. "Insert new timestamp with keyword in the planning line.
  12211. WHAT indicates what kind of time stamp to add. It is a symbol
  12212. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12213. the time to use. If none is given, the user is prompted for
  12214. a date. REMOVE indicates what kind of entries to remove. An old
  12215. WHAT entry will also be removed."
  12216. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12217. (catch 'exit
  12218. (when (and (memq what '(scheduled deadline))
  12219. (or (not time)
  12220. (and (stringp time)
  12221. (string-match "^[-+]+[0-9]" time))))
  12222. ;; Try to get a default date/time from existing timestamp
  12223. (save-excursion
  12224. (org-back-to-heading t)
  12225. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12226. (when (re-search-forward (if (eq what 'scheduled)
  12227. org-scheduled-time-regexp
  12228. org-deadline-time-regexp)
  12229. end t)
  12230. (setq ts (match-string 1)
  12231. default-time (apply 'encode-time (org-parse-time-string ts))
  12232. default-input (and ts (org-get-compact-tod ts)))))))
  12233. (when what
  12234. (setq time
  12235. (if (stringp time)
  12236. ;; This is a string (relative or absolute), set
  12237. ;; proper date.
  12238. (apply #'encode-time
  12239. (org-read-date-analyze
  12240. time default-time (decode-time default-time)))
  12241. ;; If necessary, get the time from the user
  12242. (or time (org-read-date nil 'to-time nil nil
  12243. default-time default-input)))))
  12244. (org-with-wide-buffer
  12245. (org-back-to-heading t)
  12246. (forward-line)
  12247. (unless (bolp) (insert "\n"))
  12248. (cond ((looking-at-p org-planning-line-re)
  12249. ;; Move to current indentation.
  12250. (skip-chars-forward " \t")
  12251. ;; Check if we have to remove something.
  12252. (dolist (type (if what (cons what remove) remove))
  12253. (save-excursion
  12254. (when (re-search-forward
  12255. (cl-case type
  12256. (closed org-closed-time-regexp)
  12257. (deadline org-deadline-time-regexp)
  12258. (scheduled org-scheduled-time-regexp)
  12259. (otherwise
  12260. (error "Invalid planning type: %s" type)))
  12261. (line-end-position) t)
  12262. ;; Delete until next keyword or end of line.
  12263. (delete-region
  12264. (match-beginning 0)
  12265. (if (re-search-forward org-keyword-time-not-clock-regexp
  12266. (line-end-position)
  12267. t)
  12268. (match-beginning 0)
  12269. (line-end-position))))))
  12270. ;; If there is nothing more to add and no more keyword
  12271. ;; is left, remove the line completely.
  12272. (if (and (looking-at-p "[ \t]*$") (not what))
  12273. (delete-region (line-beginning-position)
  12274. (line-beginning-position 2))
  12275. ;; If we removed last keyword, do not leave trailing
  12276. ;; white space at the end of line.
  12277. (let ((p (point)))
  12278. (save-excursion
  12279. (end-of-line)
  12280. (unless (= (skip-chars-backward " \t" p) 0)
  12281. (delete-region (point) (line-end-position)))))))
  12282. ((not what) (throw 'exit nil)) ; Nothing to do.
  12283. (t (insert-before-markers "\n")
  12284. (backward-char 1)
  12285. (when org-adapt-indentation
  12286. (indent-to-column (1+ (org-outline-level))))))
  12287. (when what
  12288. ;; Insert planning keyword.
  12289. (insert (cl-case what
  12290. (closed org-closed-string)
  12291. (deadline org-deadline-string)
  12292. (scheduled org-scheduled-string)
  12293. (otherwise (error "Invalid planning type: %s" what)))
  12294. " ")
  12295. ;; Insert associated timestamp.
  12296. (let ((ts (org-insert-time-stamp
  12297. time
  12298. (or org-time-was-given
  12299. (and (eq what 'closed) org-log-done-with-time))
  12300. (eq what 'closed)
  12301. nil nil (list org-end-time-was-given))))
  12302. (unless (eolp) (insert " "))
  12303. ts))))))
  12304. (defvar org-log-note-marker (make-marker)
  12305. "Marker pointing at the entry where the note is to be inserted.")
  12306. (defvar org-log-note-purpose nil)
  12307. (defvar org-log-note-state nil)
  12308. (defvar org-log-note-previous-state nil)
  12309. (defvar org-log-note-extra nil)
  12310. (defvar org-log-note-window-configuration nil)
  12311. (defvar org-log-note-return-to (make-marker))
  12312. (defvar org-log-note-effective-time nil
  12313. "Remembered current time so that dynamically scoped
  12314. `org-extend-today-until' affects timestamps in state change log")
  12315. (defvar org-log-post-message nil
  12316. "Message to be displayed after a log note has been stored.
  12317. The auto-repeater uses this.")
  12318. (defun org-add-note ()
  12319. "Add a note to the current entry.
  12320. This is done in the same way as adding a state change note."
  12321. (interactive)
  12322. (org-add-log-setup 'note))
  12323. (defun org-log-beginning (&optional create)
  12324. "Return expected start of log notes in current entry.
  12325. When optional argument CREATE is non-nil, the function creates
  12326. a drawer to store notes, if necessary. Returned position ignores
  12327. narrowing."
  12328. (org-with-wide-buffer
  12329. (let ((drawer (org-log-into-drawer)))
  12330. (cond
  12331. (drawer
  12332. (org-end-of-meta-data)
  12333. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12334. (end (if (org-at-heading-p) (point)
  12335. (save-excursion (outline-next-heading) (point))))
  12336. (case-fold-search t))
  12337. (catch 'exit
  12338. ;; Try to find existing drawer.
  12339. (while (re-search-forward regexp end t)
  12340. (let ((element (org-element-at-point)))
  12341. (when (eq (org-element-type element) 'drawer)
  12342. (let ((cend (org-element-property :contents-end element)))
  12343. (when (and (not org-log-states-order-reversed) cend)
  12344. (goto-char cend)))
  12345. (throw 'exit nil))))
  12346. ;; No drawer found. Create one, if permitted.
  12347. (when create
  12348. (unless (bolp) (insert "\n"))
  12349. (let ((beg (point)))
  12350. (insert ":" drawer ":\n:END:\n")
  12351. (org-indent-region beg (point)))
  12352. (end-of-line -1)))))
  12353. (t
  12354. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12355. (skip-chars-forward " \t\n")
  12356. (beginning-of-line)
  12357. (unless org-log-states-order-reversed
  12358. (org-skip-over-state-notes)
  12359. (skip-chars-backward " \t\n")
  12360. (forward-line)))))
  12361. (if (bolp) (point) (line-beginning-position 2))))
  12362. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12363. "Set up the post command hook to take a note.
  12364. If this is about to TODO state change, the new state is expected in STATE.
  12365. HOW is an indicator what kind of note should be created.
  12366. EXTRA is additional text that will be inserted into the notes buffer."
  12367. (move-marker org-log-note-marker (point))
  12368. (setq org-log-note-purpose purpose
  12369. org-log-note-state state
  12370. org-log-note-previous-state prev-state
  12371. org-log-note-how how
  12372. org-log-note-extra extra
  12373. org-log-note-effective-time (org-current-effective-time))
  12374. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12375. (defun org-skip-over-state-notes ()
  12376. "Skip past the list of State notes in an entry."
  12377. (when (ignore-errors (goto-char (org-in-item-p)))
  12378. (let* ((struct (org-list-struct))
  12379. (prevs (org-list-prevs-alist struct))
  12380. (regexp
  12381. (concat "[ \t]*- +"
  12382. (replace-regexp-in-string
  12383. " +" " +"
  12384. (org-replace-escapes
  12385. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12386. `(("%d" . ,org-ts-regexp-inactive)
  12387. ("%D" . ,org-ts-regexp)
  12388. ("%s" . "\"\\S-+\"")
  12389. ("%S" . "\"\\S-+\"")
  12390. ("%t" . ,org-ts-regexp-inactive)
  12391. ("%T" . ,org-ts-regexp)
  12392. ("%u" . ".*?")
  12393. ("%U" . ".*?")))))))
  12394. (while (looking-at-p regexp)
  12395. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12396. (org-list-get-item-end (point) struct)))))))
  12397. (defun org-add-log-note (&optional _purpose)
  12398. "Pop up a window for taking a note, and add this note later."
  12399. (remove-hook 'post-command-hook 'org-add-log-note)
  12400. (setq org-log-note-window-configuration (current-window-configuration))
  12401. (delete-other-windows)
  12402. (move-marker org-log-note-return-to (point))
  12403. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12404. (goto-char org-log-note-marker)
  12405. (org-switch-to-buffer-other-window "*Org Note*")
  12406. (erase-buffer)
  12407. (if (memq org-log-note-how '(time state))
  12408. (let (current-prefix-arg) (org-store-log-note))
  12409. (let ((org-inhibit-startup t)) (org-mode))
  12410. (insert (format "# Insert note for %s.
  12411. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12412. (cond
  12413. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12414. ((eq org-log-note-purpose 'done) "closed todo item")
  12415. ((eq org-log-note-purpose 'state)
  12416. (format "state change from \"%s\" to \"%s\""
  12417. (or org-log-note-previous-state "")
  12418. (or org-log-note-state "")))
  12419. ((eq org-log-note-purpose 'reschedule)
  12420. "rescheduling")
  12421. ((eq org-log-note-purpose 'delschedule)
  12422. "no longer scheduled")
  12423. ((eq org-log-note-purpose 'redeadline)
  12424. "changing deadline")
  12425. ((eq org-log-note-purpose 'deldeadline)
  12426. "removing deadline")
  12427. ((eq org-log-note-purpose 'refile)
  12428. "refiling")
  12429. ((eq org-log-note-purpose 'note)
  12430. "this entry")
  12431. (t (error "This should not happen")))))
  12432. (when org-log-note-extra (insert org-log-note-extra))
  12433. (setq-local org-finish-function 'org-store-log-note)
  12434. (run-hooks 'org-log-buffer-setup-hook)))
  12435. (defvar org-note-abort nil) ; dynamically scoped
  12436. (defun org-store-log-note ()
  12437. "Finish taking a log note, and insert it to where it belongs."
  12438. (let ((txt (prog1 (buffer-string)
  12439. (kill-buffer)))
  12440. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12441. lines)
  12442. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12443. (setq txt (replace-match "" t t txt)))
  12444. (when (string-match "\\s-+\\'" txt)
  12445. (setq txt (replace-match "" t t txt)))
  12446. (setq lines (org-split-string txt "\n"))
  12447. (when (org-string-nw-p note)
  12448. (setq note
  12449. (org-replace-escapes
  12450. note
  12451. (list (cons "%u" (user-login-name))
  12452. (cons "%U" user-full-name)
  12453. (cons "%t" (format-time-string
  12454. (org-time-stamp-format 'long 'inactive)
  12455. org-log-note-effective-time))
  12456. (cons "%T" (format-time-string
  12457. (org-time-stamp-format 'long nil)
  12458. org-log-note-effective-time))
  12459. (cons "%d" (format-time-string
  12460. (org-time-stamp-format nil 'inactive)
  12461. org-log-note-effective-time))
  12462. (cons "%D" (format-time-string
  12463. (org-time-stamp-format nil nil)
  12464. org-log-note-effective-time))
  12465. (cons "%s" (cond
  12466. ((not org-log-note-state) "")
  12467. ((org-string-match-p org-ts-regexp
  12468. org-log-note-state)
  12469. (format "\"[%s]\""
  12470. (substring org-log-note-state 1 -1)))
  12471. (t (format "\"%s\"" org-log-note-state))))
  12472. (cons "%S"
  12473. (cond
  12474. ((not org-log-note-previous-state) "")
  12475. ((org-string-match-p org-ts-regexp
  12476. org-log-note-previous-state)
  12477. (format "\"[%s]\""
  12478. (substring
  12479. org-log-note-previous-state 1 -1)))
  12480. (t (format "\"%s\""
  12481. org-log-note-previous-state)))))))
  12482. (when lines (setq note (concat note " \\\\")))
  12483. (push note lines))
  12484. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12485. (with-current-buffer (marker-buffer org-log-note-marker)
  12486. (org-with-wide-buffer
  12487. ;; Find location for the new note.
  12488. (goto-char org-log-note-marker)
  12489. (set-marker org-log-note-marker nil)
  12490. (goto-char (org-log-beginning t))
  12491. ;; Make sure point is at the beginning of an empty line.
  12492. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12493. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12494. ;; In an existing list, add a new item at the top level.
  12495. ;; Otherwise, indent line like a regular one.
  12496. (let ((itemp (org-in-item-p)))
  12497. (if itemp
  12498. (indent-line-to
  12499. (let ((struct (save-excursion
  12500. (goto-char itemp) (org-list-struct))))
  12501. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12502. (org-indent-line)))
  12503. (insert (org-list-bullet-string "-") (pop lines))
  12504. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12505. (dolist (line lines)
  12506. (insert "\n")
  12507. (indent-line-to ind)
  12508. (insert line)))
  12509. (message "Note stored")
  12510. (org-back-to-heading t)
  12511. (org-cycle-hide-drawers 'children))
  12512. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12513. ;; from within `org-add-log-note' because `buffer-undo-list'
  12514. ;; is then modified outside of `org-with-remote-undo'.
  12515. (when (eq this-command 'org-agenda-todo)
  12516. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12517. ;; Don't add undo information when called from `org-agenda-todo'.
  12518. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12519. (set-window-configuration org-log-note-window-configuration)
  12520. (with-current-buffer (marker-buffer org-log-note-return-to)
  12521. (goto-char org-log-note-return-to))
  12522. (move-marker org-log-note-return-to nil)
  12523. (when org-log-post-message (message "%s" org-log-post-message))))
  12524. (defun org-remove-empty-drawer-at (pos)
  12525. "Remove an empty drawer at position POS.
  12526. POS may also be a marker."
  12527. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12528. (org-with-wide-buffer
  12529. (goto-char pos)
  12530. (let ((drawer (org-element-at-point)))
  12531. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12532. (not (org-element-property :contents-begin drawer)))
  12533. (delete-region (org-element-property :begin drawer)
  12534. (progn (goto-char (org-element-property :end drawer))
  12535. (skip-chars-backward " \r\t\n")
  12536. (forward-line)
  12537. (point))))))))
  12538. (defvar org-ts-type nil)
  12539. (defun org-sparse-tree (&optional arg type)
  12540. "Create a sparse tree, prompt for the details.
  12541. This command can create sparse trees. You first need to select the type
  12542. of match used to create the tree:
  12543. t Show all TODO entries.
  12544. T Show entries with a specific TODO keyword.
  12545. m Show entries selected by a tags/property match.
  12546. p Enter a property name and its value (both with completion on existing
  12547. names/values) and show entries with that property.
  12548. r Show entries matching a regular expression (`/' can be used as well).
  12549. b Show deadlines and scheduled items before a date.
  12550. a Show deadlines and scheduled items after a date.
  12551. d Show deadlines due within `org-deadline-warning-days'.
  12552. D Show deadlines and scheduled items between a date range."
  12553. (interactive "P")
  12554. (setq type (or type org-sparse-tree-default-date-type))
  12555. (setq org-ts-type type)
  12556. (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12557. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12558. \[c]ycle through date types: %s"
  12559. (cl-case type
  12560. (all "all timestamps")
  12561. (scheduled "only scheduled")
  12562. (deadline "only deadline")
  12563. (active "only active timestamps")
  12564. (inactive "only inactive timestamps")
  12565. (closed "with a closed time-stamp")
  12566. (otherwise "scheduled/deadline")))
  12567. (let ((answer (read-char-exclusive)))
  12568. (cl-case answer
  12569. (?c
  12570. (org-sparse-tree
  12571. arg
  12572. (cadr
  12573. (memq type '(nil all scheduled deadline active inactive closed)))))
  12574. (?d (call-interactively 'org-check-deadlines))
  12575. (?b (call-interactively 'org-check-before-date))
  12576. (?a (call-interactively 'org-check-after-date))
  12577. (?D (call-interactively 'org-check-dates-range))
  12578. (?t (call-interactively 'org-show-todo-tree))
  12579. (?T (org-show-todo-tree '(4)))
  12580. (?m (call-interactively 'org-match-sparse-tree))
  12581. ((?p ?P)
  12582. (let* ((kwd (completing-read
  12583. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12584. (value (completing-read
  12585. "Value: " (mapcar #'list (org-property-values kwd)))))
  12586. (unless (string-match "\\`{.*}\\'" value)
  12587. (setq value (concat "\"" value "\"")))
  12588. (org-match-sparse-tree arg (concat kwd "=" value))))
  12589. ((?r ?R ?/) (call-interactively 'org-occur))
  12590. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12591. (defvar-local org-occur-highlights nil
  12592. "List of overlays used for occur matches.")
  12593. (defvar-local org-occur-parameters nil
  12594. "Parameters of the active org-occur calls.
  12595. This is a list, each call to org-occur pushes as cons cell,
  12596. containing the regular expression and the callback, onto the list.
  12597. The list can contain several entries if `org-occur' has been called
  12598. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12599. will only contain one set of parameters. When the highlights are
  12600. removed (for example with `C-c C-c', or with the next edit (depending
  12601. on `org-remove-highlights-with-change'), this variable is emptied
  12602. as well.")
  12603. (defun org-occur (regexp &optional keep-previous callback)
  12604. "Make a compact tree which shows all matches of REGEXP.
  12605. The tree will show the lines where the regexp matches, and any other context
  12606. defined in `org-show-context-detail', which see.
  12607. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12608. done by a previous call to `org-occur' will be kept, to allow stacking of
  12609. calls to this command.
  12610. Optional argument CALLBACK can be a function of no argument. In this case,
  12611. it is called with point at the end of the match, match data being set
  12612. accordingly. Current match is shown only if the return value is non-nil.
  12613. The function must neither move point nor alter narrowing."
  12614. (interactive "sRegexp: \nP")
  12615. (when (equal regexp "")
  12616. (user-error "Regexp cannot be empty"))
  12617. (unless keep-previous
  12618. (org-remove-occur-highlights nil nil t))
  12619. (push (cons regexp callback) org-occur-parameters)
  12620. (let ((cnt 0))
  12621. (save-excursion
  12622. (goto-char (point-min))
  12623. (when (or (not keep-previous) ; do not want to keep
  12624. (not org-occur-highlights)) ; no previous matches
  12625. ;; hide everything
  12626. (org-overview))
  12627. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12628. (isearch-no-upper-case-p regexp t)
  12629. org-occur-case-fold-search)))
  12630. (while (re-search-forward regexp nil t)
  12631. (when (or (not callback)
  12632. (save-match-data (funcall callback)))
  12633. (setq cnt (1+ cnt))
  12634. (when org-highlight-sparse-tree-matches
  12635. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12636. (org-show-context 'occur-tree)))))
  12637. (when org-remove-highlights-with-change
  12638. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12639. nil 'local))
  12640. (unless org-sparse-tree-open-archived-trees
  12641. (org-hide-archived-subtrees (point-min) (point-max)))
  12642. (run-hooks 'org-occur-hook)
  12643. (when (called-interactively-p 'interactive)
  12644. (message "%d match(es) for regexp %s" cnt regexp))
  12645. cnt))
  12646. (defun org-occur-next-match (&optional n _reset)
  12647. "Function for `next-error-function' to find sparse tree matches.
  12648. N is the number of matches to move, when negative move backwards.
  12649. This function always goes back to the starting point when no
  12650. match is found."
  12651. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12652. (search-func (if (< n 0)
  12653. 'previous-single-char-property-change
  12654. 'next-single-char-property-change))
  12655. (n (abs n))
  12656. (pos (point))
  12657. p1)
  12658. (catch 'exit
  12659. (while (setq p1 (funcall search-func (point) 'org-type))
  12660. (when (equal p1 limit)
  12661. (goto-char pos)
  12662. (user-error "No more matches"))
  12663. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12664. (setq n (1- n))
  12665. (when (= n 0)
  12666. (goto-char p1)
  12667. (throw 'exit (point))))
  12668. (goto-char p1))
  12669. (goto-char p1)
  12670. (user-error "No more matches"))))
  12671. (defun org-show-context (&optional key)
  12672. "Make sure point and context are visible.
  12673. Optional argument KEY, when non-nil, is a symbol. See
  12674. `org-show-context-detail' for allowed values and how much is to
  12675. be shown."
  12676. (org-show-set-visibility
  12677. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12678. ((cdr (assq key org-show-context-detail)))
  12679. (t (cdr (assq 'default org-show-context-detail))))))
  12680. (defun org-show-set-visibility (detail)
  12681. "Set visibility around point according to DETAIL.
  12682. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12683. `tree', `canonical' or t. See `org-show-context-detail' for more
  12684. information."
  12685. ;; Show current heading and possibly its entry, following headline
  12686. ;; or all children.
  12687. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12688. (org-flag-heading nil)
  12689. (org-show-entry)
  12690. ;; If point is hidden within a drawer or a block, make sure to
  12691. ;; expose it.
  12692. (dolist (o (overlays-at (point)))
  12693. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12694. (delete-overlay o)))
  12695. (unless (org-before-first-heading-p)
  12696. (org-with-limited-levels
  12697. (cl-case detail
  12698. ((tree canonical t) (org-show-children))
  12699. ((nil minimal ancestors))
  12700. (t (save-excursion
  12701. (outline-next-heading)
  12702. (org-flag-heading nil)))))))
  12703. ;; Show all siblings.
  12704. (when (eq detail 'lineage) (org-show-siblings))
  12705. ;; Show ancestors, possibly with their children.
  12706. (when (memq detail '(ancestors lineage tree canonical t))
  12707. (save-excursion
  12708. (while (org-up-heading-safe)
  12709. (org-flag-heading nil)
  12710. (when (memq detail '(canonical t)) (org-show-entry))
  12711. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12712. (defvar org-reveal-start-hook nil
  12713. "Hook run before revealing a location.")
  12714. (defun org-reveal (&optional siblings)
  12715. "Show current entry, hierarchy above it, and the following headline.
  12716. This can be used to show a consistent set of context around
  12717. locations exposed with `org-show-context'.
  12718. With optional argument SIBLINGS, on each level of the hierarchy all
  12719. siblings are shown. This repairs the tree structure to what it would
  12720. look like when opened with hierarchical calls to `org-cycle'.
  12721. With double optional argument \\[universal-argument] \\[universal-argument], \
  12722. go to the parent and show the
  12723. entire tree."
  12724. (interactive "P")
  12725. (run-hooks 'org-reveal-start-hook)
  12726. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12727. ((equal siblings '(16))
  12728. (save-excursion
  12729. (when (org-up-heading-safe)
  12730. (org-show-subtree)
  12731. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12732. (t (org-show-set-visibility 'lineage))))
  12733. (defun org-highlight-new-match (beg end)
  12734. "Highlight from BEG to END and mark the highlight is an occur headline."
  12735. (let ((ov (make-overlay beg end)))
  12736. (overlay-put ov 'face 'secondary-selection)
  12737. (overlay-put ov 'org-type 'org-occur)
  12738. (push ov org-occur-highlights)))
  12739. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12740. "Remove the occur highlights from the buffer.
  12741. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12742. from the `before-change-functions' in the current buffer."
  12743. (interactive)
  12744. (unless org-inhibit-highlight-removal
  12745. (mapc #'delete-overlay org-occur-highlights)
  12746. (setq org-occur-highlights nil)
  12747. (setq org-occur-parameters nil)
  12748. (unless noremove
  12749. (remove-hook 'before-change-functions
  12750. 'org-remove-occur-highlights 'local))))
  12751. ;;;; Priorities
  12752. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12753. "Regular expression matching the priority indicator.")
  12754. (defvar org-remove-priority-next-time nil)
  12755. (defun org-priority-up ()
  12756. "Increase the priority of the current item."
  12757. (interactive)
  12758. (org-priority 'up))
  12759. (defun org-priority-down ()
  12760. "Decrease the priority of the current item."
  12761. (interactive)
  12762. (org-priority 'down))
  12763. (defun org-priority (&optional action _show)
  12764. "Change the priority of an item.
  12765. ACTION can be `set', `up', `down', or a character."
  12766. (interactive "P")
  12767. (if (equal action '(4))
  12768. (org-show-priority)
  12769. (unless org-enable-priority-commands
  12770. (user-error "Priority commands are disabled"))
  12771. (setq action (or action 'set))
  12772. (let (current new news have remove)
  12773. (save-excursion
  12774. (org-back-to-heading t)
  12775. (when (looking-at org-priority-regexp)
  12776. (setq current (string-to-char (match-string 2))
  12777. have t))
  12778. (cond
  12779. ((eq action 'remove)
  12780. (setq remove t new ?\ ))
  12781. ((or (eq action 'set)
  12782. (integerp action))
  12783. (if (not (eq action 'set))
  12784. (setq new action)
  12785. (message "Priority %c-%c, SPC to remove: "
  12786. org-highest-priority org-lowest-priority)
  12787. (save-match-data
  12788. (setq new (read-char-exclusive))))
  12789. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12790. (= (upcase org-lowest-priority) org-lowest-priority))
  12791. (setq new (upcase new)))
  12792. (cond ((equal new ?\ ) (setq remove t))
  12793. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12794. (user-error "Priority must be between `%c' and `%c'"
  12795. org-highest-priority org-lowest-priority))))
  12796. ((eq action 'up)
  12797. (setq new (if have
  12798. (1- current) ; normal cycling
  12799. ;; last priority was empty
  12800. (if (eq last-command this-command)
  12801. org-lowest-priority ; wrap around empty to lowest
  12802. ;; default
  12803. (if org-priority-start-cycle-with-default
  12804. org-default-priority
  12805. (1- org-default-priority))))))
  12806. ((eq action 'down)
  12807. (setq new (if have
  12808. (1+ current) ; normal cycling
  12809. ;; last priority was empty
  12810. (if (eq last-command this-command)
  12811. org-highest-priority ; wrap around empty to highest
  12812. ;; default
  12813. (if org-priority-start-cycle-with-default
  12814. org-default-priority
  12815. (1+ org-default-priority))))))
  12816. (t (user-error "Invalid action")))
  12817. (when (or (< (upcase new) org-highest-priority)
  12818. (> (upcase new) org-lowest-priority))
  12819. (if (and (memq action '(up down))
  12820. (not have) (not (eq last-command this-command)))
  12821. ;; `new' is from default priority
  12822. (error
  12823. "The default can not be set, see `org-default-priority' why")
  12824. ;; normal cycling: `new' is beyond highest/lowest priority
  12825. ;; and is wrapped around to the empty priority
  12826. (setq remove t)))
  12827. (setq news (format "%c" new))
  12828. (if have
  12829. (if remove
  12830. (replace-match "" t t nil 1)
  12831. (replace-match news t t nil 2))
  12832. (if remove
  12833. (user-error "No priority cookie found in line")
  12834. (let ((case-fold-search nil))
  12835. (looking-at org-todo-line-regexp))
  12836. (if (match-end 2)
  12837. (progn
  12838. (goto-char (match-end 2))
  12839. (insert " [#" news "]"))
  12840. (goto-char (match-beginning 3))
  12841. (insert "[#" news "] "))))
  12842. (org-set-tags nil 'align))
  12843. (if remove
  12844. (message "Priority removed")
  12845. (message "Priority of current item set to %s" news)))))
  12846. (defun org-show-priority ()
  12847. "Show the priority of the current item.
  12848. This priority is composed of the main priority given with the [#A] cookies,
  12849. and by additional input from the age of a schedules or deadline entry."
  12850. (interactive)
  12851. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12852. (org-get-at-bol 'priority)
  12853. (save-excursion
  12854. (save-match-data
  12855. (beginning-of-line)
  12856. (and (looking-at org-heading-regexp)
  12857. (org-get-priority (match-string 0))))))))
  12858. (message "Priority is %d" (if pri pri -1000))))
  12859. (defun org-get-priority (s)
  12860. "Find priority cookie and return priority."
  12861. (save-match-data
  12862. (if (functionp org-get-priority-function)
  12863. (funcall org-get-priority-function)
  12864. (if (not (string-match org-priority-regexp s))
  12865. (* 1000 (- org-lowest-priority org-default-priority))
  12866. (* 1000 (- org-lowest-priority
  12867. (string-to-char (match-string 2 s))))))))
  12868. ;;;; Tags
  12869. (defvar org-agenda-archives-mode)
  12870. (defvar org-map-continue-from nil
  12871. "Position from where mapping should continue.
  12872. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12873. (defvar org-scanner-tags nil
  12874. "The current tag list while the tags scanner is running.")
  12875. (defvar org-trust-scanner-tags nil
  12876. "Should `org-get-tags-at' use the tags for the scanner.
  12877. This is for internal dynamical scoping only.
  12878. When this is non-nil, the function `org-get-tags-at' will return the value
  12879. of `org-scanner-tags' instead of building the list by itself. This
  12880. can lead to large speed-ups when the tags scanner is used in a file with
  12881. many entries, and when the list of tags is retrieved, for example to
  12882. obtain a list of properties. Building the tags list for each entry in such
  12883. a file becomes an N^2 operation - but with this variable set, it scales
  12884. as N.")
  12885. (defvar org--matcher-tags-todo-only nil)
  12886. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12887. "Scan headline tags with inheritance and produce output ACTION.
  12888. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12889. or `agenda' to produce an entry list for an agenda view. It can also be
  12890. a Lisp form or a function that should be called at each matched headline, in
  12891. this case the return value is a list of all return values from these calls.
  12892. MATCHER is a function accepting three arguments, returning
  12893. a non-nil value whenever a given set of tags qualifies a headline
  12894. for inclusion. See `org-make-tags-matcher' for more information.
  12895. As a special case, it can also be set to t (respectively nil) in
  12896. order to match all (respectively none) headline.
  12897. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12898. keyword are included in the output.
  12899. START-LEVEL can be a string with asterisks, reducing the scope to
  12900. headlines matching this string."
  12901. (require 'org-agenda)
  12902. (let* ((re (concat "^"
  12903. (if start-level
  12904. ;; Get the correct level to match
  12905. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12906. org-outline-regexp)
  12907. " *\\(\\<\\("
  12908. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12909. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12910. (props (list 'face 'default
  12911. 'done-face 'org-agenda-done
  12912. 'undone-face 'default
  12913. 'mouse-face 'highlight
  12914. 'org-not-done-regexp org-not-done-regexp
  12915. 'org-todo-regexp org-todo-regexp
  12916. 'org-complex-heading-regexp org-complex-heading-regexp
  12917. 'help-echo
  12918. (format "mouse-2 or RET jump to org file %s"
  12919. (abbreviate-file-name
  12920. (or (buffer-file-name (buffer-base-buffer))
  12921. (buffer-name (buffer-base-buffer)))))))
  12922. (org-map-continue-from nil)
  12923. lspos tags tags-list
  12924. (tags-alist (list (cons 0 org-file-tags)))
  12925. (llast 0) rtn rtn1 level category i txt
  12926. todo marker entry priority
  12927. ts-date ts-date-type ts-date-pair)
  12928. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12929. (setq action (list 'lambda nil action)))
  12930. (save-excursion
  12931. (goto-char (point-min))
  12932. (when (eq action 'sparse-tree)
  12933. (org-overview)
  12934. (org-remove-occur-highlights))
  12935. (while (let (case-fold-search)
  12936. (re-search-forward re nil t))
  12937. (setq org-map-continue-from nil)
  12938. (catch :skip
  12939. (setq todo
  12940. ;; TODO: is the 1-2 difference a bug?
  12941. (when (match-end 1) (match-string-no-properties 2))
  12942. tags (when (match-end 4) (match-string-no-properties 4)))
  12943. (goto-char (setq lspos (match-beginning 0)))
  12944. (setq level (org-reduced-level (org-outline-level))
  12945. category (org-get-category))
  12946. (when (eq action 'agenda)
  12947. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12948. ts-date (car ts-date-pair)
  12949. ts-date-type (cdr ts-date-pair)))
  12950. (setq i llast llast level)
  12951. ;; remove tag lists from same and sublevels
  12952. (while (>= i level)
  12953. (when (setq entry (assoc i tags-alist))
  12954. (setq tags-alist (delete entry tags-alist)))
  12955. (setq i (1- i)))
  12956. ;; add the next tags
  12957. (when tags
  12958. (setq tags (org-split-string tags ":")
  12959. tags-alist
  12960. (cons (cons level tags) tags-alist)))
  12961. ;; compile tags for current headline
  12962. (setq tags-list
  12963. (if org-use-tag-inheritance
  12964. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12965. tags)
  12966. org-scanner-tags tags-list)
  12967. (when org-use-tag-inheritance
  12968. (setcdr (car tags-alist)
  12969. (mapcar (lambda (x)
  12970. (setq x (copy-sequence x))
  12971. (org-add-prop-inherited x))
  12972. (cdar tags-alist))))
  12973. (when (and tags org-use-tag-inheritance
  12974. (or (not (eq t org-use-tag-inheritance))
  12975. org-tags-exclude-from-inheritance))
  12976. ;; Selective inheritance, remove uninherited ones.
  12977. (setcdr (car tags-alist)
  12978. (org-remove-uninherited-tags (cdar tags-alist))))
  12979. (when (and
  12980. ;; eval matcher only when the todo condition is OK
  12981. (and (or (not todo-only) (member todo org-not-done-keywords))
  12982. (if (functionp matcher)
  12983. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12984. (funcall matcher todo tags-list level))
  12985. matcher))
  12986. ;; Call the skipper, but return t if it does not
  12987. ;; skip, so that the `and' form continues evaluating.
  12988. (progn
  12989. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12990. t)
  12991. ;; Check if timestamps are deselecting this entry
  12992. (or (not todo-only)
  12993. (and (member todo org-not-done-keywords)
  12994. (or (not org-agenda-tags-todo-honor-ignore-options)
  12995. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12996. ;; select this headline
  12997. (cond
  12998. ((eq action 'sparse-tree)
  12999. (and org-highlight-sparse-tree-matches
  13000. (org-get-heading) (match-end 0)
  13001. (org-highlight-new-match
  13002. (match-beginning 1) (match-end 1)))
  13003. (org-show-context 'tags-tree))
  13004. ((eq action 'agenda)
  13005. (setq txt (org-agenda-format-item
  13006. ""
  13007. (concat
  13008. (if (eq org-tags-match-list-sublevels 'indented)
  13009. (make-string (1- level) ?.) "")
  13010. (org-get-heading))
  13011. (make-string level ?\s)
  13012. category
  13013. tags-list)
  13014. priority (org-get-priority txt))
  13015. (goto-char lspos)
  13016. (setq marker (org-agenda-new-marker))
  13017. (org-add-props txt props
  13018. 'org-marker marker 'org-hd-marker marker 'org-category category
  13019. 'todo-state todo
  13020. 'ts-date ts-date
  13021. 'priority priority
  13022. 'type (concat "tagsmatch" ts-date-type))
  13023. (push txt rtn))
  13024. ((functionp action)
  13025. (setq org-map-continue-from nil)
  13026. (save-excursion
  13027. (setq rtn1 (funcall action))
  13028. (push rtn1 rtn)))
  13029. (t (user-error "Invalid action")))
  13030. ;; if we are to skip sublevels, jump to end of subtree
  13031. (unless org-tags-match-list-sublevels
  13032. (org-end-of-subtree t)
  13033. (backward-char 1))))
  13034. ;; Get the correct position from where to continue
  13035. (if org-map-continue-from
  13036. (goto-char org-map-continue-from)
  13037. (and (= (point) lspos) (end-of-line 1)))))
  13038. (when (and (eq action 'sparse-tree)
  13039. (not org-sparse-tree-open-archived-trees))
  13040. (org-hide-archived-subtrees (point-min) (point-max)))
  13041. (nreverse rtn)))
  13042. (defun org-remove-uninherited-tags (tags)
  13043. "Remove all tags that are not inherited from the list TAGS."
  13044. (cond
  13045. ((eq org-use-tag-inheritance t)
  13046. (if org-tags-exclude-from-inheritance
  13047. (org-delete-all org-tags-exclude-from-inheritance tags)
  13048. tags))
  13049. ((not org-use-tag-inheritance) nil)
  13050. ((stringp org-use-tag-inheritance)
  13051. (delq nil (mapcar
  13052. (lambda (x)
  13053. (if (and (string-match org-use-tag-inheritance x)
  13054. (not (member x org-tags-exclude-from-inheritance)))
  13055. x nil))
  13056. tags)))
  13057. ((listp org-use-tag-inheritance)
  13058. (delq nil (mapcar
  13059. (lambda (x)
  13060. (if (member x org-use-tag-inheritance) x nil))
  13061. tags)))))
  13062. (defun org-match-sparse-tree (&optional todo-only match)
  13063. "Create a sparse tree according to tags string MATCH.
  13064. MATCH can contain positive and negative selection of tags, like
  13065. \"+WORK+URGENT-WITHBOSS\".
  13066. If optional argument TODO-ONLY is non-nil, only select lines that are
  13067. also TODO lines."
  13068. (interactive "P")
  13069. (org-agenda-prepare-buffers (list (current-buffer)))
  13070. (let ((org--matcher-tags-todo-only todo-only))
  13071. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13072. org--matcher-tags-todo-only)))
  13073. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13074. (defvar org-cached-props nil)
  13075. (defun org-cached-entry-get (pom property)
  13076. (if (or (eq t org-use-property-inheritance)
  13077. (and (stringp org-use-property-inheritance)
  13078. (let ((case-fold-search t))
  13079. (org-string-match-p org-use-property-inheritance property)))
  13080. (and (listp org-use-property-inheritance)
  13081. (member-ignore-case property org-use-property-inheritance)))
  13082. ;; Caching is not possible, check it directly.
  13083. (org-entry-get pom property 'inherit)
  13084. ;; Get all properties, so we can do complicated checks easily.
  13085. (cdr (assoc-string property
  13086. (or org-cached-props
  13087. (setq org-cached-props (org-entry-properties pom)))
  13088. t))))
  13089. (defun org-global-tags-completion-table (&optional files)
  13090. "Return the list of all tags in all agenda buffer/files.
  13091. Optional FILES argument is a list of files which can be used
  13092. instead of the agenda files."
  13093. (save-excursion
  13094. (org-uniquify
  13095. (delq nil
  13096. (apply #'append
  13097. (mapcar
  13098. (lambda (file)
  13099. (set-buffer (find-file-noselect file))
  13100. (mapcar (lambda (x)
  13101. (and (stringp (car-safe x))
  13102. (list (car-safe x))))
  13103. (or org-current-tag-alist (org-get-buffer-tags))))
  13104. (if (car-safe files) files
  13105. (org-agenda-files))))))))
  13106. (defun org-make-tags-matcher (match)
  13107. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13108. Returns a cons of the selection string MATCH and a function
  13109. implementing the matcher.
  13110. The matcher is to be called at an Org entry, with point on the
  13111. headline, and returns non-nil if the entry matches the selection
  13112. string MATCH. It must be called with three arguments: the TODO
  13113. keyword at the entry (or nil if none), the list of all tags at
  13114. the entry including inherited ones and the reduced level of the
  13115. headline. Additionally, the category of the entry, if any, must
  13116. be specified as the text property `org-category' on the headline.
  13117. This function sets the variable `org--matcher-tags-todo-only' to
  13118. a non-nil value if the matcher restricts matching to TODO
  13119. entries, otherwise it is not touched.
  13120. See also `org-scan-tags'."
  13121. (unless match
  13122. ;; Get a new match request, with completion against the global
  13123. ;; tags table and the local tags in current buffer.
  13124. (let ((org-last-tags-completion-table
  13125. (org-uniquify
  13126. (delq nil (append (org-get-buffer-tags)
  13127. (org-global-tags-completion-table))))))
  13128. (setq match
  13129. (completing-read
  13130. "Match: "
  13131. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13132. (let ((match0 match)
  13133. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13134. (start 0)
  13135. tagsmatch todomatch tagsmatcher todomatcher)
  13136. ;; Expand group tags.
  13137. (setq match (org-tags-expand match))
  13138. ;; Check if there is a TODO part of this match, which would be the
  13139. ;; part after a "/". To make sure that this slash is not part of
  13140. ;; a property value to be matched against, we also check that
  13141. ;; there is no / after that slash. First, find the last slash.
  13142. (let ((s 0))
  13143. (while (string-match "/+" match s)
  13144. (setq start (match-beginning 0))
  13145. (setq s (match-end 0))))
  13146. (if (and (string-match "/+" match start)
  13147. (not (string-match-p "\"" match start)))
  13148. ;; Match contains also a TODO-matching request.
  13149. (progn
  13150. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13151. (setq todomatch (substring match (match-end 0)))
  13152. (when (string-match "\\`!" todomatch)
  13153. (setq org--matcher-tags-todo-only t)
  13154. (setq todomatch (substring todomatch 1)))
  13155. (when (string-match "\\`\\s-*\\'" todomatch)
  13156. (setq todomatch nil)))
  13157. ;; Only matching tags.
  13158. (setq tagsmatch match)
  13159. (setq todomatch nil))
  13160. ;; Make the tags matcher.
  13161. (when (org-string-nw-p tagsmatch)
  13162. (let ((orlist nil)
  13163. (orterms (org-split-string tagsmatch "|"))
  13164. term)
  13165. (while (setq term (pop orterms))
  13166. (while (and (equal (substring term -1) "\\") orterms)
  13167. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13168. (while (string-match re term)
  13169. (let* ((rest (substring term (match-end 0)))
  13170. (minus (and (match-end 1)
  13171. (equal (match-string 1 term) "-")))
  13172. (tag (save-match-data
  13173. (replace-regexp-in-string
  13174. "\\\\-" "-" (match-string 2 term))))
  13175. (regexp (eq (string-to-char tag) ?{))
  13176. (levelp (match-end 4))
  13177. (propp (match-end 5))
  13178. (mm
  13179. (cond
  13180. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13181. (levelp
  13182. `(,(org-op-to-function (match-string 3 term))
  13183. level
  13184. ,(string-to-number (match-string 4 term))))
  13185. (propp
  13186. (let* ((gv (pcase (upcase (match-string 5 term))
  13187. ("CATEGORY"
  13188. '(get-text-property (point) 'org-category))
  13189. ("TODO" 'todo)
  13190. (p `(org-cached-entry-get nil ,p))))
  13191. (pv (match-string 7 term))
  13192. (regexp (eq (string-to-char pv) ?{))
  13193. (strp (eq (string-to-char pv) ?\"))
  13194. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13195. (po (org-op-to-function (match-string 6 term)
  13196. (if timep 'time strp))))
  13197. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13198. (when timep (setq pv (org-matcher-time pv)))
  13199. (cond ((and regexp (eq po 'org<>))
  13200. `(not (string-match ,pv (or ,gv ""))))
  13201. (regexp `(string-match ,pv (or ,gv "")))
  13202. (strp `(,po (or ,gv "") ,pv))
  13203. (t
  13204. `(,po
  13205. (string-to-number (or ,gv ""))
  13206. ,(string-to-number pv))))))
  13207. (t `(member ,tag tags-list)))))
  13208. (push (if minus `(not ,mm) mm) tagsmatcher)
  13209. (setq term rest)))
  13210. (push `(and ,@tagsmatcher) orlist)
  13211. (setq tagsmatcher nil))
  13212. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13213. ;; Make the TODO matcher.
  13214. (when (org-string-nw-p todomatch)
  13215. (let ((orlist nil))
  13216. (dolist (term (org-split-string todomatch "|"))
  13217. (while (string-match re term)
  13218. (let* ((minus (and (match-end 1)
  13219. (equal (match-string 1 term) "-")))
  13220. (kwd (match-string 2 term))
  13221. (regexp (eq (string-to-char kwd) ?{))
  13222. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13223. `(equal todo ,kwd))))
  13224. (push (if minus `(not ,mm) mm) todomatcher))
  13225. (setq term (substring term (match-end 0))))
  13226. (push (if (> (length todomatcher) 1)
  13227. (cons 'and todomatcher)
  13228. (car todomatcher))
  13229. orlist)
  13230. (setq todomatcher nil))
  13231. (setq todomatcher (cons 'or orlist))))
  13232. ;; Return the string and function of the matcher. If no
  13233. ;; tags-specific or todo-specific matcher exists, match
  13234. ;; everything.
  13235. (let ((matcher (if (and tagsmatcher todomatcher)
  13236. `(and ,tagsmatcher ,todomatcher)
  13237. (or tagsmatcher todomatcher t))))
  13238. (when org--matcher-tags-todo-only
  13239. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13240. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13241. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13242. "Expand group tags in MATCH.
  13243. This replaces every group tag in MATCH with a regexp tag search.
  13244. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13245. will be replaced like this:
  13246. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13247. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13248. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13249. Replacing by a regexp preserves the structure of the match.
  13250. E.g., this expansion
  13251. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13252. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13253. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13254. A group tag in MATCH can contain regular expressions of its own.
  13255. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13256. will be replaced like this:
  13257. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13258. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13259. assumed to be a single group tag, and the function will return
  13260. the list of tags in this group.
  13261. When DOWNCASE is non-nil, expand downcased TAGS."
  13262. (if org-group-tags
  13263. (let* ((case-fold-search t)
  13264. (stable org-mode-syntax-table)
  13265. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13266. (taggroups (if downcased
  13267. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13268. taggroups)
  13269. taggroups))
  13270. (taggroups-keys (mapcar #'car taggroups))
  13271. (return-match (if downcased (downcase match) match))
  13272. (count 0)
  13273. (work-already-expanded tags-already-expanded)
  13274. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13275. ;; @ and _ are allowed as word-components in tags.
  13276. (modify-syntax-entry ?@ "w" stable)
  13277. (modify-syntax-entry ?_ "w" stable)
  13278. ;; Temporarily replace regexp-expressions in the match-expression.
  13279. (while (string-match "{.+?}" return-match)
  13280. (cl-incf count)
  13281. (push (match-string 0 return-match) regexps-in-match)
  13282. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13283. (while (and taggroups-keys
  13284. (with-syntax-table stable
  13285. (string-match
  13286. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13287. (regexp-opt taggroups-keys) "\\>\\)")
  13288. return-match)))
  13289. (let* ((dir (match-string 1 return-match))
  13290. (tag (match-string 2 return-match))
  13291. (tag (if downcased (downcase tag) tag)))
  13292. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13293. (member tag work-already-expanded))
  13294. (setq tags-in-group (assoc tag taggroups))
  13295. (push tag work-already-expanded)
  13296. ;; Recursively expand each tag in the group, if the tag hasn't
  13297. ;; already been expanded. Restore the match-data after all recursive calls.
  13298. (save-match-data
  13299. (let (tags-expanded)
  13300. (dolist (x (cdr tags-in-group))
  13301. (if (and (member x taggroups-keys)
  13302. (not (member x work-already-expanded)))
  13303. (setq tags-expanded
  13304. (delete-dups
  13305. (append
  13306. (org-tags-expand x t downcased
  13307. work-already-expanded)
  13308. tags-expanded)))
  13309. (setq tags-expanded
  13310. (append (list x) tags-expanded)))
  13311. (setq work-already-expanded
  13312. (delete-dups
  13313. (append tags-expanded
  13314. work-already-expanded))))
  13315. (setq tags-in-group
  13316. (delete-dups (cons (car tags-in-group)
  13317. tags-expanded)))))
  13318. ;; Filter tag-regexps from tags.
  13319. (setq regexp-in-group-escaped
  13320. (delq nil (mapcar (lambda (x)
  13321. (if (stringp x)
  13322. (and (equal "{" (substring x 0 1))
  13323. (equal "}" (substring x -1))
  13324. x)
  13325. x))
  13326. tags-in-group))
  13327. regexp-in-group
  13328. (mapcar (lambda (x)
  13329. (substring x 1 -1))
  13330. regexp-in-group-escaped)
  13331. tags-in-group
  13332. (delq nil (mapcar (lambda (x)
  13333. (if (stringp x)
  13334. (and (not (equal "{" (substring x 0 1)))
  13335. (not (equal "}" (substring x -1)))
  13336. x)
  13337. x))
  13338. tags-in-group)))
  13339. ;; If single-as-list, do no more in the while-loop.
  13340. (if (not single-as-list)
  13341. (progn
  13342. (when regexp-in-group
  13343. (setq regexp-in-group
  13344. (concat "\\|"
  13345. (mapconcat 'identity regexp-in-group
  13346. "\\|"))))
  13347. (setq tags-in-group
  13348. (concat dir
  13349. "{\\<"
  13350. (regexp-opt tags-in-group)
  13351. "\\>"
  13352. regexp-in-group
  13353. "}"))
  13354. (when (stringp tags-in-group)
  13355. (org-add-props tags-in-group '(grouptag t)))
  13356. (setq return-match
  13357. (replace-match tags-in-group t t return-match)))
  13358. (setq tags-in-group
  13359. (append regexp-in-group-escaped tags-in-group))))
  13360. (setq taggroups-keys (delete tag taggroups-keys))))
  13361. ;; Add the regular expressions back into the match-expression again.
  13362. (while regexps-in-match
  13363. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13364. (pop regexps-in-match)
  13365. return-match t t))
  13366. (cl-decf count))
  13367. (if single-as-list
  13368. (if tags-in-group tags-in-group (list return-match))
  13369. return-match))
  13370. (if single-as-list
  13371. (list (if downcased (downcase match) match))
  13372. match)))
  13373. (defun org-op-to-function (op &optional stringp)
  13374. "Turn an operator into the appropriate function."
  13375. (setq op
  13376. (cond
  13377. ((equal op "<" ) '(< string< org-time<))
  13378. ((equal op ">" ) '(> org-string> org-time>))
  13379. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13380. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13381. ((member op '("=" "==")) '(= string= org-time=))
  13382. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13383. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13384. (defun org<> (a b) (not (= a b)))
  13385. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13386. (defun org-string>= (a b) (not (string< a b)))
  13387. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13388. (defun org-string<> (a b) (not (string= a b)))
  13389. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13390. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13391. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13392. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13393. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13394. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13395. (defun org-2ft (s)
  13396. "Convert S to a floating point time.
  13397. If S is already a number, just return it. If it is a string, parse
  13398. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13399. (cond
  13400. ((numberp s) s)
  13401. ((stringp s)
  13402. (condition-case nil
  13403. (float-time (apply 'encode-time (org-parse-time-string s)))
  13404. (error 0.)))
  13405. (t 0.)))
  13406. (defun org-time-today ()
  13407. "Time in seconds today at 0:00.
  13408. Returns the float number of seconds since the beginning of the
  13409. epoch to the beginning of today (00:00)."
  13410. (float-time (apply 'encode-time
  13411. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13412. (defun org-matcher-time (s)
  13413. "Interpret a time comparison value."
  13414. (save-match-data
  13415. (cond
  13416. ((string= s "<now>") (float-time))
  13417. ((string= s "<today>") (org-time-today))
  13418. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13419. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13420. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13421. (+ (org-time-today)
  13422. (* (string-to-number (match-string 1 s))
  13423. (cdr (assoc (match-string 2 s)
  13424. '(("d" . 86400.0) ("w" . 604800.0)
  13425. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13426. (t (org-2ft s)))))
  13427. (defun org-match-any-p (re list)
  13428. "Does re match any element of list?"
  13429. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13430. (delq nil list))
  13431. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13432. (defvar org-tags-overlay (make-overlay 1 1))
  13433. (delete-overlay org-tags-overlay)
  13434. (defun org-get-local-tags-at (&optional pos)
  13435. "Get a list of tags defined in the current headline."
  13436. (org-get-tags-at pos 'local))
  13437. (defun org-get-local-tags ()
  13438. "Get a list of tags defined in the current headline."
  13439. (org-get-tags-at nil 'local))
  13440. (defun org-get-tags-at (&optional pos local)
  13441. "Get a list of all headline tags applicable at POS.
  13442. POS defaults to point. If tags are inherited, the list contains
  13443. the targets in the same sequence as the headlines appear, i.e.
  13444. the tags of the current headline come last.
  13445. When LOCAL is non-nil, only return tags from the current headline,
  13446. ignore inherited ones."
  13447. (interactive)
  13448. (if (and org-trust-scanner-tags
  13449. (or (not pos) (equal pos (point)))
  13450. (not local))
  13451. org-scanner-tags
  13452. (let (tags ltags lastpos parent)
  13453. (save-excursion
  13454. (save-restriction
  13455. (widen)
  13456. (goto-char (or pos (point)))
  13457. (save-match-data
  13458. (catch 'done
  13459. (condition-case nil
  13460. (progn
  13461. (org-back-to-heading t)
  13462. (while (not (equal lastpos (point)))
  13463. (setq lastpos (point))
  13464. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13465. (setq ltags (org-split-string
  13466. (match-string-no-properties 1) ":"))
  13467. (when parent
  13468. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13469. (setq tags (append
  13470. (if parent
  13471. (org-remove-uninherited-tags ltags)
  13472. ltags)
  13473. tags)))
  13474. (or org-use-tag-inheritance (throw 'done t))
  13475. (when local (throw 'done t))
  13476. (or (org-up-heading-safe) (error nil))
  13477. (setq parent t)))
  13478. (error nil)))))
  13479. (if local
  13480. tags
  13481. (reverse (delete-dups
  13482. (reverse (append
  13483. (org-remove-uninherited-tags
  13484. org-file-tags)
  13485. tags)))))))))
  13486. (defun org-add-prop-inherited (s)
  13487. (add-text-properties 0 (length s) '(inherited t) s)
  13488. s)
  13489. (defun org-toggle-tag (tag &optional onoff)
  13490. "Toggle the tag TAG for the current line.
  13491. If ONOFF is `on' or `off', don't toggle but set to this state."
  13492. (let (res current)
  13493. (save-excursion
  13494. (org-back-to-heading t)
  13495. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13496. (point-at-eol) t)
  13497. (progn
  13498. (setq current (match-string 1))
  13499. (replace-match ""))
  13500. (setq current ""))
  13501. (setq current (nreverse (org-split-string current ":")))
  13502. (cond
  13503. ((eq onoff 'on)
  13504. (setq res t)
  13505. (or (member tag current) (push tag current)))
  13506. ((eq onoff 'off)
  13507. (or (not (member tag current)) (setq current (delete tag current))))
  13508. (t (if (member tag current)
  13509. (setq current (delete tag current))
  13510. (setq res t)
  13511. (push tag current))))
  13512. (end-of-line 1)
  13513. (if current
  13514. (progn
  13515. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13516. (org-set-tags nil t))
  13517. (delete-horizontal-space))
  13518. (run-hooks 'org-after-tags-change-hook))
  13519. res))
  13520. (defun org-align-tags-here (to-col)
  13521. ;; Assumes that this is a headline
  13522. "Align tags on the current headline to TO-COL."
  13523. (let ((pos (point)) (col (current-column)) ncol tags-l p)
  13524. (beginning-of-line 1)
  13525. (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13526. (< pos (match-beginning 2)))
  13527. (progn
  13528. (setq tags-l (string-width (match-string 2)))
  13529. (goto-char (match-beginning 1))
  13530. (insert " ")
  13531. (delete-region (point) (1+ (match-beginning 2)))
  13532. (setq ncol (max (current-column)
  13533. (1+ col)
  13534. (if (> to-col 0)
  13535. to-col
  13536. (- (abs to-col) tags-l))))
  13537. (setq p (point))
  13538. (insert (make-string (- ncol (current-column)) ?\ ))
  13539. (setq ncol (current-column))
  13540. (when indent-tabs-mode (tabify p (point-at-eol)))
  13541. (org-move-to-column (min ncol col)))
  13542. (goto-char pos))))
  13543. (defun org-set-tags-command (&optional arg just-align)
  13544. "Call the set-tags command for the current entry."
  13545. (interactive "P")
  13546. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13547. (org-set-tags arg just-align)
  13548. (save-excursion
  13549. (unless (and (org-region-active-p)
  13550. org-loop-over-headlines-in-active-region)
  13551. (org-back-to-heading t))
  13552. (org-set-tags arg just-align))))
  13553. (defun org-set-tags-to (data)
  13554. "Set the tags of the current entry to DATA, replacing the current tags.
  13555. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13556. If DATA is nil or the empty string, any tags will be removed."
  13557. (interactive "sTags: ")
  13558. (setq data
  13559. (cond
  13560. ((eq data nil) "")
  13561. ((equal data "") "")
  13562. ((stringp data)
  13563. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13564. ":"))
  13565. ((listp data)
  13566. (concat ":" (mapconcat 'identity data ":") ":"))))
  13567. (when data
  13568. (save-excursion
  13569. (org-back-to-heading t)
  13570. (when (looking-at org-complex-heading-regexp)
  13571. (if (match-end 5)
  13572. (progn
  13573. (goto-char (match-beginning 5))
  13574. (insert data)
  13575. (delete-region (point) (point-at-eol))
  13576. (org-set-tags nil 'align))
  13577. (goto-char (point-at-eol))
  13578. (insert " " data)
  13579. (org-set-tags nil 'align)))
  13580. (beginning-of-line 1)
  13581. (when (looking-at ".*?\\([ \t]+\\)$")
  13582. (delete-region (match-beginning 1) (match-end 1))))))
  13583. (defun org-align-all-tags ()
  13584. "Align the tags in all headings."
  13585. (interactive)
  13586. (save-excursion
  13587. (or (ignore-errors (org-back-to-heading t))
  13588. (outline-next-heading))
  13589. (if (org-at-heading-p)
  13590. (org-set-tags t)
  13591. (message "No headings"))))
  13592. (defvar org-indent-indentation-per-level)
  13593. (defun org-set-tags (&optional arg just-align)
  13594. "Set the tags for the current headline.
  13595. With prefix ARG, realign all tags in headings in the current buffer.
  13596. When JUST-ALIGN is non-nil, only align tags."
  13597. (interactive "P")
  13598. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13599. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13600. 'region-start-level
  13601. 'region))
  13602. org-loop-over-headlines-in-active-region)
  13603. (org-map-entries
  13604. ;; We don't use ARG and JUST-ALIGN here because these args
  13605. ;; are not useful when looping over headlines.
  13606. #'org-set-tags
  13607. org-loop-over-headlines-in-active-region
  13608. cl
  13609. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13610. (let ((org-setting-tags t))
  13611. (if arg
  13612. (save-excursion
  13613. (goto-char (point-min))
  13614. (while (re-search-forward org-outline-regexp-bol nil t)
  13615. (org-set-tags nil t)
  13616. (end-of-line))
  13617. (message "All tags realigned to column %d" org-tags-column))
  13618. (let* ((current (org-get-tags-string))
  13619. (col (current-column))
  13620. (tags
  13621. (if just-align current
  13622. ;; Get a new set of tags from the user.
  13623. (save-excursion
  13624. (let* ((seen)
  13625. (table
  13626. (setq
  13627. org-last-tags-completion-table
  13628. ;; Uniquify tags in alists, yet preserve
  13629. ;; structure (i.e., keywords).
  13630. (delq nil
  13631. (mapcar
  13632. (lambda (pair)
  13633. (let ((head (car pair)))
  13634. (cond ((symbolp head) pair)
  13635. ((member head seen) nil)
  13636. (t (push head seen)
  13637. pair))))
  13638. (append
  13639. (or org-current-tag-alist
  13640. (org-get-buffer-tags))
  13641. (and
  13642. org-complete-tags-always-offer-all-agenda-tags
  13643. (org-global-tags-completion-table
  13644. (org-agenda-files))))))))
  13645. (current-tags (org-split-string current ":"))
  13646. (inherited-tags
  13647. (nreverse (nthcdr (length current-tags)
  13648. (nreverse (org-get-tags-at))))))
  13649. (replace-regexp-in-string
  13650. "\\([-+&]+\\|,\\)"
  13651. ":"
  13652. (if (or (eq t org-use-fast-tag-selection)
  13653. (and org-use-fast-tag-selection
  13654. (delq nil (mapcar #'cdr table))))
  13655. (org-fast-tag-selection
  13656. current-tags inherited-tags table
  13657. (and org-fast-tag-selection-include-todo
  13658. org-todo-key-alist))
  13659. (let ((org-add-colon-after-tag-completion
  13660. (< 1 (length table))))
  13661. (org-trim
  13662. (completing-read
  13663. "Tags: "
  13664. #'org-tags-completion-function
  13665. nil nil current 'org-tags-history))))))))))
  13666. (when org-tags-sort-function
  13667. (setq tags
  13668. (mapconcat
  13669. #'identity
  13670. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13671. org-tags-sort-function)
  13672. ":")))
  13673. (if (not (org-string-nw-p tags)) (setq tags "")
  13674. (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
  13675. (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
  13676. ;; Insert new tags at the correct column
  13677. (beginning-of-line)
  13678. (let ((level (if (looking-at org-outline-regexp)
  13679. (- (match-end 0) (point) 1)
  13680. 1)))
  13681. (cond
  13682. ((and (equal current "") (equal tags "")))
  13683. ((re-search-forward
  13684. (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
  13685. (line-end-position)
  13686. t)
  13687. (if (equal tags "") (replace-match "" t t)
  13688. (goto-char (match-beginning 0))
  13689. (let* ((c0 (current-column))
  13690. ;; Compute offset for the case of org-indent-mode
  13691. ;; active.
  13692. (di (if (bound-and-true-p org-indent-mode)
  13693. (* (1- org-indent-indentation-per-level)
  13694. (1- level))
  13695. 0))
  13696. (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
  13697. (tc (+ org-tags-column
  13698. (if (> org-tags-column 0) (- di) di)))
  13699. (c1 (max (1+ c0)
  13700. (if (> tc 0) tc
  13701. (- (- tc) (string-width tags)))))
  13702. (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
  13703. (replace-match rpl t t)
  13704. (when indent-tabs-mode (tabify p0 (point))))))
  13705. (t (error "Tags alignment failed"))))
  13706. (org-move-to-column col))
  13707. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13708. (defun org-change-tag-in-region (beg end tag off)
  13709. "Add or remove TAG for each entry in the region.
  13710. This works in the agenda, and also in an org-mode buffer."
  13711. (interactive
  13712. (list (region-beginning) (region-end)
  13713. (let ((org-last-tags-completion-table
  13714. (if (derived-mode-p 'org-mode)
  13715. (org-uniquify
  13716. (delq nil (append (org-get-buffer-tags)
  13717. (org-global-tags-completion-table))))
  13718. (org-global-tags-completion-table))))
  13719. (completing-read
  13720. "Tag: " 'org-tags-completion-function nil nil nil
  13721. 'org-tags-history))
  13722. (progn
  13723. (message "[s]et or [r]emove? ")
  13724. (equal (read-char-exclusive) ?r))))
  13725. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13726. (let ((agendap (equal major-mode 'org-agenda-mode))
  13727. l1 l2 m buf pos newhead (cnt 0))
  13728. (goto-char end)
  13729. (setq l2 (1- (org-current-line)))
  13730. (goto-char beg)
  13731. (setq l1 (org-current-line))
  13732. (cl-loop for l from l1 to l2 do
  13733. (org-goto-line l)
  13734. (setq m (get-text-property (point) 'org-hd-marker))
  13735. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13736. (and agendap m))
  13737. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13738. pos (if agendap m (point)))
  13739. (with-current-buffer buf
  13740. (save-excursion
  13741. (save-restriction
  13742. (goto-char pos)
  13743. (setq cnt (1+ cnt))
  13744. (org-toggle-tag tag (if off 'off 'on))
  13745. (setq newhead (org-get-heading)))))
  13746. (and agendap (org-agenda-change-all-lines newhead m))))
  13747. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13748. (defun org-tags-completion-function (string _predicate &optional flag)
  13749. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13750. (confirm (lambda (x) (stringp (car x)))))
  13751. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13752. (setq s1 (match-string 1 string)
  13753. s2 (match-string 2 string))
  13754. (setq s1 "" s2 string))
  13755. (cond
  13756. ((eq flag nil)
  13757. ;; try completion
  13758. (setq rtn (try-completion s2 ctable confirm))
  13759. (when (stringp rtn)
  13760. (setq rtn
  13761. (concat s1 s2 (substring rtn (length s2))
  13762. (if (and org-add-colon-after-tag-completion
  13763. (assoc rtn ctable))
  13764. ":" ""))))
  13765. rtn)
  13766. ((eq flag t)
  13767. ;; all-completions
  13768. (all-completions s2 ctable confirm))
  13769. ((eq flag 'lambda)
  13770. ;; exact match?
  13771. (assoc s2 ctable)))))
  13772. (defun org-fast-tag-insert (kwd tags face &optional end)
  13773. "Insert KDW, and the TAGS, the latter with face FACE.
  13774. Also insert END."
  13775. (insert (format "%-12s" (concat kwd ":"))
  13776. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13777. (or end "")))
  13778. (defun org-fast-tag-show-exit (flag)
  13779. (save-excursion
  13780. (org-goto-line 3)
  13781. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13782. (replace-match ""))
  13783. (when flag
  13784. (end-of-line 1)
  13785. (org-move-to-column (- (window-width) 19) t)
  13786. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13787. (defun org-set-current-tags-overlay (current prefix)
  13788. "Add an overlay to CURRENT tag with PREFIX."
  13789. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13790. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13791. (org-overlay-display org-tags-overlay (concat prefix s))))
  13792. (defvar org-last-tag-selection-key nil)
  13793. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13794. "Fast tag selection with single keys.
  13795. CURRENT is the current list of tags in the headline, INHERITED is the
  13796. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13797. possibly with grouping information. TODO-TABLE is a similar table with
  13798. TODO keywords, should these have keys assigned to them.
  13799. If the keys are nil, a-z are automatically assigned.
  13800. Returns the new tags string, or nil to not change the current settings."
  13801. (let* ((fulltable (append table todo-table))
  13802. (maxlen (apply 'max (mapcar
  13803. (lambda (x)
  13804. (if (stringp (car x)) (string-width (car x)) 0))
  13805. fulltable)))
  13806. (buf (current-buffer))
  13807. (expert (eq org-fast-tag-selection-single-key 'expert))
  13808. (buffer-tags nil)
  13809. (fwidth (+ maxlen 3 1 3))
  13810. (ncol (/ (- (window-width) 4) fwidth))
  13811. (i-face 'org-done)
  13812. (c-face 'org-todo)
  13813. tg cnt e c char c1 c2 ntable tbl rtn
  13814. ov-start ov-end ov-prefix
  13815. (exit-after-next org-fast-tag-selection-single-key)
  13816. (done-keywords org-done-keywords)
  13817. groups ingroup intaggroup)
  13818. (save-excursion
  13819. (beginning-of-line 1)
  13820. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13821. (setq ov-start (match-beginning 1)
  13822. ov-end (match-end 1)
  13823. ov-prefix "")
  13824. (setq ov-start (1- (point-at-eol))
  13825. ov-end (1+ ov-start))
  13826. (skip-chars-forward "^\n\r")
  13827. (setq ov-prefix
  13828. (concat
  13829. (buffer-substring (1- (point)) (point))
  13830. (if (> (current-column) org-tags-column)
  13831. " "
  13832. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13833. (move-overlay org-tags-overlay ov-start ov-end)
  13834. (save-window-excursion
  13835. (if expert
  13836. (set-buffer (get-buffer-create " *Org tags*"))
  13837. (delete-other-windows)
  13838. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13839. (org-switch-to-buffer-other-window " *Org tags*"))
  13840. (erase-buffer)
  13841. (setq-local org-done-keywords done-keywords)
  13842. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13843. (org-fast-tag-insert "Current" current c-face "\n\n")
  13844. (org-fast-tag-show-exit exit-after-next)
  13845. (org-set-current-tags-overlay current ov-prefix)
  13846. (setq tbl fulltable char ?a cnt 0)
  13847. (while (setq e (pop tbl))
  13848. (cond
  13849. ((eq (car e) :startgroup)
  13850. (push '() groups) (setq ingroup t)
  13851. (unless (zerop cnt)
  13852. (setq cnt 0)
  13853. (insert "\n"))
  13854. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13855. ((eq (car e) :endgroup)
  13856. (setq ingroup nil cnt 0)
  13857. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13858. ((eq (car e) :startgrouptag)
  13859. (setq intaggroup t)
  13860. (unless (zerop cnt)
  13861. (setq cnt 0)
  13862. (insert "\n"))
  13863. (insert "[ "))
  13864. ((eq (car e) :endgrouptag)
  13865. (setq intaggroup nil cnt 0)
  13866. (insert "]\n"))
  13867. ((equal e '(:newline))
  13868. (unless (zerop cnt)
  13869. (setq cnt 0)
  13870. (insert "\n")
  13871. (setq e (car tbl))
  13872. (while (equal (car tbl) '(:newline))
  13873. (insert "\n")
  13874. (setq tbl (cdr tbl)))))
  13875. ((equal e '(:grouptags)) (insert " : "))
  13876. (t
  13877. (setq tg (copy-sequence (car e)) c2 nil)
  13878. (if (cdr e)
  13879. (setq c (cdr e))
  13880. ;; automatically assign a character.
  13881. (setq c1 (string-to-char
  13882. (downcase (substring
  13883. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13884. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13885. (while (or (rassoc char ntable) (rassoc char table))
  13886. (setq char (1+ char)))
  13887. (setq c2 c1))
  13888. (setq c (or c2 char)))
  13889. (when ingroup (push tg (car groups)))
  13890. (setq tg (org-add-props tg nil 'face
  13891. (cond
  13892. ((not (assoc tg table))
  13893. (org-get-todo-face tg))
  13894. ((member tg current) c-face)
  13895. ((member tg inherited) i-face))))
  13896. (when (equal (caar tbl) :grouptags)
  13897. (org-add-props tg nil 'face 'org-tag-group))
  13898. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13899. (insert "[" c "] " tg (make-string
  13900. (- fwidth 4 (length tg)) ?\ ))
  13901. (push (cons tg c) ntable)
  13902. (when (= (cl-incf cnt) ncol)
  13903. (insert "\n")
  13904. (when (or ingroup intaggroup) (insert " "))
  13905. (setq cnt 0)))))
  13906. (setq ntable (nreverse ntable))
  13907. (insert "\n")
  13908. (goto-char (point-min))
  13909. (unless expert (org-fit-window-to-buffer))
  13910. (setq rtn
  13911. (catch 'exit
  13912. (while t
  13913. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13914. (if (not groups) "no " "")
  13915. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13916. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13917. (setq org-last-tag-selection-key c)
  13918. (cond
  13919. ((= c ?\r) (throw 'exit t))
  13920. ((= c ?!)
  13921. (setq groups (not groups))
  13922. (goto-char (point-min))
  13923. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13924. ((= c ?\C-c)
  13925. (if (not expert)
  13926. (org-fast-tag-show-exit
  13927. (setq exit-after-next (not exit-after-next)))
  13928. (setq expert nil)
  13929. (delete-other-windows)
  13930. (set-window-buffer (split-window-vertically) " *Org tags*")
  13931. (org-switch-to-buffer-other-window " *Org tags*")
  13932. (org-fit-window-to-buffer)))
  13933. ((or (= c ?\C-g)
  13934. (and (= c ?q) (not (rassoc c ntable))))
  13935. (delete-overlay org-tags-overlay)
  13936. (setq quit-flag t))
  13937. ((= c ?\ )
  13938. (setq current nil)
  13939. (when exit-after-next (setq exit-after-next 'now)))
  13940. ((= c ?\t)
  13941. (condition-case nil
  13942. (setq tg (completing-read
  13943. "Tag: "
  13944. (or buffer-tags
  13945. (with-current-buffer buf
  13946. (setq buffer-tags
  13947. (org-get-buffer-tags))))))
  13948. (quit (setq tg "")))
  13949. (when (string-match "\\S-" tg)
  13950. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13951. (if (member tg current)
  13952. (setq current (delete tg current))
  13953. (push tg current)))
  13954. (when exit-after-next (setq exit-after-next 'now)))
  13955. ((setq e (rassoc c todo-table) tg (car e))
  13956. (with-current-buffer buf
  13957. (save-excursion (org-todo tg)))
  13958. (when exit-after-next (setq exit-after-next 'now)))
  13959. ((setq e (rassoc c ntable) tg (car e))
  13960. (if (member tg current)
  13961. (setq current (delete tg current))
  13962. (cl-loop for g in groups do
  13963. (when (member tg g)
  13964. (dolist (x g) (setq current (delete x current)))))
  13965. (push tg current))
  13966. (when exit-after-next (setq exit-after-next 'now))))
  13967. ;; Create a sorted list
  13968. (setq current
  13969. (sort current
  13970. (lambda (a b)
  13971. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13972. (when (eq exit-after-next 'now) (throw 'exit t))
  13973. (goto-char (point-min))
  13974. (beginning-of-line 2)
  13975. (delete-region (point) (point-at-eol))
  13976. (org-fast-tag-insert "Current" current c-face)
  13977. (org-set-current-tags-overlay current ov-prefix)
  13978. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13979. (setq tg (match-string 1))
  13980. (add-text-properties
  13981. (match-beginning 1) (match-end 1)
  13982. (list 'face
  13983. (cond
  13984. ((member tg current) c-face)
  13985. ((member tg inherited) i-face)
  13986. (t (get-text-property (match-beginning 1) 'face))))))
  13987. (goto-char (point-min)))))
  13988. (delete-overlay org-tags-overlay)
  13989. (if rtn
  13990. (mapconcat 'identity current ":")
  13991. nil))))
  13992. (defun org-get-tags-string ()
  13993. "Get the TAGS string in the current headline."
  13994. (unless (org-at-heading-p t)
  13995. (user-error "Not on a heading"))
  13996. (save-excursion
  13997. (beginning-of-line 1)
  13998. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13999. (match-string-no-properties 1)
  14000. "")))
  14001. (defun org-get-tags ()
  14002. "Get the list of tags specified in the current headline."
  14003. (org-split-string (org-get-tags-string) ":"))
  14004. (defun org-get-buffer-tags ()
  14005. "Get a table of all tags used in the buffer, for completion."
  14006. (org-with-wide-buffer
  14007. (goto-char (point-min))
  14008. (let ((tag-re (concat org-outline-regexp-bol
  14009. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14010. tags)
  14011. (while (re-search-forward tag-re nil t)
  14012. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14013. (push tag tags)))
  14014. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14015. ;;;; The mapping API
  14016. (defvar org-agenda-skip-comment-trees)
  14017. (defvar org-agenda-skip-function)
  14018. (defun org-map-entries (func &optional match scope &rest skip)
  14019. "Call FUNC at each headline selected by MATCH in SCOPE.
  14020. FUNC is a function or a lisp form. The function will be called without
  14021. arguments, with the cursor positioned at the beginning of the headline.
  14022. The return values of all calls to the function will be collected and
  14023. returned as a list.
  14024. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14025. does not need to preserve point. After evaluation, the cursor will be
  14026. moved to the end of the line (presumably of the headline of the
  14027. processed entry) and search continues from there. Under some
  14028. circumstances, this may not produce the wanted results. For example,
  14029. if you have removed (e.g. archived) the current (sub)tree it could
  14030. mean that the next entry will be skipped entirely. In such cases, you
  14031. can specify the position from where search should continue by making
  14032. FUNC set the variable `org-map-continue-from' to the desired buffer
  14033. position.
  14034. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14035. Only headlines that are matched by this query will be considered during
  14036. the iteration. When MATCH is nil or t, all headlines will be
  14037. visited by the iteration.
  14038. SCOPE determines the scope of this command. It can be any of:
  14039. nil The current buffer, respecting the restriction if any
  14040. tree The subtree started with the entry at point
  14041. region The entries within the active region, if any
  14042. region-start-level
  14043. The entries within the active region, but only those at
  14044. the same level than the first one.
  14045. file The current buffer, without restriction
  14046. file-with-archives
  14047. The current buffer, and any archives associated with it
  14048. agenda All agenda files
  14049. agenda-with-archives
  14050. All agenda files with any archive files associated with them
  14051. \(file1 file2 ...)
  14052. If this is a list, all files in the list will be scanned
  14053. The remaining args are treated as settings for the skipping facilities of
  14054. the scanner. The following items can be given here:
  14055. archive skip trees with the archive tag
  14056. comment skip trees with the COMMENT keyword
  14057. function or Emacs Lisp form:
  14058. will be used as value for `org-agenda-skip-function', so
  14059. whenever the function returns a position, FUNC will not be
  14060. called for that entry and search will continue from the
  14061. position returned
  14062. If your function needs to retrieve the tags including inherited tags
  14063. at the *current* entry, you can use the value of the variable
  14064. `org-scanner-tags' which will be much faster than getting the value
  14065. with `org-get-tags-at'. If your function gets properties with
  14066. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14067. to t around the call to `org-entry-properties' to get the same speedup.
  14068. Note that if your function moves around to retrieve tags and properties at
  14069. a *different* entry, you cannot use these techniques."
  14070. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14071. (not (org-region-active-p)))
  14072. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14073. (org-agenda-skip-archived-trees (memq 'archive skip))
  14074. (org-agenda-skip-comment-trees (memq 'comment skip))
  14075. (org-agenda-skip-function
  14076. (car (org-delete-all '(comment archive) skip)))
  14077. (org-tags-match-list-sublevels t)
  14078. (start-level (eq scope 'region-start-level))
  14079. matcher res
  14080. org-todo-keywords-for-agenda
  14081. org-done-keywords-for-agenda
  14082. org-todo-keyword-alist-for-agenda
  14083. org-tag-alist-for-agenda
  14084. org--matcher-tags-todo-only)
  14085. (cond
  14086. ((eq match t) (setq matcher t))
  14087. ((eq match nil) (setq matcher t))
  14088. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14089. (save-excursion
  14090. (save-restriction
  14091. (cond ((eq scope 'tree)
  14092. (org-back-to-heading t)
  14093. (org-narrow-to-subtree)
  14094. (setq scope nil))
  14095. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14096. (org-region-active-p))
  14097. ;; If needed, set start-level to a string like "2"
  14098. (when start-level
  14099. (save-excursion
  14100. (goto-char (region-beginning))
  14101. (unless (org-at-heading-p) (outline-next-heading))
  14102. (setq start-level (org-current-level))))
  14103. (narrow-to-region (region-beginning)
  14104. (save-excursion
  14105. (goto-char (region-end))
  14106. (unless (and (bolp) (org-at-heading-p))
  14107. (outline-next-heading))
  14108. (point)))
  14109. (setq scope nil)))
  14110. (if (not scope)
  14111. (progn
  14112. (org-agenda-prepare-buffers
  14113. (and buffer-file-name (list buffer-file-name)))
  14114. (setq res
  14115. (org-scan-tags
  14116. func matcher org--matcher-tags-todo-only start-level)))
  14117. ;; Get the right scope
  14118. (cond
  14119. ((and scope (listp scope) (symbolp (car scope)))
  14120. (setq scope (eval scope)))
  14121. ((eq scope 'agenda)
  14122. (setq scope (org-agenda-files t)))
  14123. ((eq scope 'agenda-with-archives)
  14124. (setq scope (org-agenda-files t))
  14125. (setq scope (org-add-archive-files scope)))
  14126. ((eq scope 'file)
  14127. (setq scope (and buffer-file-name (list buffer-file-name))))
  14128. ((eq scope 'file-with-archives)
  14129. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14130. (org-agenda-prepare-buffers scope)
  14131. (dolist (file scope)
  14132. (with-current-buffer (org-find-base-buffer-visiting file)
  14133. (save-excursion
  14134. (save-restriction
  14135. (widen)
  14136. (goto-char (point-min))
  14137. (setq res
  14138. (append
  14139. res
  14140. (org-scan-tags
  14141. func matcher org--matcher-tags-todo-only))))))))))
  14142. res)))
  14143. ;;; Properties API
  14144. (defconst org-special-properties
  14145. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14146. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14147. "The special properties valid in Org mode.
  14148. These are properties that are not defined in the property drawer,
  14149. but in some other way.")
  14150. (defconst org-default-properties
  14151. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14152. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14153. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14154. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14155. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14156. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14157. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14158. "Some properties that are used by Org mode for various purposes.
  14159. Being in this list makes sure that they are offered for completion.")
  14160. (defun org--valid-property-p (property)
  14161. "Non nil when string PROPERTY is a valid property name."
  14162. (not
  14163. (or (equal property "")
  14164. (org-string-match-p "\\s-" property))))
  14165. (defun org--update-property-plist (key val props)
  14166. "Associate KEY to VAL in alist PROPS.
  14167. Modifications are made by side-effect. Return new alist."
  14168. (let* ((appending (string= (substring key -1) "+"))
  14169. (key (if appending (substring key 0 -1) key))
  14170. (old (assoc-string key props t)))
  14171. (if (not old) (cons (cons key val) props)
  14172. (setcdr old (if appending (concat (cdr old) " " val) val))
  14173. props)))
  14174. (defun org-get-property-block (&optional beg force)
  14175. "Return the (beg . end) range of the body of the property drawer.
  14176. BEG is the beginning of the current subtree, or of the part
  14177. before the first headline. If it is not given, it will be found.
  14178. If the drawer does not exist, create it if FORCE is non-nil, or
  14179. return nil."
  14180. (org-with-wide-buffer
  14181. (when beg (goto-char beg))
  14182. (unless (org-before-first-heading-p)
  14183. (let ((beg (cond (beg)
  14184. ((or (not (featurep 'org-inlinetask))
  14185. (org-inlinetask-in-task-p))
  14186. (org-back-to-heading t))
  14187. (t (org-with-limited-levels (org-back-to-heading t))))))
  14188. (forward-line)
  14189. (when (looking-at-p org-planning-line-re) (forward-line))
  14190. (cond ((looking-at org-property-drawer-re)
  14191. (forward-line)
  14192. (cons (point) (progn (goto-char (match-end 0))
  14193. (line-beginning-position))))
  14194. (force
  14195. (goto-char beg)
  14196. (org-insert-property-drawer)
  14197. (let ((pos (save-excursion (search-forward ":END:")
  14198. (line-beginning-position))))
  14199. (cons pos pos))))))))
  14200. (defun org-at-property-p ()
  14201. "Non-nil when point is inside a property drawer.
  14202. See `org-property-re' for match data, if applicable."
  14203. (save-excursion
  14204. (beginning-of-line)
  14205. (and (looking-at org-property-re)
  14206. (let ((property-drawer (save-match-data (org-get-property-block))))
  14207. (and property-drawer
  14208. (>= (point) (car property-drawer))
  14209. (< (point) (cdr property-drawer)))))))
  14210. (defun org-property-action ()
  14211. "Do an action on properties."
  14212. (interactive)
  14213. (unless (org-at-property-p) (user-error "Not at a property"))
  14214. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14215. (let ((c (read-char-exclusive)))
  14216. (cl-case c
  14217. (?s (call-interactively #'org-set-property))
  14218. (?d (call-interactively #'org-delete-property))
  14219. (?D (call-interactively #'org-delete-property-globally))
  14220. (?c (call-interactively #'org-compute-property-at-point))
  14221. (otherwise (user-error "No such property action %c" c)))))
  14222. (defun org-inc-effort ()
  14223. "Increment the value of the effort property in the current entry."
  14224. (interactive)
  14225. (org-set-effort nil t))
  14226. (defvar org-clock-effort) ; Defined in org-clock.el.
  14227. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14228. (defun org-set-effort (&optional value increment)
  14229. "Set the effort property of the current entry.
  14230. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14231. 10th allowed value.
  14232. When INCREMENT is non-nil, set the property to the next allowed value."
  14233. (interactive "P")
  14234. (when (equal value 0) (setq value 10))
  14235. (let* ((completion-ignore-case t)
  14236. (prop org-effort-property)
  14237. (cur (org-entry-get nil prop))
  14238. (allowed (org-property-get-allowed-values nil prop 'table))
  14239. (existing (mapcar 'list (org-property-values prop)))
  14240. (heading (nth 4 (org-heading-components)))
  14241. rpl
  14242. (val (cond
  14243. ((stringp value) value)
  14244. ((and allowed (integerp value))
  14245. (or (car (nth (1- value) allowed))
  14246. (car (org-last allowed))))
  14247. ((and allowed increment)
  14248. (or (cl-caadr (member (list cur) allowed))
  14249. (user-error "Allowed effort values are not set")))
  14250. (allowed
  14251. (message "Select 1-9,0, [RET%s]: %s"
  14252. (if cur (concat "=" cur) "")
  14253. (mapconcat 'car allowed " "))
  14254. (setq rpl (read-char-exclusive))
  14255. (if (equal rpl ?\r)
  14256. cur
  14257. (setq rpl (- rpl ?0))
  14258. (when (equal rpl 0) (setq rpl 10))
  14259. (if (and (> rpl 0) (<= rpl (length allowed)))
  14260. (car (nth (1- rpl) allowed))
  14261. (org-completing-read "Effort: " allowed nil))))
  14262. (t
  14263. (org-completing-read
  14264. (concat "Effort" (and cur (string-match "\\S-" cur)
  14265. (concat " [" cur "]"))
  14266. ": ")
  14267. existing nil nil "" nil cur)))))
  14268. (unless (equal (org-entry-get nil prop) val)
  14269. (org-entry-put nil prop val))
  14270. (org-refresh-property
  14271. '((effort . identity)
  14272. (effort-minutes . org-duration-string-to-minutes))
  14273. val)
  14274. (when (equal heading (bound-and-true-p org-clock-current-task))
  14275. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14276. (org-clock-update-mode-line))
  14277. (message "%s is now %s" prop val)))
  14278. (defun org-entry-properties (&optional pom which)
  14279. "Get all properties of the current entry.
  14280. When POM is a buffer position, get all properties from the entry
  14281. there instead.
  14282. This includes the TODO keyword, the tags, time strings for
  14283. deadline, scheduled, and clocking, and any additional properties
  14284. defined in the entry.
  14285. If WHICH is nil or `all', get all properties. If WHICH is
  14286. `special' or `standard', only get that subclass. If WHICH is
  14287. a string, only get that property.
  14288. Return value is an alist. Keys are properties, as upcased
  14289. strings."
  14290. (org-with-point-at pom
  14291. (when (and (derived-mode-p 'org-mode)
  14292. (ignore-errors (org-back-to-heading t)))
  14293. (catch 'exit
  14294. (let* ((beg (point))
  14295. (specific (and (stringp which) (upcase which)))
  14296. (which (cond ((not specific) which)
  14297. ((member specific org-special-properties) 'special)
  14298. (t 'standard)))
  14299. props)
  14300. ;; Get the special properties, like TODO and TAGS.
  14301. (when (memq which '(nil all special))
  14302. (when (or (not specific) (string= specific "CLOCKSUM"))
  14303. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14304. (when clocksum
  14305. (push (cons "CLOCKSUM"
  14306. (org-minutes-to-clocksum-string clocksum))
  14307. props)))
  14308. (when specific (throw 'exit props)))
  14309. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14310. (let ((clocksumt (get-text-property (point)
  14311. :org-clock-minutes-today)))
  14312. (when clocksumt
  14313. (push (cons "CLOCKSUM_T"
  14314. (org-minutes-to-clocksum-string clocksumt))
  14315. props)))
  14316. (when specific (throw 'exit props)))
  14317. (when (or (not specific) (string= specific "ITEM"))
  14318. (when (looking-at org-complex-heading-regexp)
  14319. (push (cons "ITEM"
  14320. (let ((title (match-string-no-properties 4)))
  14321. (if (org-string-nw-p title)
  14322. (org-remove-tabs title)
  14323. "")))
  14324. props))
  14325. (when specific (throw 'exit props)))
  14326. (when (or (not specific) (string= specific "TODO"))
  14327. (let ((case-fold-search nil))
  14328. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14329. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14330. (when specific (throw 'exit props)))
  14331. (when (or (not specific) (string= specific "PRIORITY"))
  14332. (push (cons "PRIORITY"
  14333. (if (looking-at org-priority-regexp)
  14334. (match-string-no-properties 2)
  14335. (char-to-string org-default-priority)))
  14336. props)
  14337. (when specific (throw 'exit props)))
  14338. (when (or (not specific) (string= specific "FILE"))
  14339. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14340. props)
  14341. (when specific (throw 'exit props)))
  14342. (when (or (not specific) (string= specific "TAGS"))
  14343. (let ((value (org-string-nw-p (org-get-tags-string))))
  14344. (when value (push (cons "TAGS" value) props)))
  14345. (when specific (throw 'exit props)))
  14346. (when (or (not specific) (string= specific "ALLTAGS"))
  14347. (let ((value (org-get-tags-at)))
  14348. (when value
  14349. (push (cons "ALLTAGS"
  14350. (format ":%s:" (mapconcat #'identity value ":")))
  14351. props)))
  14352. (when specific (throw 'exit props)))
  14353. (when (or (not specific) (string= specific "BLOCKED"))
  14354. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14355. (when specific (throw 'exit props)))
  14356. (when (or (not specific)
  14357. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14358. (forward-line)
  14359. (when (looking-at-p org-planning-line-re)
  14360. (end-of-line)
  14361. (let ((bol (line-beginning-position))
  14362. ;; Backward compatibility: time keywords used to
  14363. ;; be configurable (before 8.3). Make sure we
  14364. ;; get the correct keyword.
  14365. (key-assoc `(("CLOSED" . ,org-closed-string)
  14366. ("DEADLINE" . ,org-deadline-string)
  14367. ("SCHEDULED" . ,org-scheduled-string))))
  14368. (dolist (pair (if specific (list (assoc specific key-assoc))
  14369. key-assoc))
  14370. (save-excursion
  14371. (when (search-backward (cdr pair) bol t)
  14372. (goto-char (match-end 0))
  14373. (skip-chars-forward " \t")
  14374. (and (looking-at org-ts-regexp-both)
  14375. (push (cons (car pair)
  14376. (match-string-no-properties 0))
  14377. props)))))))
  14378. (when specific (throw 'exit props)))
  14379. (when (or (not specific)
  14380. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14381. (let ((find-ts
  14382. (lambda (end ts)
  14383. ;; Fix next time-stamp before END. TS is the
  14384. ;; list of time-stamps found so far.
  14385. (let ((ts ts)
  14386. (regexp (cond
  14387. ((string= specific "TIMESTAMP")
  14388. org-ts-regexp)
  14389. ((string= specific "TIMESTAMP_IA")
  14390. org-ts-regexp-inactive)
  14391. ((assoc "TIMESTAMP_IA" ts)
  14392. org-ts-regexp)
  14393. ((assoc "TIMESTAMP" ts)
  14394. org-ts-regexp-inactive)
  14395. (t org-ts-regexp-both))))
  14396. (catch 'next
  14397. (while (re-search-forward regexp end t)
  14398. (backward-char)
  14399. (let ((object (org-element-context)))
  14400. ;; Accept to match timestamps in node
  14401. ;; properties, too.
  14402. (when (memq (org-element-type object)
  14403. '(node-property timestamp))
  14404. (let ((type
  14405. (org-element-property :type object)))
  14406. (cond
  14407. ((and (memq type '(active active-range))
  14408. (not (equal specific "TIMESTAMP_IA")))
  14409. (unless (assoc "TIMESTAMP" ts)
  14410. (push (cons "TIMESTAMP"
  14411. (org-element-property
  14412. :raw-value object))
  14413. ts)
  14414. (when specific (throw 'exit ts))))
  14415. ((and (memq type '(inactive inactive-range))
  14416. (not (string= specific "TIMESTAMP")))
  14417. (unless (assoc "TIMESTAMP_IA" ts)
  14418. (push (cons "TIMESTAMP_IA"
  14419. (org-element-property
  14420. :raw-value object))
  14421. ts)
  14422. (when specific (throw 'exit ts))))))
  14423. ;; Both timestamp types are found,
  14424. ;; move to next part.
  14425. (when (= (length ts) 2) (throw 'next ts)))))
  14426. ts)))))
  14427. (goto-char beg)
  14428. ;; First look for timestamps within headline.
  14429. (let ((ts (funcall find-ts (line-end-position) nil)))
  14430. (if (= (length ts) 2) (setq props (nconc ts props))
  14431. (forward-line)
  14432. ;; Then find timestamps in the section, skipping
  14433. ;; planning line.
  14434. (when (looking-at-p org-planning-line-re)
  14435. (forward-line))
  14436. (let ((end (save-excursion (outline-next-heading))))
  14437. (setq props (nconc (funcall find-ts end ts) props))))))))
  14438. ;; Get the standard properties, like :PROP:.
  14439. (when (memq which '(nil all standard))
  14440. ;; If we are looking after a specific property, delegate
  14441. ;; to `org-entry-get', which is faster. However, make an
  14442. ;; exception for "CATEGORY", since it can be also set
  14443. ;; through keywords (i.e. #+CATEGORY).
  14444. (if (and specific (not (equal specific "CATEGORY")))
  14445. (let ((value (org-entry-get beg specific nil t)))
  14446. (throw 'exit (and value (list (cons specific value)))))
  14447. (let ((range (org-get-property-block beg)))
  14448. (when range
  14449. (let ((end (cdr range)) seen-base)
  14450. (goto-char (car range))
  14451. ;; Unlike to `org--update-property-plist', we
  14452. ;; handle the case where base values is found
  14453. ;; after its extension. We also forbid standard
  14454. ;; properties to be named as special properties.
  14455. (while (re-search-forward org-property-re end t)
  14456. (let* ((key (upcase (match-string-no-properties 2)))
  14457. (extendp (org-string-match-p "\\+\\'" key))
  14458. (key-base (if extendp (substring key 0 -1) key))
  14459. (value (match-string-no-properties 3)))
  14460. (cond
  14461. ((member-ignore-case key-base org-special-properties))
  14462. (extendp
  14463. (setq props
  14464. (org--update-property-plist key value props)))
  14465. ((member key seen-base))
  14466. (t (push key seen-base)
  14467. (let ((p (assoc-string key props t)))
  14468. (if p (setcdr p (concat value " " (cdr p)))
  14469. (push (cons key value) props))))))))))))
  14470. (unless (assoc "CATEGORY" props)
  14471. (push (cons "CATEGORY" (org-get-category beg)) props)
  14472. (when (string= specific "CATEGORY") (throw 'exit props)))
  14473. ;; Return value.
  14474. props)))))
  14475. (defun org-property--local-values (property literal-nil)
  14476. "Return value for PROPERTY in current entry.
  14477. Value is a list whose car is the base value for PROPERTY and cdr
  14478. a list of accumulated values. Return nil if neither is found in
  14479. the entry. Also return nil when PROPERTY is set to \"nil\",
  14480. unless LITERAL-NIL is non-nil."
  14481. (let ((range (org-get-property-block)))
  14482. (when range
  14483. (goto-char (car range))
  14484. (let* ((case-fold-search t)
  14485. (end (cdr range))
  14486. (value
  14487. ;; Base value.
  14488. (save-excursion
  14489. (let ((v (and (re-search-forward
  14490. (org-re-property property nil t) end t)
  14491. (match-string-no-properties 3))))
  14492. (list (if literal-nil v (org-not-nil v)))))))
  14493. ;; Find additional values.
  14494. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14495. (while (re-search-forward property+ end t)
  14496. (push (match-string-no-properties 3) value)))
  14497. ;; Return final values.
  14498. (and (not (equal value '(nil))) (nreverse value))))))
  14499. (defun org-entry-get (pom property &optional inherit literal-nil)
  14500. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14501. If INHERIT is non-nil and the entry does not have the property,
  14502. then also check higher levels of the hierarchy. If INHERIT is
  14503. the symbol `selective', use inheritance only if the setting in
  14504. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14505. If the property is present but empty, the return value is the
  14506. empty string. If the property is not present at all, nil is
  14507. returned. In any other case, return the value as a string.
  14508. Search is case-insensitive.
  14509. If LITERAL-NIL is set, return the string value \"nil\" as
  14510. a string, do not interpret it as the list atom nil. This is used
  14511. for inheritance when a \"nil\" value can supersede a non-nil
  14512. value higher up the hierarchy."
  14513. (org-with-point-at pom
  14514. (cond
  14515. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14516. ;; We need a special property. Use `org-entry-properties' to
  14517. ;; retrieve it, but specify the wanted property.
  14518. (cdr (assoc-string property (org-entry-properties nil property))))
  14519. ((and inherit
  14520. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14521. (org-entry-get-with-inheritance property literal-nil))
  14522. (t
  14523. (let* ((local (org-property--local-values property literal-nil))
  14524. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14525. (if literal-nil value (org-not-nil value)))))))
  14526. (defun org-property-or-variable-value (var &optional inherit)
  14527. "Check if there is a property fixing the value of VAR.
  14528. If yes, return this value. If not, return the current value of the variable."
  14529. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14530. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14531. (read prop)
  14532. (symbol-value var))))
  14533. (defun org-entry-delete (pom property)
  14534. "Delete PROPERTY from entry at point-or-marker POM.
  14535. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14536. non-nil when a property was removed."
  14537. (unless (member property org-special-properties)
  14538. (org-with-point-at pom
  14539. (let ((range (org-get-property-block)))
  14540. (when range
  14541. (let* ((begin (car range))
  14542. (origin (cdr range))
  14543. (end (copy-marker origin))
  14544. (re (org-re-property
  14545. (concat (regexp-quote property) "\\+?") t t)))
  14546. (goto-char begin)
  14547. (while (re-search-forward re end t)
  14548. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14549. ;; If drawer is empty, remove it altogether.
  14550. (when (= begin end)
  14551. (delete-region (line-beginning-position 0)
  14552. (line-beginning-position 2)))
  14553. ;; Return non-nil if some property was removed.
  14554. (prog1 (/= end origin) (set-marker end nil))))))))
  14555. ;; Multi-values properties are properties that contain multiple values
  14556. ;; These values are assumed to be single words, separated by whitespace.
  14557. (defun org-entry-add-to-multivalued-property (pom property value)
  14558. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14559. (let* ((old (org-entry-get pom property))
  14560. (values (and old (org-split-string old "[ \t]"))))
  14561. (setq value (org-entry-protect-space value))
  14562. (unless (member value values)
  14563. (setq values (append values (list value)))
  14564. (org-entry-put pom property
  14565. (mapconcat 'identity values " ")))))
  14566. (defun org-entry-remove-from-multivalued-property (pom property value)
  14567. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14568. (let* ((old (org-entry-get pom property))
  14569. (values (and old (org-split-string old "[ \t]"))))
  14570. (setq value (org-entry-protect-space value))
  14571. (when (member value values)
  14572. (setq values (delete value values))
  14573. (org-entry-put pom property
  14574. (mapconcat 'identity values " ")))))
  14575. (defun org-entry-member-in-multivalued-property (pom property value)
  14576. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14577. (let* ((old (org-entry-get pom property))
  14578. (values (and old (org-split-string old "[ \t]"))))
  14579. (setq value (org-entry-protect-space value))
  14580. (member value values)))
  14581. (defun org-entry-get-multivalued-property (pom property)
  14582. "Return a list of values in a multivalued property."
  14583. (let* ((value (org-entry-get pom property))
  14584. (values (and value (org-split-string value "[ \t]"))))
  14585. (mapcar 'org-entry-restore-space values)))
  14586. (defun org-entry-put-multivalued-property (pom property &rest values)
  14587. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14588. VALUES should be a list of strings. Spaces will be protected."
  14589. (org-entry-put pom property
  14590. (mapconcat 'org-entry-protect-space values " "))
  14591. (let* ((value (org-entry-get pom property))
  14592. (values (and value (org-split-string value "[ \t]"))))
  14593. (mapcar 'org-entry-restore-space values)))
  14594. (defun org-entry-protect-space (s)
  14595. "Protect spaces and newline in string S."
  14596. (while (string-match " " s)
  14597. (setq s (replace-match "%20" t t s)))
  14598. (while (string-match "\n" s)
  14599. (setq s (replace-match "%0A" t t s)))
  14600. s)
  14601. (defun org-entry-restore-space (s)
  14602. "Restore spaces and newline in string S."
  14603. (while (string-match "%20" s)
  14604. (setq s (replace-match " " t t s)))
  14605. (while (string-match "%0A" s)
  14606. (setq s (replace-match "\n" t t s)))
  14607. s)
  14608. (defvar org-entry-property-inherited-from (make-marker)
  14609. "Marker pointing to the entry from where a property was inherited.
  14610. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14611. location of the entry where the inheritance search matched. If there was
  14612. no match, the marker will point nowhere.
  14613. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14614. is set.")
  14615. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14616. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14617. The search will stop at the first ancestor which has the property defined.
  14618. If the value found is \"nil\", return nil to show that the property
  14619. should be considered as undefined (this is the meaning of nil here).
  14620. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14621. (move-marker org-entry-property-inherited-from nil)
  14622. (org-with-wide-buffer
  14623. (let (value)
  14624. (catch 'exit
  14625. (while t
  14626. (let ((v (org-property--local-values property literal-nil)))
  14627. (when v
  14628. (setq value
  14629. (concat (mapconcat #'identity (delq nil v) " ")
  14630. (and value " ")
  14631. value)))
  14632. (cond
  14633. ((car v)
  14634. (org-back-to-heading t)
  14635. (move-marker org-entry-property-inherited-from (point))
  14636. (throw 'exit nil))
  14637. ((org-up-heading-safe))
  14638. (t
  14639. (let ((global
  14640. (cdr (or (assoc-string property org-file-properties t)
  14641. (assoc-string property org-global-properties t)
  14642. (assoc-string property org-global-properties-fixed t)))))
  14643. (cond ((not global))
  14644. (value (setq value (concat global " " value)))
  14645. (t (setq value global))))
  14646. (throw 'exit nil))))))
  14647. (if literal-nil value (org-not-nil value)))))
  14648. (defvar org-property-changed-functions nil
  14649. "Hook called when the value of a property has changed.
  14650. Each hook function should accept two arguments, the name of the property
  14651. and the new value.")
  14652. (defun org-entry-put (pom property value)
  14653. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14654. If the value is nil, it is converted to the empty string. If it
  14655. is not a string, an error is raised. Also raise an error on
  14656. invalid property names.
  14657. PROPERTY can be any regular property (see
  14658. `org-special-properties'). It can also be \"TODO\",
  14659. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14660. For the last two properties, VALUE may have any of the special
  14661. values \"earlier\" and \"later\". The function then increases or
  14662. decreases scheduled or deadline date by one day."
  14663. (cond ((null value) (setq value ""))
  14664. ((not (stringp value)) (error "Properties values should be strings"))
  14665. ((not (org--valid-property-p property))
  14666. (user-error "Invalid property name: \"%s\"" property)))
  14667. (org-with-point-at pom
  14668. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14669. (org-back-to-heading t)
  14670. (org-with-limited-levels (org-back-to-heading t)))
  14671. (let ((beg (point)))
  14672. (cond
  14673. ((equal property "TODO")
  14674. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14675. ((not (member value org-todo-keywords-1))
  14676. (user-error "\"%s\" is not a valid TODO state" value)))
  14677. (org-todo value)
  14678. (org-set-tags nil 'align))
  14679. ((equal property "PRIORITY")
  14680. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14681. (org-set-tags nil 'align))
  14682. ((equal property "SCHEDULED")
  14683. (forward-line)
  14684. (if (and (looking-at-p org-planning-line-re)
  14685. (re-search-forward
  14686. org-scheduled-time-regexp (line-end-position) t))
  14687. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14688. ((string= value "later") (org-timestamp-change 1 'day))
  14689. ((string= value "") (org-schedule '(4)))
  14690. (t (org-schedule nil value)))
  14691. (if (member value '("earlier" "later" ""))
  14692. (call-interactively #'org-schedule)
  14693. (org-schedule nil value))))
  14694. ((equal property "DEADLINE")
  14695. (forward-line)
  14696. (if (and (looking-at-p org-planning-line-re)
  14697. (re-search-forward
  14698. org-deadline-time-regexp (line-end-position) t))
  14699. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14700. ((string= value "later") (org-timestamp-change 1 'day))
  14701. ((string= value "") (org-deadline '(4)))
  14702. (t (org-deadline nil value)))
  14703. (if (member value '("earlier" "later" ""))
  14704. (call-interactively #'org-deadline)
  14705. (org-deadline nil value))))
  14706. ((member property org-special-properties)
  14707. (error "The %s property cannot be set with `org-entry-put'" property))
  14708. (t
  14709. (let* ((range (org-get-property-block beg 'force))
  14710. (end (cdr range))
  14711. (case-fold-search t))
  14712. (goto-char (car range))
  14713. (if (re-search-forward (org-re-property property nil t) end t)
  14714. (progn (delete-region (match-beginning 0) (match-end 0))
  14715. (goto-char (match-beginning 0)))
  14716. (goto-char end)
  14717. (insert "\n")
  14718. (backward-char))
  14719. (insert ":" property ":")
  14720. (when value (insert " " value))
  14721. (org-indent-line)))))
  14722. (run-hook-with-args 'org-property-changed-functions property value)))
  14723. (defun org-buffer-property-keys
  14724. (&optional specials defaults columns ignore-malformed)
  14725. "Get all property keys in the current buffer.
  14726. When SPECIALS is non-nil, also list the special properties that
  14727. reflect things like tags and TODO state.
  14728. When DEFAULTS is non-nil, also include properties that has
  14729. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14730. DESCRIPTION, LOCATION, and LOGGING and others.
  14731. When COLUMNS in non-nil, also include property names given in
  14732. COLUMN formats in the current buffer.
  14733. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14734. automatically performed, such drawers will be silently ignored."
  14735. (let ((case-fold-search t)
  14736. (props (append
  14737. (and specials org-special-properties)
  14738. (and defaults (cons org-effort-property org-default-properties))
  14739. nil)))
  14740. (org-with-wide-buffer
  14741. (goto-char (point-min))
  14742. (while (re-search-forward org-property-start-re nil t)
  14743. (let ((range (org-get-property-block)))
  14744. (catch 'skip
  14745. (unless range
  14746. (when (and (not ignore-malformed)
  14747. (not (org-before-first-heading-p))
  14748. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14749. (line-beginning-position))))
  14750. (org-get-property-block nil t))
  14751. (throw 'skip nil))
  14752. (goto-char (car range))
  14753. (let ((begin (car range))
  14754. (end (cdr range)))
  14755. ;; Make sure that found property block is not located
  14756. ;; before current point, as it would generate an infloop.
  14757. ;; It can happen, for example, in the following
  14758. ;; situation:
  14759. ;;
  14760. ;; * Headline
  14761. ;; :PROPERTIES:
  14762. ;; ...
  14763. ;; :END:
  14764. ;; *************** Inlinetask
  14765. ;; #+BEGIN_EXAMPLE
  14766. ;; :PROPERTIES:
  14767. ;; #+END_EXAMPLE
  14768. ;;
  14769. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14770. (while (< (point) end)
  14771. (let ((p (progn (looking-at org-property-re)
  14772. (match-string-no-properties 2))))
  14773. ;; Only add true property name, not extension symbol.
  14774. (push (if (not (org-string-match-p "\\+\\'" p)) p
  14775. (substring p 0 -1))
  14776. props))
  14777. (forward-line))))
  14778. (outline-next-heading)))
  14779. (when columns
  14780. (goto-char (point-min))
  14781. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14782. (let ((element (org-element-at-point)))
  14783. (when (memq (org-element-type element) '(keyword node-property))
  14784. (let ((value (org-element-property :value element))
  14785. (start 0))
  14786. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14787. (setq start (match-end 0))
  14788. (let ((p (match-string-no-properties 1 value)))
  14789. (unless (member-ignore-case p org-special-properties)
  14790. (push p props))))))))))
  14791. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14792. (defun org-property-values (key)
  14793. "List all non-nil values of property KEY in current buffer."
  14794. (org-with-wide-buffer
  14795. (goto-char (point-min))
  14796. (let ((case-fold-search t)
  14797. (re (org-re-property key))
  14798. values)
  14799. (while (re-search-forward re nil t)
  14800. (push (org-entry-get (point) key) values))
  14801. (delete-dups values))))
  14802. (defun org-insert-property-drawer ()
  14803. "Insert a property drawer into the current entry."
  14804. (org-with-wide-buffer
  14805. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14806. (org-back-to-heading t)
  14807. (org-with-limited-levels (org-back-to-heading t)))
  14808. (forward-line)
  14809. (when (looking-at-p org-planning-line-re) (forward-line))
  14810. (unless (looking-at-p org-property-drawer-re)
  14811. ;; Make sure we start editing a line from current entry, not from
  14812. ;; next one. It prevents extending text properties or overlays
  14813. ;; belonging to the latter.
  14814. (when (bolp) (backward-char))
  14815. (let ((begin (1+ (point)))
  14816. (inhibit-read-only t))
  14817. (insert "\n:PROPERTIES:\n:END:")
  14818. (when (eobp) (insert "\n"))
  14819. (org-indent-region begin (point))))))
  14820. (defun org-insert-drawer (&optional arg drawer)
  14821. "Insert a drawer at point.
  14822. When optional argument ARG is non-nil, insert a property drawer.
  14823. Optional argument DRAWER, when non-nil, is a string representing
  14824. drawer's name. Otherwise, the user is prompted for a name.
  14825. If a region is active, insert the drawer around that region
  14826. instead.
  14827. Point is left between drawer's boundaries."
  14828. (interactive "P")
  14829. (let* ((drawer (if arg "PROPERTIES"
  14830. (or drawer (read-from-minibuffer "Drawer: ")))))
  14831. (cond
  14832. ;; With C-u, fall back on `org-insert-property-drawer'
  14833. (arg (org-insert-property-drawer))
  14834. ;; Check validity of suggested drawer's name.
  14835. ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14836. (user-error "Invalid drawer name"))
  14837. ;; With an active region, insert a drawer at point.
  14838. ((not (org-region-active-p))
  14839. (progn
  14840. (unless (bolp) (insert "\n"))
  14841. (insert (format ":%s:\n\n:END:\n" drawer))
  14842. (forward-line -2)))
  14843. ;; Otherwise, insert the drawer at point
  14844. (t
  14845. (let ((rbeg (region-beginning))
  14846. (rend (copy-marker (region-end))))
  14847. (unwind-protect
  14848. (progn
  14849. (goto-char rbeg)
  14850. (beginning-of-line)
  14851. (when (save-excursion
  14852. (re-search-forward org-outline-regexp-bol rend t))
  14853. (user-error "Drawers cannot contain headlines"))
  14854. ;; Position point at the beginning of the first
  14855. ;; non-blank line in region. Insert drawer's opening
  14856. ;; there, then indent it.
  14857. (org-skip-whitespace)
  14858. (beginning-of-line)
  14859. (insert ":" drawer ":\n")
  14860. (forward-line -1)
  14861. (indent-for-tab-command)
  14862. ;; Move point to the beginning of the first blank line
  14863. ;; after the last non-blank line in region. Insert
  14864. ;; drawer's closing, then indent it.
  14865. (goto-char rend)
  14866. (skip-chars-backward " \r\t\n")
  14867. (insert "\n:END:")
  14868. (deactivate-mark t)
  14869. (indent-for-tab-command)
  14870. (unless (eolp) (insert "\n")))
  14871. ;; Clear marker, whatever the outcome of insertion is.
  14872. (set-marker rend nil)))))))
  14873. (defvar org-property-set-functions-alist nil
  14874. "Property set function alist.
  14875. Each entry should have the following format:
  14876. (PROPERTY . READ-FUNCTION)
  14877. The read function will be called with the same argument as
  14878. `org-completing-read'.")
  14879. (defun org-set-property-function (property)
  14880. "Get the function that should be used to set PROPERTY.
  14881. This is computed according to `org-property-set-functions-alist'."
  14882. (or (cdr (assoc property org-property-set-functions-alist))
  14883. 'org-completing-read))
  14884. (defun org-read-property-value (property)
  14885. "Read PROPERTY value from user."
  14886. (let* ((completion-ignore-case t)
  14887. (allowed (org-property-get-allowed-values nil property 'table))
  14888. (cur (org-entry-get nil property))
  14889. (prompt (concat property " value"
  14890. (if (and cur (string-match "\\S-" cur))
  14891. (concat " [" cur "]") "") ": "))
  14892. (set-function (org-set-property-function property))
  14893. (val (if allowed
  14894. (funcall set-function prompt allowed nil
  14895. (not (get-text-property 0 'org-unrestricted
  14896. (caar allowed))))
  14897. (funcall set-function prompt
  14898. (mapcar 'list (org-property-values property))
  14899. nil nil "" nil cur))))
  14900. (org-trim val)))
  14901. (defvar org-last-set-property nil)
  14902. (defvar org-last-set-property-value nil)
  14903. (defun org-read-property-name ()
  14904. "Read a property name."
  14905. (let ((completion-ignore-case t)
  14906. (default-prop (or (and (org-at-property-p)
  14907. (match-string-no-properties 2))
  14908. org-last-set-property)))
  14909. (org-completing-read
  14910. (concat "Property"
  14911. (if default-prop (concat " [" default-prop "]") "")
  14912. ": ")
  14913. (mapcar #'list (org-buffer-property-keys nil t t))
  14914. nil nil nil nil default-prop)))
  14915. (defun org-set-property-and-value (use-last)
  14916. "Allow to set [PROPERTY]: [value] direction from prompt.
  14917. When use-default, don't even ask, just use the last
  14918. \"[PROPERTY]: [value]\" string from the history."
  14919. (interactive "P")
  14920. (let* ((completion-ignore-case t)
  14921. (pv (or (and use-last org-last-set-property-value)
  14922. (org-completing-read
  14923. "Enter a \"[Property]: [value]\" pair: "
  14924. nil nil nil nil nil
  14925. org-last-set-property-value)))
  14926. prop val)
  14927. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14928. (setq prop (match-string 1 pv)
  14929. val (match-string 2 pv))
  14930. (org-set-property prop val))))
  14931. (defun org-set-property (property value)
  14932. "In the current entry, set PROPERTY to VALUE.
  14933. When called interactively, this will prompt for a property name, offering
  14934. completion on existing and default properties. And then it will prompt
  14935. for a value, offering completion either on allowed values (via an inherited
  14936. xxx_ALL property) or on existing values in other instances of this property
  14937. in the current file.
  14938. Throw an error when trying to set a property with an invalid name."
  14939. (interactive (list nil nil))
  14940. (let ((property (or property (org-read-property-name))))
  14941. ;; `org-entry-put' also makes the following check, but this one
  14942. ;; avoids polluting `org-last-set-property' and
  14943. ;; `org-last-set-property-value' needlessly.
  14944. (unless (org--valid-property-p property)
  14945. (user-error "Invalid property name: \"%s\"" property))
  14946. (let ((value (or value (org-read-property-value property)))
  14947. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14948. (setq org-last-set-property property)
  14949. (setq org-last-set-property-value (concat property ": " value))
  14950. ;; Possibly postprocess the inserted value:
  14951. (when fn (setq value (funcall fn value)))
  14952. (unless (equal (org-entry-get nil property) value)
  14953. (org-entry-put nil property value)))))
  14954. (defun org-find-property (property &optional value)
  14955. "Find first entry in buffer that sets PROPERTY.
  14956. When optional argument VALUE is non-nil, only consider an entry
  14957. if it contains PROPERTY set to this value. If PROPERTY should be
  14958. explicitly set to nil, use string \"nil\" for VALUE.
  14959. Return position where the entry begins, or nil if there is no
  14960. such entry. If narrowing is in effect, only search the visible
  14961. part of the buffer."
  14962. (save-excursion
  14963. (goto-char (point-min))
  14964. (let ((case-fold-search t)
  14965. (re (org-re-property property nil (not value) value)))
  14966. (catch 'exit
  14967. (while (re-search-forward re nil t)
  14968. (when (if value (org-at-property-p)
  14969. (org-entry-get (point) property nil t))
  14970. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14971. (defun org-delete-property (property)
  14972. "In the current entry, delete PROPERTY."
  14973. (interactive
  14974. (let* ((completion-ignore-case t)
  14975. (cat (org-entry-get (point) "CATEGORY"))
  14976. (props0 (org-entry-properties nil 'standard))
  14977. (props (if cat props0
  14978. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14979. (prop (if (< 1 (length props))
  14980. (completing-read "Property: " props nil t)
  14981. (caar props))))
  14982. (list prop)))
  14983. (if (not property)
  14984. (message "No property to delete in this entry")
  14985. (org-entry-delete nil property)
  14986. (message "Property \"%s\" deleted" property)))
  14987. (defun org-delete-property-globally (property)
  14988. "Remove PROPERTY globally, from all entries.
  14989. This function ignores narrowing, if any."
  14990. (interactive
  14991. (let* ((completion-ignore-case t)
  14992. (prop (completing-read
  14993. "Globally remove property: "
  14994. (mapcar #'list (org-buffer-property-keys)))))
  14995. (list prop)))
  14996. (org-with-wide-buffer
  14997. (goto-char (point-min))
  14998. (let ((count 0)
  14999. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15000. (while (re-search-forward re nil t)
  15001. (when (org-entry-delete (point) property) (cl-incf count)))
  15002. (message "Property \"%s\" removed from %d entries" property count))))
  15003. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15004. (defun org-compute-property-at-point ()
  15005. "Compute the property at point.
  15006. This looks for an enclosing column format, extracts the operator and
  15007. then applies it to the property in the column format's scope."
  15008. (interactive)
  15009. (unless (org-at-property-p)
  15010. (user-error "Not at a property"))
  15011. (let ((prop (match-string-no-properties 2)))
  15012. (org-columns-get-format-and-top-level)
  15013. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15014. (user-error "No operator defined for property %s" prop))
  15015. (org-columns-compute prop)))
  15016. (defvar org-property-allowed-value-functions nil
  15017. "Hook for functions supplying allowed values for a specific property.
  15018. The functions must take a single argument, the name of the property, and
  15019. return a flat list of allowed values. If \":ETC\" is one of
  15020. the values, this means that these values are intended as defaults for
  15021. completion, but that other values should be allowed too.
  15022. The functions must return nil if they are not responsible for this
  15023. property.")
  15024. (defun org-property-get-allowed-values (pom property &optional table)
  15025. "Get allowed values for the property PROPERTY.
  15026. When TABLE is non-nil, return an alist that can directly be used for
  15027. completion."
  15028. (let (vals)
  15029. (cond
  15030. ((equal property "TODO")
  15031. (setq vals (org-with-point-at pom
  15032. (append org-todo-keywords-1 '("")))))
  15033. ((equal property "PRIORITY")
  15034. (let ((n org-lowest-priority))
  15035. (while (>= n org-highest-priority)
  15036. (push (char-to-string n) vals)
  15037. (setq n (1- n)))))
  15038. ((equal property "CATEGORY"))
  15039. ((member property org-special-properties))
  15040. ((setq vals (run-hook-with-args-until-success
  15041. 'org-property-allowed-value-functions property)))
  15042. (t
  15043. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15044. (when (and vals (string-match "\\S-" vals))
  15045. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15046. (setq vals (mapcar (lambda (x)
  15047. (cond ((stringp x) x)
  15048. ((numberp x) (number-to-string x))
  15049. ((symbolp x) (symbol-name x))
  15050. (t "???")))
  15051. vals)))))
  15052. (when (member ":ETC" vals)
  15053. (setq vals (remove ":ETC" vals))
  15054. (org-add-props (car vals) '(org-unrestricted t)))
  15055. (if table (mapcar 'list vals) vals)))
  15056. (defun org-property-previous-allowed-value (&optional _previous)
  15057. "Switch to the next allowed value for this property."
  15058. (interactive)
  15059. (org-property-next-allowed-value t))
  15060. (defun org-property-next-allowed-value (&optional previous)
  15061. "Switch to the next allowed value for this property."
  15062. (interactive)
  15063. (unless (org-at-property-p)
  15064. (user-error "Not at a property"))
  15065. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15066. (key (match-string 2))
  15067. (value (match-string 3))
  15068. (allowed (or (org-property-get-allowed-values (point) key)
  15069. (and (member value '("[ ]" "[-]" "[X]"))
  15070. '("[ ]" "[X]"))))
  15071. (heading (save-match-data (nth 4 (org-heading-components))))
  15072. nval)
  15073. (unless allowed
  15074. (user-error "Allowed values for this property have not been defined"))
  15075. (when previous (setq allowed (reverse allowed)))
  15076. (when (member value allowed)
  15077. (setq nval (car (cdr (member value allowed)))))
  15078. (setq nval (or nval (car allowed)))
  15079. (when (equal nval value)
  15080. (user-error "Only one allowed value for this property"))
  15081. (org-at-property-p)
  15082. (replace-match (concat " :" key ": " nval) t t)
  15083. (org-indent-line)
  15084. (beginning-of-line 1)
  15085. (skip-chars-forward " \t")
  15086. (when (equal prop org-effort-property)
  15087. (org-refresh-property
  15088. '((effort . identity)
  15089. (effort-minutes . org-duration-string-to-minutes))
  15090. nval)
  15091. (when (string= org-clock-current-task heading)
  15092. (setq org-clock-effort nval)
  15093. (org-clock-update-mode-line)))
  15094. (run-hook-with-args 'org-property-changed-functions key nval)))
  15095. (defun org-find-olp (path &optional this-buffer)
  15096. "Return a marker pointing to the entry at outline path OLP.
  15097. If anything goes wrong, throw an error.
  15098. You can wrap this call to catch the error like this:
  15099. \(condition-case msg
  15100. \(org-mobile-locate-entry (match-string 4))
  15101. \(error (nth 1 msg)))
  15102. The return value will then be either a string with the error message,
  15103. or a marker if everything is OK.
  15104. If THIS-BUFFER is set, the outline path does not contain a file,
  15105. only headings."
  15106. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15107. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15108. (level 1)
  15109. (lmin 1)
  15110. (lmax 1)
  15111. end found flevel)
  15112. (unless buffer (error "File not found :%s" file))
  15113. (with-current-buffer buffer
  15114. (org-with-wide-buffer
  15115. (goto-char (point-min))
  15116. (dolist (heading path)
  15117. (let ((re (format org-complex-heading-regexp-format
  15118. (regexp-quote heading)))
  15119. (cnt 0))
  15120. (while (re-search-forward re end t)
  15121. (setq level (- (match-end 1) (match-beginning 1)))
  15122. (when (and (>= level lmin) (<= level lmax))
  15123. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15124. (when (= cnt 0)
  15125. (error "Heading not found on level %d: %s" lmax heading))
  15126. (when (> cnt 1)
  15127. (error "Heading not unique on level %d: %s" lmax heading))
  15128. (goto-char found)
  15129. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15130. (setq end (save-excursion (org-end-of-subtree t t)))))
  15131. (when (org-at-heading-p)
  15132. (point-marker))))))
  15133. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15134. "Find node HEADING in BUFFER.
  15135. Return a marker to the heading if it was found, or nil if not.
  15136. If POS-ONLY is set, return just the position instead of a marker.
  15137. The heading text must match exact, but it may have a TODO keyword,
  15138. a priority cookie and tags in the standard locations."
  15139. (with-current-buffer (or buffer (current-buffer))
  15140. (save-excursion
  15141. (save-restriction
  15142. (widen)
  15143. (goto-char (point-min))
  15144. (let (case-fold-search)
  15145. (when (re-search-forward
  15146. (format org-complex-heading-regexp-format
  15147. (regexp-quote heading)) nil t)
  15148. (if pos-only
  15149. (match-beginning 0)
  15150. (move-marker (make-marker) (match-beginning 0)))))))))
  15151. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15152. "Find Org node headline HEADING in all .org files in directory DIR.
  15153. When the target headline is found, return a marker to this location."
  15154. (let ((files (directory-files (or dir default-directory)
  15155. t "\\`[^.#].*\\.org\\'"))
  15156. visiting m buffer)
  15157. (catch 'found
  15158. (dolist (file files)
  15159. (message "trying %s" file)
  15160. (setq visiting (org-find-base-buffer-visiting file))
  15161. (setq buffer (or visiting (find-file-noselect file)))
  15162. (setq m (org-find-exact-headline-in-buffer
  15163. heading buffer))
  15164. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15165. (and m (throw 'found m))))))
  15166. (defun org-find-entry-with-id (ident)
  15167. "Locate the entry that contains the ID property with exact value IDENT.
  15168. IDENT can be a string, a symbol or a number, this function will search for
  15169. the string representation of it.
  15170. Return the position where this entry starts, or nil if there is no such entry."
  15171. (interactive "sID: ")
  15172. (let ((id (cond
  15173. ((stringp ident) ident)
  15174. ((symbolp ident) (symbol-name ident))
  15175. ((numberp ident) (number-to-string ident))
  15176. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15177. (org-with-wide-buffer (org-find-property "ID" id))))
  15178. ;;;; Timestamps
  15179. (defvar org-last-changed-timestamp nil)
  15180. (defvar org-last-inserted-timestamp nil
  15181. "The last time stamp inserted with `org-insert-time-stamp'.")
  15182. (defvar org-ts-what) ; dynamically scoped parameter
  15183. (defun org-time-stamp (arg &optional inactive)
  15184. "Prompt for a date/time and insert a time stamp.
  15185. If the user specifies a time like HH:MM or if this command is
  15186. called with at least one prefix argument, the time stamp contains
  15187. the date and the time. Otherwise, only the date is included.
  15188. All parts of a date not specified by the user are filled in from
  15189. the timestamp at point, if any, or the current date/time
  15190. otherwise.
  15191. If there is already a timestamp at the cursor, it is replaced.
  15192. With two universal prefix arguments, insert an active timestamp
  15193. with the current time without prompting the user.
  15194. When called from lisp, the timestamp is inactive if INACTIVE is
  15195. non-nil."
  15196. (interactive "P")
  15197. (let* ((ts (cond
  15198. ((org-at-date-range-p t)
  15199. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15200. ((org-at-timestamp-p t) (match-string 0))))
  15201. ;; Default time is either the timestamp at point or today.
  15202. ;; When entering a range, only the range start is considered.
  15203. (default-time (if (not ts) (current-time)
  15204. (apply #'encode-time (org-parse-time-string ts))))
  15205. (default-input (and ts (org-get-compact-tod ts)))
  15206. (repeater (and ts
  15207. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15208. (match-string 0 ts)))
  15209. org-time-was-given
  15210. org-end-time-was-given
  15211. (time
  15212. (and (if (equal arg '(16)) (current-time)
  15213. ;; Preserve `this-command' and `last-command'.
  15214. (let ((this-command this-command)
  15215. (last-command last-command))
  15216. (org-read-date
  15217. arg 'totime nil nil default-time default-input
  15218. inactive))))))
  15219. (cond
  15220. ((and ts
  15221. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15222. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15223. (insert "--")
  15224. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15225. (ts
  15226. ;; Make sure we're on a timestamp. When in the middle of a date
  15227. ;; range, move arbitrarily to range end.
  15228. (unless (org-at-timestamp-p t)
  15229. (skip-chars-forward "-")
  15230. (org-at-timestamp-p t))
  15231. (replace-match "")
  15232. (setq org-last-changed-timestamp
  15233. (org-insert-time-stamp
  15234. time (or org-time-was-given arg)
  15235. inactive nil nil (list org-end-time-was-given)))
  15236. (when repeater
  15237. (backward-char)
  15238. (insert " " repeater)
  15239. (setq org-last-changed-timestamp
  15240. (concat (substring org-last-inserted-timestamp 0 -1)
  15241. " " repeater ">")))
  15242. (message "Timestamp updated"))
  15243. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15244. (t (org-insert-time-stamp
  15245. time (or org-time-was-given arg) inactive nil nil
  15246. (list org-end-time-was-given))))))
  15247. ;; FIXME: can we use this for something else, like computing time differences?
  15248. (defun org-get-compact-tod (s)
  15249. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15250. (let* ((t1 (match-string 1 s))
  15251. (h1 (string-to-number (match-string 2 s)))
  15252. (m1 (string-to-number (match-string 3 s)))
  15253. (t2 (and (match-end 4) (match-string 5 s)))
  15254. (h2 (and t2 (string-to-number (match-string 6 s))))
  15255. (m2 (and t2 (string-to-number (match-string 7 s))))
  15256. dh dm)
  15257. (if (not t2)
  15258. t1
  15259. (setq dh (- h2 h1) dm (- m2 m1))
  15260. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15261. (concat t1 "+" (number-to-string dh)
  15262. (and (/= 0 dm) (format ":%02d" dm)))))))
  15263. (defun org-time-stamp-inactive (&optional arg)
  15264. "Insert an inactive time stamp.
  15265. An inactive time stamp is enclosed in square brackets instead of angle
  15266. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15267. does not link to the calendar and cannot be changed with the S-cursor keys.
  15268. So these are more for recording a certain time/date."
  15269. (interactive "P")
  15270. (org-time-stamp arg 'inactive))
  15271. (defvar org-date-ovl (make-overlay 1 1))
  15272. (overlay-put org-date-ovl 'face 'org-date-selected)
  15273. (delete-overlay org-date-ovl)
  15274. (defvar org-ans1) ; dynamically scoped parameter
  15275. (defvar org-ans2) ; dynamically scoped parameter
  15276. (defvar org-plain-time-of-day-regexp) ; defined below
  15277. (defvar org-overriding-default-time nil) ; dynamically scoped
  15278. (defvar org-read-date-overlay nil)
  15279. (defvar org-dcst nil) ; dynamically scoped
  15280. (defvar org-read-date-history nil)
  15281. (defvar org-read-date-final-answer nil)
  15282. (defvar org-read-date-analyze-futurep nil)
  15283. (defvar org-read-date-analyze-forced-year nil)
  15284. (defvar org-read-date-inactive)
  15285. (defvar org-read-date-minibuffer-local-map
  15286. (let* ((map (make-sparse-keymap)))
  15287. (set-keymap-parent map minibuffer-local-map)
  15288. (org-defkey map (kbd ".")
  15289. (lambda () (interactive)
  15290. ;; Are we at the beginning of the prompt?
  15291. (if (looking-back "^[^:]+: "
  15292. (let ((inhibit-field-text-motion t))
  15293. (line-beginning-position)))
  15294. (org-eval-in-calendar '(calendar-goto-today))
  15295. (insert "."))))
  15296. (org-defkey map (kbd "C-.")
  15297. (lambda () (interactive)
  15298. (org-eval-in-calendar '(calendar-goto-today))))
  15299. (org-defkey map [(meta shift left)]
  15300. (lambda () (interactive)
  15301. (org-eval-in-calendar '(calendar-backward-month 1))))
  15302. (org-defkey map [(meta shift right)]
  15303. (lambda () (interactive)
  15304. (org-eval-in-calendar '(calendar-forward-month 1))))
  15305. (org-defkey map [(meta shift up)]
  15306. (lambda () (interactive)
  15307. (org-eval-in-calendar '(calendar-backward-year 1))))
  15308. (org-defkey map [(meta shift down)]
  15309. (lambda () (interactive)
  15310. (org-eval-in-calendar '(calendar-forward-year 1))))
  15311. (org-defkey map [?\e (shift left)]
  15312. (lambda () (interactive)
  15313. (org-eval-in-calendar '(calendar-backward-month 1))))
  15314. (org-defkey map [?\e (shift right)]
  15315. (lambda () (interactive)
  15316. (org-eval-in-calendar '(calendar-forward-month 1))))
  15317. (org-defkey map [?\e (shift up)]
  15318. (lambda () (interactive)
  15319. (org-eval-in-calendar '(calendar-backward-year 1))))
  15320. (org-defkey map [?\e (shift down)]
  15321. (lambda () (interactive)
  15322. (org-eval-in-calendar '(calendar-forward-year 1))))
  15323. (org-defkey map [(shift up)]
  15324. (lambda () (interactive)
  15325. (org-eval-in-calendar '(calendar-backward-week 1))))
  15326. (org-defkey map [(shift down)]
  15327. (lambda () (interactive)
  15328. (org-eval-in-calendar '(calendar-forward-week 1))))
  15329. (org-defkey map [(shift left)]
  15330. (lambda () (interactive)
  15331. (org-eval-in-calendar '(calendar-backward-day 1))))
  15332. (org-defkey map [(shift right)]
  15333. (lambda () (interactive)
  15334. (org-eval-in-calendar '(calendar-forward-day 1))))
  15335. (org-defkey map "!"
  15336. (lambda () (interactive)
  15337. (org-eval-in-calendar '(diary-view-entries))
  15338. (message "")))
  15339. (org-defkey map ">"
  15340. (lambda () (interactive)
  15341. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15342. (org-defkey map "<"
  15343. (lambda () (interactive)
  15344. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15345. (org-defkey map "\C-v"
  15346. (lambda () (interactive)
  15347. (org-eval-in-calendar
  15348. '(calendar-scroll-left-three-months 1))))
  15349. (org-defkey map "\M-v"
  15350. (lambda () (interactive)
  15351. (org-eval-in-calendar
  15352. '(calendar-scroll-right-three-months 1))))
  15353. map)
  15354. "Keymap for minibuffer commands when using `org-read-date'.")
  15355. (defvar org-def)
  15356. (defvar org-defdecode)
  15357. (defvar org-with-time)
  15358. (defvar calendar-setup) ; Dynamically scoped.
  15359. (defun org-read-date (&optional with-time to-time from-string prompt
  15360. default-time default-input inactive)
  15361. "Read a date, possibly a time, and make things smooth for the user.
  15362. The prompt will suggest to enter an ISO date, but you can also enter anything
  15363. which will at least partially be understood by `parse-time-string'.
  15364. Unrecognized parts of the date will default to the current day, month, year,
  15365. hour and minute. If this command is called to replace a timestamp at point,
  15366. or to enter the second timestamp of a range, the default time is taken
  15367. from the existing stamp. Furthermore, the command prefers the future,
  15368. so if you are giving a date where the year is not given, and the day-month
  15369. combination is already past in the current year, it will assume you
  15370. mean next year. For details, see the manual. A few examples:
  15371. 3-2-5 --> 2003-02-05
  15372. feb 15 --> currentyear-02-15
  15373. 2/15 --> currentyear-02-15
  15374. sep 12 9 --> 2009-09-12
  15375. 12:45 --> today 12:45
  15376. 22 sept 0:34 --> currentyear-09-22 0:34
  15377. 12 --> currentyear-currentmonth-12
  15378. Fri --> nearest Friday after today
  15379. -Tue --> last Tuesday
  15380. etc.
  15381. Furthermore you can specify a relative date by giving, as the *first* thing
  15382. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15383. change in days weeks, months, years.
  15384. With a single plus or minus, the date is relative to today. With a double
  15385. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15386. +4d --> four days from today
  15387. +4 --> same as above
  15388. +2w --> two weeks from today
  15389. ++5 --> five days from default date
  15390. The function understands only English month and weekday abbreviations.
  15391. While prompting, a calendar is popped up - you can also select the
  15392. date with the mouse (button 1). The calendar shows a period of three
  15393. months. To scroll it to other months, use the keys `>' and `<'.
  15394. If you don't like the calendar, turn it off with
  15395. (setq org-read-date-popup-calendar nil)
  15396. With optional argument TO-TIME, the date will immediately be converted
  15397. to an internal time.
  15398. With an optional argument WITH-TIME, the prompt will suggest to
  15399. also insert a time. Note that when WITH-TIME is not set, you can
  15400. still enter a time, and this function will inform the calling routine
  15401. about this change. The calling routine may then choose to change the
  15402. format used to insert the time stamp into the buffer to include the time.
  15403. With optional argument FROM-STRING, read from this string instead from
  15404. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15405. the time/date that is used for everything that is not specified by the
  15406. user."
  15407. (require 'parse-time)
  15408. (let* ((org-with-time with-time)
  15409. (org-time-stamp-rounding-minutes
  15410. (if (equal org-with-time '(16))
  15411. '(0 0)
  15412. org-time-stamp-rounding-minutes))
  15413. (org-dcst org-display-custom-times)
  15414. (ct (org-current-time))
  15415. (org-def (or org-overriding-default-time default-time ct))
  15416. (org-defdecode (decode-time org-def))
  15417. (cur-frame (selected-frame))
  15418. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15419. (calendar-setup
  15420. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15421. (calendar-move-hook nil)
  15422. (calendar-view-diary-initially-flag nil)
  15423. (calendar-view-holidays-initially-flag nil)
  15424. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15425. ;; Rationalize `org-def' and `org-defdecode', if required.
  15426. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15427. (setf (nth 2 org-defdecode) -1)
  15428. (setf (nth 1 org-defdecode) 59)
  15429. (setq org-def (apply #'encode-time org-defdecode))
  15430. (setq org-defdecode (decode-time org-def)))
  15431. (let* ((timestr (format-time-string
  15432. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15433. org-def))
  15434. (prompt (concat (if prompt (concat prompt " ") "")
  15435. (format "Date+time [%s]: " timestr))))
  15436. (cond
  15437. (from-string (setq ans from-string))
  15438. (org-read-date-popup-calendar
  15439. (save-excursion
  15440. (save-window-excursion
  15441. (calendar)
  15442. (when (eq calendar-setup 'calendar-only)
  15443. (setq cal-frame
  15444. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15445. (select-frame cal-frame))
  15446. (org-eval-in-calendar '(setq cursor-type nil) t)
  15447. (unwind-protect
  15448. (progn
  15449. (calendar-forward-day (- (time-to-days org-def)
  15450. (calendar-absolute-from-gregorian
  15451. (calendar-current-date))))
  15452. (org-eval-in-calendar nil t)
  15453. (let* ((old-map (current-local-map))
  15454. (map (copy-keymap calendar-mode-map))
  15455. (minibuffer-local-map
  15456. (copy-keymap org-read-date-minibuffer-local-map)))
  15457. (org-defkey map (kbd "RET") 'org-calendar-select)
  15458. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15459. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15460. (unwind-protect
  15461. (progn
  15462. (use-local-map map)
  15463. (setq org-read-date-inactive inactive)
  15464. (add-hook 'post-command-hook 'org-read-date-display)
  15465. (setq org-ans0
  15466. (read-string prompt
  15467. default-input
  15468. 'org-read-date-history
  15469. nil))
  15470. ;; org-ans0: from prompt
  15471. ;; org-ans1: from mouse click
  15472. ;; org-ans2: from calendar motion
  15473. (setq ans
  15474. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15475. (remove-hook 'post-command-hook 'org-read-date-display)
  15476. (use-local-map old-map)
  15477. (when org-read-date-overlay
  15478. (delete-overlay org-read-date-overlay)
  15479. (setq org-read-date-overlay nil)))))
  15480. (bury-buffer "*Calendar*")
  15481. (when cal-frame
  15482. (delete-frame cal-frame)
  15483. (select-frame-set-input-focus cur-frame))))))
  15484. (t ; Naked prompt only
  15485. (unwind-protect
  15486. (setq ans (read-string prompt default-input
  15487. 'org-read-date-history timestr))
  15488. (when org-read-date-overlay
  15489. (delete-overlay org-read-date-overlay)
  15490. (setq org-read-date-overlay nil))))))
  15491. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15492. (when org-read-date-analyze-forced-year
  15493. (message "Year was forced into %s"
  15494. (if org-read-date-force-compatible-dates
  15495. "compatible range (1970-2037)"
  15496. "range representable on this machine"))
  15497. (ding))
  15498. ;; One round trip to get rid of 34th of August and stuff like that....
  15499. (setq final (decode-time (apply 'encode-time final)))
  15500. (setq org-read-date-final-answer ans)
  15501. (if to-time
  15502. (apply 'encode-time final)
  15503. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15504. (format "%04d-%02d-%02d %02d:%02d"
  15505. (nth 5 final) (nth 4 final) (nth 3 final)
  15506. (nth 2 final) (nth 1 final))
  15507. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15508. (defun org-read-date-display ()
  15509. "Display the current date prompt interpretation in the minibuffer."
  15510. (when org-read-date-display-live
  15511. (when org-read-date-overlay
  15512. (delete-overlay org-read-date-overlay))
  15513. (when (minibufferp (current-buffer))
  15514. (save-excursion
  15515. (end-of-line 1)
  15516. (while (not (equal (buffer-substring
  15517. (max (point-min) (- (point) 4)) (point))
  15518. " "))
  15519. (insert " ")))
  15520. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15521. " " (or org-ans1 org-ans2)))
  15522. (org-end-time-was-given nil)
  15523. (f (org-read-date-analyze ans org-def org-defdecode))
  15524. (fmts (if org-dcst
  15525. org-time-stamp-custom-formats
  15526. org-time-stamp-formats))
  15527. (fmt (if (or org-with-time
  15528. (and (boundp 'org-time-was-given) org-time-was-given))
  15529. (cdr fmts)
  15530. (car fmts)))
  15531. (txt (format-time-string fmt (apply 'encode-time f)))
  15532. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15533. (txt (concat "=> " txt)))
  15534. (when (and org-end-time-was-given
  15535. (string-match org-plain-time-of-day-regexp txt))
  15536. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15537. org-end-time-was-given
  15538. (substring txt (match-end 0)))))
  15539. (when org-read-date-analyze-futurep
  15540. (setq txt (concat txt " (=>F)")))
  15541. (setq org-read-date-overlay
  15542. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15543. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15544. (defun org-read-date-analyze (ans def defdecode)
  15545. "Analyze the combined answer of the date prompt."
  15546. ;; FIXME: cleanup and comment
  15547. ;; Pass `current-time' result to `decode-time' (instead of calling
  15548. ;; without arguments) so that only `current-time' has to be
  15549. ;; overriden in tests.
  15550. (let ((org-def def)
  15551. (org-defdecode defdecode)
  15552. (nowdecode (decode-time (current-time)))
  15553. delta deltan deltaw deltadef year month day
  15554. hour minute second wday pm h2 m2 tl wday1
  15555. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15556. (setq org-read-date-analyze-futurep nil
  15557. org-read-date-analyze-forced-year nil)
  15558. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15559. (setq ans "+0"))
  15560. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15561. (setq ans (replace-match "" t t ans)
  15562. deltan (car delta)
  15563. deltaw (nth 1 delta)
  15564. deltadef (nth 2 delta)))
  15565. ;; Check if there is an iso week date in there. If yes, store the
  15566. ;; info and postpone interpreting it until the rest of the parsing
  15567. ;; is done.
  15568. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15569. (setq iso-year (when (match-end 1)
  15570. (org-small-year-to-year
  15571. (string-to-number (match-string 1 ans))))
  15572. iso-weekday (when (match-end 3)
  15573. (string-to-number (match-string 3 ans)))
  15574. iso-week (string-to-number (match-string 2 ans)))
  15575. (setq ans (replace-match "" t t ans)))
  15576. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15577. (when (string-match
  15578. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15579. (setq year (if (match-end 2)
  15580. (string-to-number (match-string 2 ans))
  15581. (progn (setq kill-year t)
  15582. (string-to-number (format-time-string "%Y"))))
  15583. month (string-to-number (match-string 3 ans))
  15584. day (string-to-number (match-string 4 ans)))
  15585. (setq year (org-small-year-to-year year))
  15586. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15587. t nil ans)))
  15588. ;; Help matching dotted european dates
  15589. (when (string-match
  15590. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15591. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15592. (setq kill-year t)
  15593. (string-to-number (format-time-string "%Y")))
  15594. day (string-to-number (match-string 1 ans))
  15595. month (string-to-number (match-string 2 ans))
  15596. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15597. t nil ans)))
  15598. ;; Help matching american dates, like 5/30 or 5/30/7
  15599. (when (string-match
  15600. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15601. (setq year (if (match-end 4)
  15602. (string-to-number (match-string 4 ans))
  15603. (progn (setq kill-year t)
  15604. (string-to-number (format-time-string "%Y"))))
  15605. month (string-to-number (match-string 1 ans))
  15606. day (string-to-number (match-string 2 ans)))
  15607. (setq year (org-small-year-to-year year))
  15608. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15609. t nil ans)))
  15610. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15611. ;; If there is a time with am/pm, and *no* time without it, we convert
  15612. ;; so that matching will be successful.
  15613. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15614. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15615. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15616. (setq hour (string-to-number (match-string 1 ans))
  15617. minute (if (match-end 3)
  15618. (string-to-number (match-string 3 ans))
  15619. 0)
  15620. pm (equal ?p
  15621. (string-to-char (downcase (match-string 4 ans)))))
  15622. (if (and (= hour 12) (not pm))
  15623. (setq hour 0)
  15624. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15625. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15626. t t ans))))
  15627. ;; Check if a time range is given as a duration
  15628. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15629. (setq hour (string-to-number (match-string 1 ans))
  15630. h2 (+ hour (string-to-number (match-string 3 ans)))
  15631. minute (string-to-number (match-string 2 ans))
  15632. m2 (+ minute (if (match-end 5) (string-to-number
  15633. (match-string 5 ans))0)))
  15634. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15635. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15636. t t ans)))
  15637. ;; Check if there is a time range
  15638. (when (boundp 'org-end-time-was-given)
  15639. (setq org-time-was-given nil)
  15640. (when (and (string-match org-plain-time-of-day-regexp ans)
  15641. (match-end 8))
  15642. (setq org-end-time-was-given (match-string 8 ans))
  15643. (setq ans (concat (substring ans 0 (match-beginning 7))
  15644. (substring ans (match-end 7))))))
  15645. (setq tl (parse-time-string ans)
  15646. day (or (nth 3 tl) (nth 3 org-defdecode))
  15647. month
  15648. (cond ((nth 4 tl))
  15649. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15650. ;; Day was specified. Make sure DAY+MONTH
  15651. ;; combination happens in the future.
  15652. ((nth 3 tl)
  15653. (setq futurep t)
  15654. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15655. (nth 4 nowdecode)))
  15656. (t (nth 4 org-defdecode)))
  15657. year
  15658. (cond ((and (not kill-year) (nth 5 tl)))
  15659. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15660. ;; Month was guessed in the future and is at least
  15661. ;; equal to NOWDECODE's. Fix year accordingly.
  15662. (futurep
  15663. (if (or (> month (nth 4 nowdecode))
  15664. (>= day (nth 3 nowdecode)))
  15665. (nth 5 nowdecode)
  15666. (1+ (nth 5 nowdecode))))
  15667. ;; Month was specified. Make sure MONTH+YEAR
  15668. ;; combination happens in the future.
  15669. ((nth 4 tl)
  15670. (setq futurep t)
  15671. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15672. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15673. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15674. (t (nth 5 nowdecode))))
  15675. (t (nth 5 org-defdecode)))
  15676. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15677. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15678. second (or (nth 0 tl) 0)
  15679. wday (nth 6 tl))
  15680. (when (and (eq org-read-date-prefer-future 'time)
  15681. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15682. (equal day (nth 3 nowdecode))
  15683. (equal month (nth 4 nowdecode))
  15684. (equal year (nth 5 nowdecode))
  15685. (nth 2 tl)
  15686. (or (< (nth 2 tl) (nth 2 nowdecode))
  15687. (and (= (nth 2 tl) (nth 2 nowdecode))
  15688. (nth 1 tl)
  15689. (< (nth 1 tl) (nth 1 nowdecode)))))
  15690. (setq day (1+ day)
  15691. futurep t))
  15692. ;; Special date definitions below
  15693. (cond
  15694. (iso-week
  15695. ;; There was an iso week
  15696. (require 'cal-iso)
  15697. (setq futurep nil)
  15698. (setq year (or iso-year year)
  15699. day (or iso-weekday wday 1)
  15700. wday nil ; to make sure that the trigger below does not match
  15701. iso-date (calendar-gregorian-from-absolute
  15702. (calendar-iso-to-absolute
  15703. (list iso-week day year))))
  15704. ; FIXME: Should we also push ISO weeks into the future?
  15705. ; (when (and org-read-date-prefer-future
  15706. ; (not iso-year)
  15707. ; (< (calendar-absolute-from-gregorian iso-date)
  15708. ; (time-to-days (current-time))))
  15709. ; (setq year (1+ year)
  15710. ; iso-date (calendar-gregorian-from-absolute
  15711. ; (calendar-iso-to-absolute
  15712. ; (list iso-week day year)))))
  15713. (setq month (car iso-date)
  15714. year (nth 2 iso-date)
  15715. day (nth 1 iso-date)))
  15716. (deltan
  15717. (setq futurep nil)
  15718. (unless deltadef
  15719. ;; Pass `current-time' result to `decode-time' (instead of
  15720. ;; calling without arguments) so that only `current-time' has
  15721. ;; to be overriden in tests.
  15722. (let ((now (decode-time (current-time))))
  15723. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15724. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15725. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15726. ((equal deltaw "m") (setq month (+ month deltan)))
  15727. ((equal deltaw "y") (setq year (+ year deltan)))))
  15728. ((and wday (not (nth 3 tl)))
  15729. ;; Weekday was given, but no day, so pick that day in the week
  15730. ;; on or after the derived date.
  15731. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15732. (unless (equal wday wday1)
  15733. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15734. (when (and (boundp 'org-time-was-given)
  15735. (nth 2 tl))
  15736. (setq org-time-was-given t))
  15737. (when (< year 100) (setq year (+ 2000 year)))
  15738. ;; Check of the date is representable
  15739. (if org-read-date-force-compatible-dates
  15740. (progn
  15741. (when (< year 1970)
  15742. (setq year 1970 org-read-date-analyze-forced-year t))
  15743. (when (> year 2037)
  15744. (setq year 2037 org-read-date-analyze-forced-year t)))
  15745. (condition-case nil
  15746. (ignore (encode-time second minute hour day month year))
  15747. (error
  15748. (setq year (nth 5 org-defdecode))
  15749. (setq org-read-date-analyze-forced-year t))))
  15750. (setq org-read-date-analyze-futurep futurep)
  15751. (list second minute hour day month year)))
  15752. (defvar parse-time-weekdays)
  15753. (defun org-read-date-get-relative (s today default)
  15754. "Check string S for special relative date string.
  15755. TODAY and DEFAULT are internal times, for today and for a default.
  15756. Return shift list (N what def-flag)
  15757. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15758. N is the number of WHATs to shift.
  15759. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15760. the DEFAULT date rather than TODAY."
  15761. (require 'parse-time)
  15762. (when (and
  15763. (string-match
  15764. (concat
  15765. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15766. "\\([0-9]+\\)?"
  15767. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15768. "\\([ \t]\\|$\\)") s)
  15769. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15770. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15771. (string-to-char (substring (match-string 1 s) -1))
  15772. ?+))
  15773. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15774. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15775. (what (if (match-end 3) (match-string 3 s) "d"))
  15776. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15777. (date (if rel default today))
  15778. (wday (nth 6 (decode-time date)))
  15779. delta)
  15780. (if wday1
  15781. (progn
  15782. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15783. (when (= delta 0) (setq delta 7))
  15784. (when (= dir ?-)
  15785. (setq delta (- delta 7))
  15786. (when (= delta 0) (setq delta -7)))
  15787. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15788. (list delta "d" rel))
  15789. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15790. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15791. "Turn a user-specified date into the internal representation.
  15792. The internal representation needed by the calendar is (month day year).
  15793. This is a wrapper to handle the brain-dead convention in calendar that
  15794. user function argument order change dependent on argument order."
  15795. (pcase calendar-date-style
  15796. (`american (list arg1 arg2 arg3))
  15797. (`european (list arg2 arg1 arg3))
  15798. (`iso (list arg2 arg3 arg1))))
  15799. (defun org-eval-in-calendar (form &optional keepdate)
  15800. "Eval FORM in the calendar window and return to current window.
  15801. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15802. (let ((sf (selected-frame))
  15803. (sw (selected-window)))
  15804. (select-window (get-buffer-window "*Calendar*" t))
  15805. (eval form)
  15806. (when (and (not keepdate) (calendar-cursor-to-date))
  15807. (let* ((date (calendar-cursor-to-date))
  15808. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15809. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15810. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15811. (select-window sw)
  15812. (select-frame-set-input-focus sf)))
  15813. (defun org-calendar-select ()
  15814. "Return to `org-read-date' with the date currently selected.
  15815. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15816. (interactive)
  15817. (when (calendar-cursor-to-date)
  15818. (let* ((date (calendar-cursor-to-date))
  15819. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15820. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15821. (when (active-minibuffer-window) (exit-minibuffer))))
  15822. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15823. "Insert a date stamp for the date given by the internal TIME.
  15824. See `format-time-string' for the format of TIME.
  15825. WITH-HM means use the stamp format that includes the time of the day.
  15826. INACTIVE means use square brackets instead of angular ones, so that the
  15827. stamp will not contribute to the agenda.
  15828. PRE and POST are optional strings to be inserted before and after the
  15829. stamp.
  15830. The command returns the inserted time stamp."
  15831. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15832. stamp)
  15833. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15834. (insert-before-markers (or pre ""))
  15835. (when (listp extra)
  15836. (setq extra (car extra))
  15837. (if (and (stringp extra)
  15838. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15839. (setq extra (format "-%02d:%02d"
  15840. (string-to-number (match-string 1 extra))
  15841. (string-to-number (match-string 2 extra))))
  15842. (setq extra nil)))
  15843. (when extra
  15844. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15845. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15846. (insert-before-markers (or post ""))
  15847. (setq org-last-inserted-timestamp stamp)))
  15848. (defun org-toggle-time-stamp-overlays ()
  15849. "Toggle the use of custom time stamp formats."
  15850. (interactive)
  15851. (setq org-display-custom-times (not org-display-custom-times))
  15852. (unless org-display-custom-times
  15853. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15854. (while (setq p (next-single-property-change p 'display))
  15855. (when (and (get-text-property p 'display)
  15856. (eq (get-text-property p 'face) 'org-date))
  15857. (remove-text-properties
  15858. p (setq p (next-single-property-change p 'display))
  15859. '(display t))))
  15860. (set-buffer-modified-p bmp)))
  15861. (org-restart-font-lock)
  15862. (setq org-table-may-need-update t)
  15863. (if org-display-custom-times
  15864. (message "Time stamps are overlaid with custom format")
  15865. (message "Time stamp overlays removed")))
  15866. (defun org-display-custom-time (beg end)
  15867. "Overlay modified time stamp format over timestamp between BEG and END."
  15868. (let* ((ts (buffer-substring beg end))
  15869. t1 w1 with-hm tf time str w2 (off 0))
  15870. (save-match-data
  15871. (setq t1 (org-parse-time-string ts t))
  15872. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15873. (setq off (- (match-end 0) (match-beginning 0)))))
  15874. (setq end (- end off))
  15875. (setq w1 (- end beg)
  15876. with-hm (and (nth 1 t1) (nth 2 t1))
  15877. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15878. time (org-fix-decoded-time t1)
  15879. str (org-add-props
  15880. (format-time-string
  15881. (substring tf 1 -1) (apply 'encode-time time))
  15882. nil 'mouse-face 'highlight)
  15883. w2 (length str))
  15884. (unless (= w2 w1)
  15885. (add-text-properties (1+ beg) (+ 2 beg)
  15886. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15887. (put-text-property beg end 'display str)))
  15888. (defun org-fix-decoded-time (time)
  15889. "Set 0 instead of nil for the first 6 elements of time.
  15890. Don't touch the rest."
  15891. (let ((n 0))
  15892. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15893. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15894. "Difference between TIMESTAMP-STRING and now in days.
  15895. If SECONDS is non-nil, return the difference in seconds."
  15896. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15897. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15898. (funcall fdiff (current-time)))))
  15899. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15900. "Is the time in TIMESTAMP-STRING close to the current date?"
  15901. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15902. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15903. (not (org-entry-is-done-p))))
  15904. (defun org-get-wdays (ts &optional delay zero-delay)
  15905. "Get the deadline lead time appropriate for timestring TS.
  15906. When DELAY is non-nil, get the delay time for scheduled items
  15907. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15908. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15909. don't try to find the delay cookie in the scheduled timestamp."
  15910. (let ((tv (if delay org-scheduled-delay-days
  15911. org-deadline-warning-days)))
  15912. (cond
  15913. ((or (and delay (< tv 0))
  15914. (and delay zero-delay (<= tv 0))
  15915. (and (not delay) (<= tv 0)))
  15916. ;; Enforce this value no matter what
  15917. (- tv))
  15918. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15919. ;; lead time is specified.
  15920. (floor (* (string-to-number (match-string 1 ts))
  15921. (cdr (assoc (match-string 2 ts)
  15922. '(("d" . 1) ("w" . 7)
  15923. ("m" . 30.4) ("y" . 365.25)
  15924. ("h" . 0.041667)))))))
  15925. ;; go for the default.
  15926. (t tv))))
  15927. (defun org-calendar-select-mouse (ev)
  15928. "Return to `org-read-date' with the date currently selected.
  15929. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15930. (interactive "e")
  15931. (mouse-set-point ev)
  15932. (when (calendar-cursor-to-date)
  15933. (let* ((date (calendar-cursor-to-date))
  15934. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15935. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15936. (when (active-minibuffer-window) (exit-minibuffer))))
  15937. (defun org-check-deadlines (ndays)
  15938. "Check if there are any deadlines due or past due.
  15939. A deadline is considered due if it happens within `org-deadline-warning-days'
  15940. days from today's date. If the deadline appears in an entry marked DONE,
  15941. it is not shown. The prefix arg NDAYS can be used to test that many
  15942. days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
  15943. (interactive "P")
  15944. (let* ((org-warn-days
  15945. (cond
  15946. ((equal ndays '(4)) 100000)
  15947. (ndays (prefix-numeric-value ndays))
  15948. (t (abs org-deadline-warning-days))))
  15949. (case-fold-search nil)
  15950. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15951. (callback
  15952. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15953. (message "%d deadlines past-due or due within %d days"
  15954. (org-occur regexp nil callback)
  15955. org-warn-days)))
  15956. (defsubst org-re-timestamp (type)
  15957. "Return a regexp for timestamp TYPE.
  15958. Allowed values for TYPE are:
  15959. all: all timestamps
  15960. active: only active timestamps (<...>)
  15961. inactive: only inactive timestamps ([...])
  15962. scheduled: only scheduled timestamps
  15963. deadline: only deadline timestamps
  15964. closed: only closed time-stamps
  15965. When TYPE is nil, fall back on returning a regexp that matches
  15966. both scheduled and deadline timestamps."
  15967. (cl-case type
  15968. (all org-ts-regexp-both)
  15969. (active org-ts-regexp)
  15970. (inactive org-ts-regexp-inactive)
  15971. (scheduled org-scheduled-time-regexp)
  15972. (deadline org-deadline-time-regexp)
  15973. (closed org-closed-time-regexp)
  15974. (otherwise
  15975. (concat "\\<"
  15976. (regexp-opt (list org-deadline-string org-scheduled-string))
  15977. " *<\\([^>]+\\)>"))))
  15978. (defun org-check-before-date (d)
  15979. "Check if there are deadlines or scheduled entries before date D."
  15980. (interactive (list (org-read-date)))
  15981. (let* ((case-fold-search nil)
  15982. (regexp (org-re-timestamp org-ts-type))
  15983. (ts-type org-ts-type)
  15984. (callback
  15985. (lambda ()
  15986. (let ((match (match-string 1)))
  15987. (and (if (memq ts-type '(active inactive all))
  15988. (eq (org-element-type (save-excursion
  15989. (backward-char)
  15990. (org-element-context)))
  15991. 'timestamp)
  15992. (org-at-planning-p))
  15993. (time-less-p
  15994. (org-time-string-to-time match)
  15995. (org-time-string-to-time d)))))))
  15996. (message "%d entries before %s"
  15997. (org-occur regexp nil callback)
  15998. d)))
  15999. (defun org-check-after-date (d)
  16000. "Check if there are deadlines or scheduled entries after date D."
  16001. (interactive (list (org-read-date)))
  16002. (let* ((case-fold-search nil)
  16003. (regexp (org-re-timestamp org-ts-type))
  16004. (ts-type org-ts-type)
  16005. (callback
  16006. (lambda ()
  16007. (let ((match (match-string 1)))
  16008. (and (if (memq ts-type '(active inactive all))
  16009. (eq (org-element-type (save-excursion
  16010. (backward-char)
  16011. (org-element-context)))
  16012. 'timestamp)
  16013. (org-at-planning-p))
  16014. (not (time-less-p
  16015. (org-time-string-to-time match)
  16016. (org-time-string-to-time d))))))))
  16017. (message "%d entries after %s"
  16018. (org-occur regexp nil callback)
  16019. d)))
  16020. (defun org-check-dates-range (start-date end-date)
  16021. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16022. (interactive (list (org-read-date nil nil nil "Range starts")
  16023. (org-read-date nil nil nil "Range end")))
  16024. (let ((case-fold-search nil)
  16025. (regexp (org-re-timestamp org-ts-type))
  16026. (callback
  16027. (let ((type org-ts-type))
  16028. (lambda ()
  16029. (let ((match (match-string 1)))
  16030. (and
  16031. (if (memq type '(active inactive all))
  16032. (eq (org-element-type (save-excursion
  16033. (backward-char)
  16034. (org-element-context)))
  16035. 'timestamp)
  16036. (org-at-planning-p))
  16037. (not (time-less-p
  16038. (org-time-string-to-time match)
  16039. (org-time-string-to-time start-date)))
  16040. (time-less-p
  16041. (org-time-string-to-time match)
  16042. (org-time-string-to-time end-date))))))))
  16043. (message "%d entries between %s and %s"
  16044. (org-occur regexp nil callback) start-date end-date)))
  16045. (defun org-evaluate-time-range (&optional to-buffer)
  16046. "Evaluate a time range by computing the difference between start and end.
  16047. Normally the result is just printed in the echo area, but with prefix arg
  16048. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16049. If the time range is actually in a table, the result is inserted into the
  16050. next column.
  16051. For time difference computation, a year is assumed to be exactly 365
  16052. days in order to avoid rounding problems."
  16053. (interactive "P")
  16054. (or
  16055. (org-clock-update-time-maybe)
  16056. (save-excursion
  16057. (unless (org-at-date-range-p t)
  16058. (goto-char (point-at-bol))
  16059. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16060. (unless (org-at-date-range-p t)
  16061. (user-error "Not at a time-stamp range, and none found in current line")))
  16062. (let* ((ts1 (match-string 1))
  16063. (ts2 (match-string 2))
  16064. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16065. (match-end (match-end 0))
  16066. (time1 (org-time-string-to-time ts1))
  16067. (time2 (org-time-string-to-time ts2))
  16068. (t1 (float-time time1))
  16069. (t2 (float-time time2))
  16070. (diff (abs (- t2 t1)))
  16071. (negative (< (- t2 t1) 0))
  16072. ;; (ys (floor (* 365 24 60 60)))
  16073. (ds (* 24 60 60))
  16074. (hs (* 60 60))
  16075. (fy "%dy %dd %02d:%02d")
  16076. (fy1 "%dy %dd")
  16077. (fd "%dd %02d:%02d")
  16078. (fd1 "%dd")
  16079. (fh "%02d:%02d")
  16080. y d h m align)
  16081. (if havetime
  16082. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16083. y 0
  16084. d (floor (/ diff ds)) diff (mod diff ds)
  16085. h (floor (/ diff hs)) diff (mod diff hs)
  16086. m (floor (/ diff 60)))
  16087. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16088. y 0
  16089. d (floor (+ (/ diff ds) 0.5))
  16090. h 0 m 0))
  16091. (if (not to-buffer)
  16092. (message "%s" (org-make-tdiff-string y d h m))
  16093. (if (org-at-table-p)
  16094. (progn
  16095. (goto-char match-end)
  16096. (setq align t)
  16097. (and (looking-at " *|") (goto-char (match-end 0))))
  16098. (goto-char match-end))
  16099. (when (looking-at
  16100. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16101. (replace-match ""))
  16102. (when negative (insert " -"))
  16103. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16104. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16105. (insert " " (format fh h m))))
  16106. (when align (org-table-align))
  16107. (message "Time difference inserted")))))
  16108. (defun org-make-tdiff-string (y d h m)
  16109. (let ((fmt "")
  16110. (l nil))
  16111. (when (> y 0)
  16112. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16113. (push y l))
  16114. (when (> d 0)
  16115. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16116. (push d l))
  16117. (when (> h 0)
  16118. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16119. (push h l))
  16120. (when (> m 0)
  16121. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16122. (push m l))
  16123. (apply 'format fmt (nreverse l))))
  16124. (defun org-time-string-to-time (s &optional buffer pos)
  16125. "Convert a timestamp string into internal time."
  16126. (condition-case errdata
  16127. (apply 'encode-time (org-parse-time-string s))
  16128. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16129. s (if (not (and buffer pos))
  16130. ""
  16131. (format-message " at %d in buffer `%s'" pos buffer))
  16132. (cdr errdata)))))
  16133. (defun org-time-string-to-seconds (s)
  16134. "Convert a timestamp string to a number of seconds."
  16135. (float-time (org-time-string-to-time s)))
  16136. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16137. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16138. "Convert time stamp S to an absolute day number.
  16139. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16140. stamp, get the closest date to DAYNR. If PREFER is
  16141. `past' (respectively `future') return a date past (respectively
  16142. after) or equal to DAYNR.
  16143. POS is the location of time stamp S, as a buffer position in
  16144. BUFFER.
  16145. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16146. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16147. signalled."
  16148. (cond
  16149. ((string-match "\\`%%\\((.*)\\)" s)
  16150. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16151. ;; only able to match individual dates. If it fails, raise an
  16152. ;; error.
  16153. (if (and daynr
  16154. (org-diary-sexp-entry
  16155. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16156. daynr
  16157. (signal 'org-diary-sexp-no-match (list s))))
  16158. ((and daynr show-all) (org-closest-date s daynr prefer))
  16159. (t (time-to-days
  16160. (condition-case errdata
  16161. (apply #'encode-time (org-parse-time-string s))
  16162. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16163. s
  16164. (if (not (and buffer pos)) ""
  16165. (format-message " at %d in buffer `%s'" pos buffer))
  16166. (cdr errdata))))))))
  16167. (defun org-days-to-iso-week (days)
  16168. "Return the iso week number."
  16169. (require 'cal-iso)
  16170. (car (calendar-iso-from-absolute days)))
  16171. (defun org-small-year-to-year (year)
  16172. "Convert 2-digit years into 4-digit years.
  16173. YEAR is expanded into one of the 30 next years, if possible, or
  16174. into a past one. Any year larger than 99 is returned unchanged."
  16175. (if (>= year 100) year
  16176. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16177. (century (/ current 100))
  16178. (offset (- year (% current 100))))
  16179. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16180. ((> offset -70) (+ (* century 100) year))
  16181. (t (+ (* (1+ century) 100) year))))))
  16182. (defun org-time-from-absolute (d)
  16183. "Return the time corresponding to date D.
  16184. D may be an absolute day number, or a calendar-type list (month day year)."
  16185. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16186. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16187. (defvar org-agenda-current-date)
  16188. (defun org-calendar-holiday ()
  16189. "List of holidays, for Diary display in Org mode."
  16190. (require 'holidays)
  16191. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16192. (and hl (mapconcat #'identity hl "; "))))
  16193. (defun org-diary-sexp-entry (sexp entry d)
  16194. "Process a SEXP diary ENTRY for date D."
  16195. (require 'diary-lib)
  16196. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16197. ;; dynamically.
  16198. (let* ((sexp `(let ((entry ,entry)
  16199. (date ',d))
  16200. ,(car (read-from-string sexp))))
  16201. (result (if calendar-debug-sexp (eval sexp)
  16202. (condition-case nil
  16203. (eval sexp)
  16204. (error
  16205. (beep)
  16206. (message "Bad sexp at line %d in %s: %s"
  16207. (org-current-line)
  16208. (buffer-file-name) sexp)
  16209. (sleep-for 2))))))
  16210. (cond ((stringp result) (split-string result "; "))
  16211. ((and (consp result)
  16212. (not (consp (cdr result)))
  16213. (stringp (cdr result))) (cdr result))
  16214. ((and (consp result)
  16215. (stringp (car result))) result)
  16216. (result entry))))
  16217. (defun org-diary-to-ical-string (frombuf)
  16218. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16219. This uses the icalendar.el library."
  16220. (let* ((tmpdir temporary-file-directory)
  16221. (tmpfile (make-temp-name
  16222. (expand-file-name "orgics" tmpdir)))
  16223. buf rtn b e)
  16224. (with-current-buffer frombuf
  16225. (icalendar-export-region (point-min) (point-max) tmpfile)
  16226. (setq buf (find-buffer-visiting tmpfile))
  16227. (set-buffer buf)
  16228. (goto-char (point-min))
  16229. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16230. (setq b (match-beginning 0)))
  16231. (goto-char (point-max))
  16232. (when (re-search-backward "^END:VEVENT" nil t)
  16233. (setq e (match-end 0)))
  16234. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16235. (kill-buffer buf)
  16236. (delete-file tmpfile)
  16237. rtn))
  16238. (defun org-closest-date (start current prefer)
  16239. "Return closest date to CURRENT starting from START.
  16240. CURRENT and START are both time stamps.
  16241. When PREFER is `past', return a date that is either CURRENT or
  16242. past. When PREFER is `future', return a date that is either
  16243. CURRENT or future.
  16244. Only time stamps with a repeater are modified. Any other time
  16245. stamp stay unchanged. In any case, return value is an absolute
  16246. day number."
  16247. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16248. ;; No repeater. Do not shift time stamp.
  16249. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16250. (let ((value (string-to-number (match-string 1 start)))
  16251. (type (match-string 2 start)))
  16252. (if (= 0 value)
  16253. ;; Repeater with a 0-value is considered as void.
  16254. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16255. (let* ((base (org-date-to-gregorian start))
  16256. (target (org-date-to-gregorian current))
  16257. (sday (calendar-absolute-from-gregorian base))
  16258. (cday (calendar-absolute-from-gregorian target))
  16259. n1 n2)
  16260. ;; If START is already past CURRENT, just return START.
  16261. (if (<= cday sday) sday
  16262. ;; Compute closest date before (N1) and closest date past
  16263. ;; (N2) CURRENT.
  16264. (pcase type
  16265. ("h"
  16266. (let ((missing-hours
  16267. (mod (+ (- (* 24 (- cday sday))
  16268. (nth 2 (org-parse-time-string start)))
  16269. org-extend-today-until)
  16270. value)))
  16271. (setf n1 (if (= missing-hours 0) cday
  16272. (- cday (1+ (/ missing-hours 24)))))
  16273. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16274. ((or "d" "w")
  16275. (let ((value (if (equal type "w") (* 7 value) value)))
  16276. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16277. (setf n2 (+ n1 value))))
  16278. ("m"
  16279. (let* ((add-months
  16280. (lambda (d n)
  16281. ;; Add N months to gregorian date D, i.e.,
  16282. ;; a list (MONTH DAY YEAR). Return a valid
  16283. ;; gregorian date.
  16284. (let ((m (+ (nth 0 d) n)))
  16285. (list (mod m 12)
  16286. (nth 1 d)
  16287. (+ (/ m 12) (nth 2 d))))))
  16288. (months ; Complete months to TARGET.
  16289. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16290. (- (nth 0 target) (nth 0 base))
  16291. ;; If START's day is greater than
  16292. ;; TARGET's, remove incomplete month.
  16293. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16294. value)
  16295. value))
  16296. (before (funcall add-months base months)))
  16297. (setf n1 (calendar-absolute-from-gregorian before))
  16298. (setf n2
  16299. (calendar-absolute-from-gregorian
  16300. (funcall add-months before value)))))
  16301. (_
  16302. (let* ((d (nth 1 base))
  16303. (m (nth 0 base))
  16304. (y (nth 2 base))
  16305. (years ; Complete years to TARGET.
  16306. (* (/ (- (nth 2 target)
  16307. y
  16308. ;; If START's month and day are
  16309. ;; greater than TARGET's, remove
  16310. ;; incomplete year.
  16311. (if (or (> (nth 0 target) m)
  16312. (and (= (nth 0 target) m)
  16313. (> (nth 1 target) d)))
  16314. 0
  16315. 1))
  16316. value)
  16317. value))
  16318. (before (list m d (+ y years))))
  16319. (setf n1 (calendar-absolute-from-gregorian before))
  16320. (setf n2 (calendar-absolute-from-gregorian
  16321. (list m d (+ (nth 2 before) value)))))))
  16322. ;; Handle PREFER parameter, if any.
  16323. (cond
  16324. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16325. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16326. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16327. (defun org-date-to-gregorian (d)
  16328. "Turn any specification of date D into a Gregorian date for the calendar."
  16329. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16330. ((and (listp d) (= (length d) 3)) d)
  16331. ((stringp d)
  16332. (let ((d (org-parse-time-string d)))
  16333. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16334. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16335. (defun org-parse-time-string (s &optional nodefault)
  16336. "Parse the standard Org-mode time string.
  16337. This should be a lot faster than the normal `parse-time-string'.
  16338. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16339. hour and minute fields will be nil if not given."
  16340. (cond ((string-match org-ts-regexp0 s)
  16341. (list 0
  16342. (when (or (match-beginning 8) (not nodefault))
  16343. (string-to-number (or (match-string 8 s) "0")))
  16344. (when (or (match-beginning 7) (not nodefault))
  16345. (string-to-number (or (match-string 7 s) "0")))
  16346. (string-to-number (match-string 4 s))
  16347. (string-to-number (match-string 3 s))
  16348. (string-to-number (match-string 2 s))
  16349. nil nil nil))
  16350. ((string-match "^<[^>]+>$" s)
  16351. (decode-time (seconds-to-time (org-matcher-time s))))
  16352. (t (error "Not a standard Org-mode time string: %s" s))))
  16353. (defun org-timestamp-up (&optional arg)
  16354. "Increase the date item at the cursor by one.
  16355. If the cursor is on the year, change the year. If it is on the month,
  16356. the day or the time, change that.
  16357. With prefix ARG, change by that many units."
  16358. (interactive "p")
  16359. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16360. (defun org-timestamp-down (&optional arg)
  16361. "Decrease the date item at the cursor by one.
  16362. If the cursor is on the year, change the year. If it is on the month,
  16363. the day or the time, change that.
  16364. With prefix ARG, change by that many units."
  16365. (interactive "p")
  16366. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16367. (defun org-timestamp-up-day (&optional arg)
  16368. "Increase the date in the time stamp by one day.
  16369. With prefix ARG, change that many days."
  16370. (interactive "p")
  16371. (if (and (not (org-at-timestamp-p t))
  16372. (org-at-heading-p))
  16373. (org-todo 'up)
  16374. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16375. (defun org-timestamp-down-day (&optional arg)
  16376. "Decrease the date in the time stamp by one day.
  16377. With prefix ARG, change that many days."
  16378. (interactive "p")
  16379. (if (and (not (org-at-timestamp-p t))
  16380. (org-at-heading-p))
  16381. (org-todo 'down)
  16382. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16383. (defun org-at-timestamp-p (&optional inactive-ok)
  16384. "Non-nil if point is inside a timestamp.
  16385. When optional argument INACTIVE-OK is non-nil, also consider
  16386. inactive timestamps.
  16387. When this function returns a non-nil value, match data is set
  16388. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16389. INACTIVE-OK."
  16390. (interactive)
  16391. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16392. (pos (point))
  16393. (ans (or (looking-at tsr)
  16394. (save-excursion
  16395. (skip-chars-backward "^[<\n\r\t")
  16396. (when (> (point) (point-min)) (backward-char 1))
  16397. (and (looking-at tsr)
  16398. (> (- (match-end 0) pos) -1))))))
  16399. (and ans
  16400. (boundp 'org-ts-what)
  16401. (setq org-ts-what
  16402. (cond
  16403. ((= pos (match-beginning 0)) 'bracket)
  16404. ;; Point is considered to be "on the bracket" whether
  16405. ;; it's really on it or right after it.
  16406. ((= pos (1- (match-end 0))) 'bracket)
  16407. ((= pos (match-end 0)) 'after)
  16408. ((org-pos-in-match-range pos 2) 'year)
  16409. ((org-pos-in-match-range pos 3) 'month)
  16410. ((org-pos-in-match-range pos 7) 'hour)
  16411. ((org-pos-in-match-range pos 8) 'minute)
  16412. ((or (org-pos-in-match-range pos 4)
  16413. (org-pos-in-match-range pos 5)) 'day)
  16414. ((and (> pos (or (match-end 8) (match-end 5)))
  16415. (< pos (match-end 0)))
  16416. (- pos (or (match-end 8) (match-end 5))))
  16417. (t 'day))))
  16418. ans))
  16419. (defun org-toggle-timestamp-type ()
  16420. "Toggle the type (<active> or [inactive]) of a time stamp."
  16421. (interactive)
  16422. (when (org-at-timestamp-p t)
  16423. (let ((beg (match-beginning 0)) (end (match-end 0))
  16424. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16425. (save-excursion
  16426. (goto-char beg)
  16427. (while (re-search-forward "[][<>]" end t)
  16428. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16429. t t)))
  16430. (message "Timestamp is now %sactive"
  16431. (if (equal (char-after beg) ?<) "" "in")))))
  16432. (defun org-at-clock-log-p nil
  16433. "Is the cursor on the clock log line?"
  16434. (save-excursion
  16435. (move-beginning-of-line 1)
  16436. (looking-at org-clock-line-re)))
  16437. (defvar org-clock-history) ; defined in org-clock.el
  16438. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16439. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16440. "Change the date in the time stamp at point.
  16441. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16442. `year', `minute', `second'. If WHAT is not given, the cursor position
  16443. in the timestamp determines what will be changed.
  16444. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16445. (let ((origin (point)) origin-cat
  16446. with-hm inactive
  16447. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16448. org-ts-what
  16449. extra rem
  16450. ts time time0 fixnext clrgx)
  16451. (unless (org-at-timestamp-p t)
  16452. (user-error "Not at a timestamp"))
  16453. (if (and (not what) (eq org-ts-what 'bracket))
  16454. (org-toggle-timestamp-type)
  16455. ;; Point isn't on brackets. Remember the part of the time-stamp
  16456. ;; the point was in. Indeed, size of time-stamps may change,
  16457. ;; but point must be kept in the same category nonetheless.
  16458. (setq origin-cat org-ts-what)
  16459. (when (and (not what) (not (eq org-ts-what 'day))
  16460. org-display-custom-times
  16461. (get-text-property (point) 'display)
  16462. (not (get-text-property (1- (point)) 'display)))
  16463. (setq org-ts-what 'day))
  16464. (setq org-ts-what (or what org-ts-what)
  16465. inactive (= (char-after (match-beginning 0)) ?\[)
  16466. ts (match-string 0))
  16467. (replace-match "")
  16468. (when (string-match
  16469. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16470. ts)
  16471. (setq extra (match-string 1 ts))
  16472. (when suppress-tmp-delay
  16473. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16474. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16475. (setq with-hm t))
  16476. (setq time0 (org-parse-time-string ts))
  16477. (when (and updown
  16478. (eq org-ts-what 'minute)
  16479. (not current-prefix-arg))
  16480. ;; This looks like s-up and s-down. Change by one rounding step.
  16481. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16482. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16483. (setcar (cdr time0) (+ (nth 1 time0)
  16484. (if (> n 0) (- rem) (- dm rem))))))
  16485. (setq time
  16486. (apply #'encode-time
  16487. (or (car time0) 0)
  16488. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16489. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16490. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16491. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16492. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16493. (nthcdr 6 time0)))
  16494. (when (and (member org-ts-what '(hour minute))
  16495. extra
  16496. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16497. (setq extra (org-modify-ts-extra
  16498. extra
  16499. (if (eq org-ts-what 'hour) 2 5)
  16500. n dm)))
  16501. (when (integerp org-ts-what)
  16502. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16503. (when (eq what 'calendar)
  16504. (let ((cal-date (org-get-date-from-calendar)))
  16505. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16506. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16507. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16508. (setcar time0 (or (car time0) 0))
  16509. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16510. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16511. (setq time (apply 'encode-time time0))))
  16512. ;; Insert the new time-stamp, and ensure point stays in the same
  16513. ;; category as before (i.e. not after the last position in that
  16514. ;; category).
  16515. (let ((pos (point)))
  16516. ;; Stay before inserted string. `save-excursion' is of no use.
  16517. (setq org-last-changed-timestamp
  16518. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16519. (goto-char pos))
  16520. (save-match-data
  16521. (looking-at org-ts-regexp3)
  16522. (goto-char (cond
  16523. ;; `day' category ends before `hour' if any, or at
  16524. ;; the end of the day name.
  16525. ((eq origin-cat 'day)
  16526. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16527. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16528. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16529. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16530. ;; `year' and `month' have both fixed size: point
  16531. ;; couldn't have moved into another part.
  16532. (t origin))))
  16533. ;; Update clock if on a CLOCK line.
  16534. (org-clock-update-time-maybe)
  16535. ;; Maybe adjust the closest clock in `org-clock-history'
  16536. (when org-clock-adjust-closest
  16537. (if (not (and (org-at-clock-log-p)
  16538. (< 1 (length (delq nil (mapcar 'marker-position
  16539. org-clock-history))))))
  16540. (message "No clock to adjust")
  16541. (cond ((save-excursion ; fix previous clock?
  16542. (re-search-backward org-ts-regexp0 nil t)
  16543. (looking-back (concat org-clock-string " \\[")
  16544. (line-beginning-position)))
  16545. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16546. ((save-excursion ; fix next clock?
  16547. (re-search-backward org-ts-regexp0 nil t)
  16548. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16549. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16550. (save-window-excursion
  16551. ;; Find closest clock to point, adjust the previous/next one in history
  16552. (let* ((p (save-excursion (org-back-to-heading t)))
  16553. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16554. (clfixnth
  16555. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16556. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16557. (if (not clfixpos)
  16558. (message "No clock to adjust")
  16559. (save-excursion
  16560. (org-goto-marker-or-bmk clfixpos)
  16561. (org-show-subtree)
  16562. (when (re-search-forward clrgx nil t)
  16563. (goto-char (match-beginning 1))
  16564. (let (org-clock-adjust-closest)
  16565. (org-timestamp-change n org-ts-what updown))
  16566. (message "Clock adjusted in %s for heading: %s"
  16567. (file-name-nondirectory (buffer-file-name))
  16568. (org-get-heading t t)))))))))
  16569. ;; Try to recenter the calendar window, if any.
  16570. (when (and org-calendar-follow-timestamp-change
  16571. (get-buffer-window "*Calendar*" t)
  16572. (memq org-ts-what '(day month year)))
  16573. (org-recenter-calendar (time-to-days time))))))
  16574. (defun org-modify-ts-extra (s pos n dm)
  16575. "Change the different parts of the lead-time and repeat fields in timestamp."
  16576. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16577. ng h m new rem)
  16578. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16579. (cond
  16580. ((or (org-pos-in-match-range pos 2)
  16581. (org-pos-in-match-range pos 3))
  16582. (setq m (string-to-number (match-string 3 s))
  16583. h (string-to-number (match-string 2 s)))
  16584. (if (org-pos-in-match-range pos 2)
  16585. (setq h (+ h n))
  16586. (setq n (* dm (with-no-warnings (signum n))))
  16587. (unless (= 0 (setq rem (% m dm)))
  16588. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16589. (setq m (+ m n)))
  16590. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16591. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16592. (setq h (mod h 24))
  16593. (setq ng 1 new (format "-%02d:%02d" h m)))
  16594. ((org-pos-in-match-range pos 6)
  16595. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16596. ((org-pos-in-match-range pos 5)
  16597. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16598. ((org-pos-in-match-range pos 9)
  16599. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16600. ((org-pos-in-match-range pos 8)
  16601. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16602. (when ng
  16603. (setq s (concat
  16604. (substring s 0 (match-beginning ng))
  16605. new
  16606. (substring s (match-end ng))))))
  16607. s))
  16608. (defun org-recenter-calendar (d)
  16609. "If the calendar is visible, recenter it to date D."
  16610. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16611. (when cwin
  16612. (let ((calendar-move-hook nil))
  16613. (with-selected-window cwin
  16614. (calendar-goto-date
  16615. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16616. (defun org-goto-calendar (&optional arg)
  16617. "Go to the Emacs calendar at the current date.
  16618. If there is a time stamp in the current line, go to that date.
  16619. A prefix ARG can be used to force the current date."
  16620. (interactive "P")
  16621. (let ((tsr org-ts-regexp) diff
  16622. (calendar-move-hook nil)
  16623. (calendar-view-holidays-initially-flag nil)
  16624. (calendar-view-diary-initially-flag nil))
  16625. (when (or (org-at-timestamp-p)
  16626. (save-excursion
  16627. (beginning-of-line 1)
  16628. (looking-at (concat ".*" tsr))))
  16629. (let ((d1 (time-to-days (current-time)))
  16630. (d2 (time-to-days
  16631. (org-time-string-to-time (match-string 1)))))
  16632. (setq diff (- d2 d1))))
  16633. (calendar)
  16634. (calendar-goto-today)
  16635. (when (and diff (not arg)) (calendar-forward-day diff))))
  16636. (defun org-get-date-from-calendar ()
  16637. "Return a list (month day year) of date at point in calendar."
  16638. (with-current-buffer "*Calendar*"
  16639. (save-match-data
  16640. (calendar-cursor-to-date))))
  16641. (defun org-date-from-calendar ()
  16642. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16643. If there is already a time stamp at the cursor position, update it."
  16644. (interactive)
  16645. (if (org-at-timestamp-p t)
  16646. (org-timestamp-change 0 'calendar)
  16647. (let ((cal-date (org-get-date-from-calendar)))
  16648. (org-insert-time-stamp
  16649. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16650. (defcustom org-effort-durations
  16651. `(("min" . 1)
  16652. ("h" . 60)
  16653. ("d" . ,(* 60 8))
  16654. ("w" . ,(* 60 8 5))
  16655. ("m" . ,(* 60 8 5 4))
  16656. ("y" . ,(* 60 8 5 40)))
  16657. "Conversion factor to minutes for an effort modifier.
  16658. Each entry has the form (MODIFIER . MINUTES).
  16659. In an effort string, a number followed by MODIFIER is multiplied
  16660. by the specified number of MINUTES to obtain an effort in
  16661. minutes.
  16662. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16663. effort string \"2hours\" is equivalent to 120 minutes."
  16664. :group 'org-agenda
  16665. :version "25.1"
  16666. :package-version '(Org . "8.3")
  16667. :type '(alist :key-type (string :tag "Modifier")
  16668. :value-type (number :tag "Minutes")))
  16669. (defun org-minutes-to-clocksum-string (m)
  16670. "Format number of minutes as a clocksum string.
  16671. The format is determined by `org-time-clocksum-format',
  16672. `org-time-clocksum-use-fractional' and
  16673. `org-time-clocksum-fractional-format' and
  16674. `org-time-clocksum-use-effort-durations'."
  16675. (let ((clocksum "")
  16676. (m (round m)) ; Don't allow fractions of minutes
  16677. h d w mo y fmt n)
  16678. (setq h (if org-time-clocksum-use-effort-durations
  16679. (cdr (assoc "h" org-effort-durations)) 60)
  16680. d (if org-time-clocksum-use-effort-durations
  16681. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16682. w (if org-time-clocksum-use-effort-durations
  16683. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16684. mo (if org-time-clocksum-use-effort-durations
  16685. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16686. y (if org-time-clocksum-use-effort-durations
  16687. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16688. ;; fractional format
  16689. (if org-time-clocksum-use-fractional
  16690. (cond
  16691. ;; single format string
  16692. ((stringp org-time-clocksum-fractional-format)
  16693. (format org-time-clocksum-fractional-format (/ m (float h))))
  16694. ;; choice of fractional formats for different time units
  16695. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16696. (> (/ (truncate m) (* y d h)) 0))
  16697. (format fmt (/ m (* y d (float h)))))
  16698. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16699. (> (/ (truncate m) (* mo d h)) 0))
  16700. (format fmt (/ m (* mo d (float h)))))
  16701. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16702. (> (/ (truncate m) (* w d h)) 0))
  16703. (format fmt (/ m (* w d (float h)))))
  16704. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16705. (> (/ (truncate m) (* d h)) 0))
  16706. (format fmt (/ m (* d (float h)))))
  16707. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16708. (> (/ (truncate m) h) 0))
  16709. (format fmt (/ m (float h))))
  16710. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16711. (format fmt m))
  16712. ;; fall back to smallest time unit with a format
  16713. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16714. (format fmt (/ m (float h))))
  16715. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16716. (format fmt (/ m (* d (float h)))))
  16717. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16718. (format fmt (/ m (* w d (float h)))))
  16719. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16720. (format fmt (/ m (* mo d (float h)))))
  16721. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16722. (format fmt (/ m (* y d (float h))))))
  16723. ;; standard (non-fractional) format, with single format string
  16724. (if (stringp org-time-clocksum-format)
  16725. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16726. ;; separate formats components
  16727. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16728. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16729. (plist-get org-time-clocksum-format :require-years))
  16730. (setq clocksum (concat clocksum (format fmt n))
  16731. m (- m (* n y d h))))
  16732. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16733. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16734. (plist-get org-time-clocksum-format :require-months))
  16735. (setq clocksum (concat clocksum (format fmt n))
  16736. m (- m (* n mo d h))))
  16737. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16738. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16739. (plist-get org-time-clocksum-format :require-weeks))
  16740. (setq clocksum (concat clocksum (format fmt n))
  16741. m (- m (* n w d h))))
  16742. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16743. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16744. (plist-get org-time-clocksum-format :require-days))
  16745. (setq clocksum (concat clocksum (format fmt n))
  16746. m (- m (* n d h))))
  16747. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16748. (or (> (setq n (/ (truncate m) h)) 0)
  16749. (plist-get org-time-clocksum-format :require-hours))
  16750. (setq clocksum (concat clocksum (format fmt n))
  16751. m (- m (* n h))))
  16752. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16753. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16754. (setq clocksum (concat clocksum (format fmt m))))
  16755. ;; return formatted time duration
  16756. clocksum))))
  16757. (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
  16758. (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
  16759. "Org mode version 8.0")
  16760. (defun org-hours-to-clocksum-string (n)
  16761. (org-minutes-to-clocksum-string (* n 60)))
  16762. (defun org-hh:mm-string-to-minutes (s)
  16763. "Convert a string H:MM to a number of minutes.
  16764. If the string is just a number, interpret it as minutes.
  16765. In fact, the first hh:mm or number in the string will be taken,
  16766. there can be extra stuff in the string.
  16767. If no number is found, the return value is 0."
  16768. (cond
  16769. ((integerp s) s)
  16770. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16771. (+ (* (string-to-number (match-string 1 s)) 60)
  16772. (string-to-number (match-string 2 s))))
  16773. ((string-match "\\([0-9]+\\)" s)
  16774. (string-to-number (match-string 1 s)))
  16775. (t 0)))
  16776. (defcustom org-image-actual-width t
  16777. "Should we use the actual width of images when inlining them?
  16778. When set to t, always use the image width.
  16779. When set to a number, use imagemagick (when available) to set
  16780. the image's width to this value.
  16781. When set to a number in a list, try to get the width from any
  16782. #+ATTR.* keyword if it matches a width specification like
  16783. #+ATTR_HTML: :width 300px
  16784. and fall back on that number if none is found.
  16785. When set to nil, try to get the width from an #+ATTR.* keyword
  16786. and fall back on the original width if none is found.
  16787. This requires Emacs >= 24.1, build with imagemagick support."
  16788. :group 'org-appearance
  16789. :version "24.4"
  16790. :package-version '(Org . "8.0")
  16791. :type '(choice
  16792. (const :tag "Use the image width" t)
  16793. (integer :tag "Use a number of pixels")
  16794. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16795. (const :tag "Use #+ATTR* or don't resize" nil)))
  16796. (defcustom org-agenda-inhibit-startup nil
  16797. "Inhibit startup when preparing agenda buffers.
  16798. When this variable is t, the initialization of the Org agenda
  16799. buffers is inhibited: e.g. the visibility state is not set, the
  16800. tables are not re-aligned, etc."
  16801. :type 'boolean
  16802. :version "24.3"
  16803. :group 'org-agenda)
  16804. (defcustom org-agenda-ignore-properties nil
  16805. "Avoid updating text properties when building the agenda.
  16806. Properties are used to prepare buffers for effort estimates,
  16807. appointments, statistics and subtree-local categories.
  16808. If you don't use these in the agenda, you can add them to this
  16809. list and agenda building will be a bit faster.
  16810. The value is a list, with zero or more of the symbols `effort', `appt',
  16811. `stats' or `category'."
  16812. :type '(set :greedy t
  16813. (const effort)
  16814. (const appt)
  16815. (const stats)
  16816. (const category))
  16817. :version "25.1"
  16818. :package-version '(Org . "8.3")
  16819. :group 'org-agenda)
  16820. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16821. "Convert a duration string S to minutes.
  16822. A bare number is interpreted as minutes, modifiers can be set by
  16823. customizing `org-effort-durations' (which see).
  16824. Entries containing a colon are interpreted as H:MM by
  16825. `org-hh:mm-string-to-minutes'."
  16826. (let ((result 0)
  16827. (re (concat "\\([0-9.]+\\) *\\("
  16828. (regexp-opt (mapcar 'car org-effort-durations))
  16829. "\\)")))
  16830. (while (string-match re s)
  16831. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16832. (string-to-number (match-string 1 s))))
  16833. (setq s (replace-match "" nil t s)))
  16834. (setq result (floor result))
  16835. (cl-incf result (org-hh:mm-string-to-minutes s))
  16836. (if output-to-string (number-to-string result) result)))
  16837. ;;;; Files
  16838. (defun org-save-all-org-buffers ()
  16839. "Save all Org-mode buffers without user confirmation."
  16840. (interactive)
  16841. (message "Saving all Org-mode buffers...")
  16842. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16843. (when (featurep 'org-id) (org-id-locations-save))
  16844. (message "Saving all Org-mode buffers... done"))
  16845. (defun org-revert-all-org-buffers ()
  16846. "Revert all Org-mode buffers.
  16847. Prompt for confirmation when there are unsaved changes.
  16848. Be sure you know what you are doing before letting this function
  16849. overwrite your changes.
  16850. This function is useful in a setup where one tracks org files
  16851. with a version control system, to revert on one machine after pulling
  16852. changes from another. I believe the procedure must be like this:
  16853. 1. M-x org-save-all-org-buffers
  16854. 2. Pull changes from the other machine, resolve conflicts
  16855. 3. M-x org-revert-all-org-buffers"
  16856. (interactive)
  16857. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16858. (user-error "Abort"))
  16859. (save-excursion
  16860. (save-window-excursion
  16861. (dolist (b (buffer-list))
  16862. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16863. (with-current-buffer b buffer-file-name))
  16864. (pop-to-buffer-same-window b)
  16865. (revert-buffer t 'no-confirm)))
  16866. (when (and (featurep 'org-id) org-id-track-globally)
  16867. (org-id-locations-load)))))
  16868. ;;;; Agenda files
  16869. ;;;###autoload
  16870. (defun org-switchb (&optional arg)
  16871. "Switch between Org buffers.
  16872. With \\[universal-argument] prefix, restrict available buffers to files.
  16873. With \\[universal-argument] \\[universal-argument] \
  16874. prefix, restrict available buffers to agenda files."
  16875. (interactive "P")
  16876. (let ((blist (org-buffer-list
  16877. (cond ((equal arg '(4)) 'files)
  16878. ((equal arg '(16)) 'agenda)))))
  16879. (pop-to-buffer-same-window
  16880. (completing-read "Org buffer: "
  16881. (mapcar #'list (mapcar #'buffer-name blist))
  16882. nil t))))
  16883. (defun org-buffer-list (&optional predicate exclude-tmp)
  16884. "Return a list of Org buffers.
  16885. PREDICATE can be `export', `files' or `agenda'.
  16886. export restrict the list to Export buffers.
  16887. files restrict the list to buffers visiting Org files.
  16888. agenda restrict the list to buffers visiting agenda files.
  16889. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16890. (let* ((bfn nil)
  16891. (agenda-files (and (eq predicate 'agenda)
  16892. (mapcar 'file-truename (org-agenda-files t))))
  16893. (filter
  16894. (cond
  16895. ((eq predicate 'files)
  16896. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16897. ((eq predicate 'export)
  16898. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16899. ((eq predicate 'agenda)
  16900. (lambda (b)
  16901. (with-current-buffer b
  16902. (and (derived-mode-p 'org-mode)
  16903. (setq bfn (buffer-file-name b))
  16904. (member (file-truename bfn) agenda-files)))))
  16905. (t (lambda (b) (with-current-buffer b
  16906. (or (derived-mode-p 'org-mode)
  16907. (string-match "\\*Org .*Export"
  16908. (buffer-name b)))))))))
  16909. (delq nil
  16910. (mapcar
  16911. (lambda(b)
  16912. (if (and (funcall filter b)
  16913. (or (not exclude-tmp)
  16914. (not (string-match "tmp" (buffer-name b)))))
  16915. b
  16916. nil))
  16917. (buffer-list)))))
  16918. (defun org-agenda-files (&optional unrestricted archives)
  16919. "Get the list of agenda files.
  16920. Optional UNRESTRICTED means return the full list even if a restriction
  16921. is currently in place.
  16922. When ARCHIVES is t, include all archive files that are really being
  16923. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16924. `org-agenda-archives-mode' is t."
  16925. (let ((files
  16926. (cond
  16927. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16928. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16929. ((listp org-agenda-files) org-agenda-files)
  16930. (t (error "Invalid value of `org-agenda-files'")))))
  16931. (setq files (apply 'append
  16932. (mapcar (lambda (f)
  16933. (if (file-directory-p f)
  16934. (directory-files
  16935. f t org-agenda-file-regexp)
  16936. (list f)))
  16937. files)))
  16938. (when org-agenda-skip-unavailable-files
  16939. (setq files (delq nil
  16940. (mapcar (function
  16941. (lambda (file)
  16942. (and (file-readable-p file) file)))
  16943. files))))
  16944. (when (or (eq archives t)
  16945. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16946. (setq files (org-add-archive-files files)))
  16947. files))
  16948. (defun org-agenda-file-p (&optional file)
  16949. "Return non-nil, if FILE is an agenda file.
  16950. If FILE is omitted, use the file associated with the current
  16951. buffer."
  16952. (let ((fname (or file (buffer-file-name))))
  16953. (and fname
  16954. (member (file-truename fname)
  16955. (mapcar #'file-truename (org-agenda-files t))))))
  16956. (defun org-edit-agenda-file-list ()
  16957. "Edit the list of agenda files.
  16958. Depending on setup, this either uses customize to edit the variable
  16959. `org-agenda-files', or it visits the file that is holding the list. In the
  16960. latter case, the buffer is set up in a way that saving it automatically kills
  16961. the buffer and restores the previous window configuration."
  16962. (interactive)
  16963. (if (stringp org-agenda-files)
  16964. (let ((cw (current-window-configuration)))
  16965. (find-file org-agenda-files)
  16966. (setq-local org-window-configuration cw)
  16967. (add-hook 'after-save-hook
  16968. (lambda ()
  16969. (set-window-configuration
  16970. (prog1 org-window-configuration
  16971. (kill-buffer (current-buffer))))
  16972. (org-install-agenda-files-menu)
  16973. (message "New agenda file list installed"))
  16974. nil 'local)
  16975. (message "%s" (substitute-command-keys
  16976. "Edit list and finish with \\[save-buffer]")))
  16977. (customize-variable 'org-agenda-files)))
  16978. (defun org-store-new-agenda-file-list (list)
  16979. "Set new value for the agenda file list and save it correctly."
  16980. (if (stringp org-agenda-files)
  16981. (let ((fe (org-read-agenda-file-list t)) b u)
  16982. (while (setq b (find-buffer-visiting org-agenda-files))
  16983. (kill-buffer b))
  16984. (with-temp-file org-agenda-files
  16985. (insert
  16986. (mapconcat
  16987. (lambda (f) ;; Keep un-expanded entries.
  16988. (if (setq u (assoc f fe))
  16989. (cdr u)
  16990. f))
  16991. list "\n")
  16992. "\n")))
  16993. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16994. (org-insert-mode-line-in-empty-file nil))
  16995. (setq org-agenda-files list)
  16996. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16997. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16998. "Read the list of agenda files from a file.
  16999. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17000. filenames, used by `org-store-new-agenda-file-list' to write back
  17001. un-expanded file names."
  17002. (when (file-directory-p org-agenda-files)
  17003. (error "`org-agenda-files' cannot be a single directory"))
  17004. (when (stringp org-agenda-files)
  17005. (with-temp-buffer
  17006. (insert-file-contents org-agenda-files)
  17007. (mapcar
  17008. (lambda (f)
  17009. (let ((e (expand-file-name (substitute-in-file-name f)
  17010. org-directory)))
  17011. (if pair-with-expansion
  17012. (cons e f)
  17013. e)))
  17014. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17015. ;;;###autoload
  17016. (defun org-cycle-agenda-files ()
  17017. "Cycle through the files in `org-agenda-files'.
  17018. If the current buffer visits an agenda file, find the next one in the list.
  17019. If the current buffer does not, find the first agenda file."
  17020. (interactive)
  17021. (let* ((fs (or (org-agenda-files t)
  17022. (user-error "No agenda files")))
  17023. (files (copy-sequence fs))
  17024. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17025. file)
  17026. (when tcf
  17027. (while (and (setq file (pop files))
  17028. (not (equal (file-truename file) tcf)))))
  17029. (find-file (car (or files fs)))
  17030. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17031. (defun org-agenda-file-to-front (&optional to-end)
  17032. "Move/add the current file to the top of the agenda file list.
  17033. If the file is not present in the list, it is added to the front. If it is
  17034. present, it is moved there. With optional argument TO-END, add/move to the
  17035. end of the list."
  17036. (interactive "P")
  17037. (let ((org-agenda-skip-unavailable-files nil)
  17038. (file-alist (mapcar (lambda (x)
  17039. (cons (file-truename x) x))
  17040. (org-agenda-files t)))
  17041. (ctf (file-truename
  17042. (or buffer-file-name
  17043. (user-error "Please save the current buffer to a file"))))
  17044. x had)
  17045. (setq x (assoc ctf file-alist) had x)
  17046. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17047. (if to-end
  17048. (setq file-alist (append (delq x file-alist) (list x)))
  17049. (setq file-alist (cons x (delq x file-alist))))
  17050. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17051. (org-install-agenda-files-menu)
  17052. (message "File %s to %s of agenda file list"
  17053. (if had "moved" "added") (if to-end "end" "front"))))
  17054. (defun org-remove-file (&optional file)
  17055. "Remove current file from the list of files in variable `org-agenda-files'.
  17056. These are the files which are being checked for agenda entries.
  17057. Optional argument FILE means use this file instead of the current."
  17058. (interactive)
  17059. (let* ((org-agenda-skip-unavailable-files nil)
  17060. (file (or file buffer-file-name
  17061. (user-error "Current buffer does not visit a file")))
  17062. (true-file (file-truename file))
  17063. (afile (abbreviate-file-name file))
  17064. (files (delq nil (mapcar
  17065. (lambda (x)
  17066. (unless (equal true-file
  17067. (file-truename x))
  17068. x))
  17069. (org-agenda-files t)))))
  17070. (if (not (= (length files) (length (org-agenda-files t))))
  17071. (progn
  17072. (org-store-new-agenda-file-list files)
  17073. (org-install-agenda-files-menu)
  17074. (message "Removed from Org Agenda list: %s" afile))
  17075. (message "File was not in list: %s (not removed)" afile))))
  17076. (defun org-file-menu-entry (file)
  17077. (vector file (list 'find-file file) t))
  17078. (defun org-check-agenda-file (file)
  17079. "Make sure FILE exists. If not, ask user what to do."
  17080. (unless (file-exists-p file)
  17081. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17082. (abbreviate-file-name file))
  17083. (let ((r (downcase (read-char-exclusive))))
  17084. (cond
  17085. ((equal r ?r)
  17086. (org-remove-file file)
  17087. (throw 'nextfile t))
  17088. (t (user-error "Abort"))))))
  17089. (defun org-get-agenda-file-buffer (file)
  17090. "Get an agenda buffer visiting FILE.
  17091. If the buffer needs to be created, add it to the list of buffers
  17092. which might be released later."
  17093. (let ((buf (org-find-base-buffer-visiting file)))
  17094. (if buf
  17095. buf ; just return it
  17096. ;; Make a new buffer and remember it
  17097. (setq buf (find-file-noselect file))
  17098. (when buf (push buf org-agenda-new-buffers))
  17099. buf)))
  17100. (defun org-release-buffers (blist)
  17101. "Release all buffers in list, asking the user for confirmation when needed.
  17102. When a buffer is unmodified, it is just killed. When modified, it is saved
  17103. \(if the user agrees) and then killed."
  17104. (let (file)
  17105. (dolist (buf blist)
  17106. (setq file (buffer-file-name buf))
  17107. (when (and (buffer-modified-p buf)
  17108. file
  17109. (y-or-n-p (format "Save file %s? " file)))
  17110. (with-current-buffer buf (save-buffer)))
  17111. (kill-buffer buf))))
  17112. (defun org-agenda-prepare-buffers (files)
  17113. "Create buffers for all agenda files, protect archived trees and comments."
  17114. (interactive)
  17115. (let ((pa '(:org-archived t))
  17116. (pc '(:org-comment t))
  17117. (pall '(:org-archived t :org-comment t))
  17118. (inhibit-read-only t)
  17119. (org-inhibit-startup org-agenda-inhibit-startup)
  17120. (rea (concat ":" org-archive-tag ":"))
  17121. re pos)
  17122. (setq org-tag-alist-for-agenda nil
  17123. org-tag-groups-alist-for-agenda nil)
  17124. (save-excursion
  17125. (save-restriction
  17126. (dolist (file files)
  17127. (catch 'nextfile
  17128. (if (bufferp file)
  17129. (set-buffer file)
  17130. (org-check-agenda-file file)
  17131. (set-buffer (org-get-agenda-file-buffer file)))
  17132. (widen)
  17133. (org-set-regexps-and-options 'tags-only)
  17134. (setq pos (point))
  17135. (or (memq 'category org-agenda-ignore-properties)
  17136. (org-refresh-category-properties))
  17137. (or (memq 'stats org-agenda-ignore-properties)
  17138. (org-refresh-stats-properties))
  17139. (or (memq 'effort org-agenda-ignore-properties)
  17140. (org-refresh-effort-properties))
  17141. (or (memq 'appt org-agenda-ignore-properties)
  17142. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17143. (setq org-todo-keywords-for-agenda
  17144. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17145. (setq org-done-keywords-for-agenda
  17146. (append org-done-keywords-for-agenda org-done-keywords))
  17147. (setq org-todo-keyword-alist-for-agenda
  17148. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17149. (setq org-tag-alist-for-agenda
  17150. (org-uniquify
  17151. (append org-tag-alist-for-agenda
  17152. org-current-tag-alist)))
  17153. ;; Merge current file's tag groups into global
  17154. ;; `org-tag-groups-alist-for-agenda'.
  17155. (when org-group-tags
  17156. (dolist (alist org-tag-groups-alist)
  17157. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17158. (if old
  17159. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17160. (push alist org-tag-groups-alist-for-agenda)))))
  17161. (org-with-silent-modifications
  17162. (save-excursion
  17163. (remove-text-properties (point-min) (point-max) pall)
  17164. (when org-agenda-skip-archived-trees
  17165. (goto-char (point-min))
  17166. (while (re-search-forward rea nil t)
  17167. (when (org-at-heading-p t)
  17168. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17169. (goto-char (point-min))
  17170. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17171. (while (re-search-forward re nil t)
  17172. (when (save-match-data (org-in-commented-heading-p t))
  17173. (add-text-properties
  17174. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17175. (goto-char pos)))))
  17176. (setq org-todo-keywords-for-agenda
  17177. (org-uniquify org-todo-keywords-for-agenda))
  17178. (setq org-todo-keyword-alist-for-agenda
  17179. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17180. ;;;; CDLaTeX minor mode
  17181. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17182. "Keymap for the minor `org-cdlatex-mode'.")
  17183. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17184. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17185. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17186. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17187. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17188. (defvar org-cdlatex-texmathp-advice-is-done nil
  17189. "Flag remembering if we have applied the advice to texmathp already.")
  17190. (define-minor-mode org-cdlatex-mode
  17191. "Toggle the minor `org-cdlatex-mode'.
  17192. This mode supports entering LaTeX environment and math in LaTeX fragments
  17193. in Org-mode.
  17194. \\{org-cdlatex-mode-map}"
  17195. nil " OCDL" nil
  17196. (when org-cdlatex-mode
  17197. (require 'cdlatex)
  17198. (run-hooks 'cdlatex-mode-hook)
  17199. (cdlatex-compute-tables))
  17200. (unless org-cdlatex-texmathp-advice-is-done
  17201. (setq org-cdlatex-texmathp-advice-is-done t)
  17202. (defadvice texmathp (around org-math-always-on activate)
  17203. "Always return t in org-mode buffers.
  17204. This is because we want to insert math symbols without dollars even outside
  17205. the LaTeX math segments. If Orgmode thinks that point is actually inside
  17206. an embedded LaTeX fragment, let texmathp do its job.
  17207. \\[org-cdlatex-mode-map]"
  17208. (interactive)
  17209. (let (p)
  17210. (cond
  17211. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17212. ((eq this-command 'cdlatex-math-symbol)
  17213. (setq ad-return-value t
  17214. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17215. (t
  17216. (let ((p (org-inside-LaTeX-fragment-p)))
  17217. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17218. (setq ad-return-value t
  17219. texmathp-why '("Org-mode embedded math" . 0))
  17220. (when p ad-do-it)))))))))
  17221. (defun turn-on-org-cdlatex ()
  17222. "Unconditionally turn on `org-cdlatex-mode'."
  17223. (org-cdlatex-mode 1))
  17224. (defun org-try-cdlatex-tab ()
  17225. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17226. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17227. - inside a LaTeX fragment, or
  17228. - after the first word in a line, where an abbreviation expansion could
  17229. insert a LaTeX environment."
  17230. (when org-cdlatex-mode
  17231. (cond
  17232. ;; Before any word on the line: No expansion possible.
  17233. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17234. ;; Just after first word on the line: Expand it. Make sure it
  17235. ;; cannot happen on headlines, though.
  17236. ((save-excursion
  17237. (skip-chars-backward "a-zA-Z0-9*")
  17238. (skip-chars-backward " \t")
  17239. (and (bolp) (not (org-at-heading-p))))
  17240. (cdlatex-tab) t)
  17241. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17242. (defun org-cdlatex-underscore-caret (&optional _arg)
  17243. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17244. Revert to the normal definition outside of these fragments."
  17245. (interactive "P")
  17246. (if (org-inside-LaTeX-fragment-p)
  17247. (call-interactively 'cdlatex-sub-superscript)
  17248. (let (org-cdlatex-mode)
  17249. (call-interactively (key-binding (vector last-input-event))))))
  17250. (defun org-cdlatex-math-modify (&optional _arg)
  17251. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17252. Revert to the normal definition outside of these fragments."
  17253. (interactive "P")
  17254. (if (org-inside-LaTeX-fragment-p)
  17255. (call-interactively 'cdlatex-math-modify)
  17256. (let (org-cdlatex-mode)
  17257. (call-interactively (key-binding (vector last-input-event))))))
  17258. (defun org-cdlatex-environment-indent (&optional environment item)
  17259. "Execute `cdlatex-environment' and indent the inserted environment.
  17260. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17261. The inserted environment is indented to current indentation
  17262. unless point is at the beginning of the line, in which the
  17263. environment remains unintended."
  17264. (interactive)
  17265. ;; cdlatex-environment always return nil. Therefore, capture output
  17266. ;; first and determine if an environment was selected.
  17267. (let* ((beg (point-marker))
  17268. (end (copy-marker (point) t))
  17269. (inserted (progn
  17270. (ignore-errors (cdlatex-environment environment item))
  17271. (< beg end)))
  17272. ;; Figure out how many lines to move forward after the
  17273. ;; environment has been inserted.
  17274. (lines (when inserted
  17275. (save-excursion
  17276. (- (cl-loop while (< beg (point))
  17277. with x = 0
  17278. do (forward-line -1)
  17279. (cl-incf x)
  17280. finally return x)
  17281. (if (progn (goto-char beg)
  17282. (and (progn (skip-chars-forward " \t") (eolp))
  17283. (progn (skip-chars-backward " \t") (bolp))))
  17284. 1 0)))))
  17285. (env (org-trim (delete-and-extract-region beg end))))
  17286. (when inserted
  17287. ;; Get indentation of next line unless at column 0.
  17288. (let ((ind (if (bolp) 0
  17289. (save-excursion
  17290. (org-return-indent)
  17291. (prog1 (org-get-indentation)
  17292. (when (progn (skip-chars-forward " \t") (eolp))
  17293. (delete-region beg (point)))))))
  17294. (bol (progn (skip-chars-backward " \t") (bolp))))
  17295. ;; Insert a newline before environment unless at column zero
  17296. ;; to "escape" the current line. Insert a newline if
  17297. ;; something is one the same line as \end{ENVIRONMENT}.
  17298. (insert
  17299. (concat (unless bol "\n") env
  17300. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17301. (unless (zerop ind)
  17302. (save-excursion
  17303. (goto-char beg)
  17304. (while (< (point) end)
  17305. (unless (eolp) (indent-line-to ind))
  17306. (forward-line))))
  17307. (goto-char beg)
  17308. (forward-line lines)
  17309. (indent-line-to ind)))
  17310. (set-marker beg nil)
  17311. (set-marker end nil)))
  17312. ;;;; LaTeX fragments
  17313. (defun org-inside-LaTeX-fragment-p ()
  17314. "Test if point is inside a LaTeX fragment.
  17315. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17316. sequence appearing also before point.
  17317. Even though the matchers for math are configurable, this function assumes
  17318. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17319. delimiters are skipped when they have been removed by customization.
  17320. The return value is nil, or a cons cell with the delimiter and the
  17321. position of this delimiter.
  17322. This function does a reasonably good job, but can locally be fooled by
  17323. for example currency specifications. For example it will assume being in
  17324. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17325. fragments that are properly closed, but during editing, we have to live
  17326. with the uncertainty caused by missing closing delimiters. This function
  17327. looks only before point, not after."
  17328. (catch 'exit
  17329. (let ((pos (point))
  17330. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17331. (lim (progn
  17332. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17333. (point)))
  17334. dd-on str (start 0) m re)
  17335. (goto-char pos)
  17336. (when dodollar
  17337. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17338. re (nth 1 (assoc "$" org-latex-regexps)))
  17339. (while (string-match re str start)
  17340. (cond
  17341. ((= (match-end 0) (length str))
  17342. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17343. ((= (match-end 0) (- (length str) 5))
  17344. (throw 'exit nil))
  17345. (t (setq start (match-end 0))))))
  17346. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17347. (goto-char pos)
  17348. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17349. (and (match-beginning 2) (throw 'exit nil))
  17350. ;; count $$
  17351. (while (re-search-backward "\\$\\$" lim t)
  17352. (setq dd-on (not dd-on)))
  17353. (goto-char pos)
  17354. (when dd-on (cons "$$" m))))))
  17355. (defun org-inside-latex-macro-p ()
  17356. "Is point inside a LaTeX macro or its arguments?"
  17357. (save-match-data
  17358. (org-in-regexp
  17359. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17360. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17361. "Build an overlay between BEG and END using IMAGE file.
  17362. Argument IMAGETYPE is the extension of the displayed image,
  17363. as a string. It defaults to \"png\"."
  17364. (let ((ov (make-overlay beg end))
  17365. (imagetype (or (intern imagetype) 'png)))
  17366. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17367. (overlay-put ov 'evaporate t)
  17368. (overlay-put ov
  17369. 'modification-hooks
  17370. (list (lambda (o _flag _beg _end &optional _l)
  17371. (delete-overlay o))))
  17372. (overlay-put ov
  17373. 'display
  17374. (list 'image :type imagetype :file image :ascent 'center))))
  17375. (defun org--list-latex-overlays (&optional beg end)
  17376. "List all Org LaTeX overlays in current buffer.
  17377. Limit to overlays between BEG and END when those are provided."
  17378. (cl-remove-if-not
  17379. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17380. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17381. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17382. "Remove all overlays with LaTeX fragment images in current buffer.
  17383. When optional arguments BEG and END are non-nil, remove all
  17384. overlays between them instead. Return a non-nil value when some
  17385. overlays were removed, nil otherwise."
  17386. (let ((overlays (org--list-latex-overlays beg end)))
  17387. (mapc #'delete-overlay overlays)
  17388. overlays))
  17389. (defun org-toggle-latex-fragment (&optional arg)
  17390. "Preview the LaTeX fragment at point, or all locally or globally.
  17391. If the cursor is on a LaTeX fragment, create the image and overlay
  17392. it over the source code, if there is none. Remove it otherwise.
  17393. If there is no fragment at point, display all fragments in the
  17394. current section.
  17395. With prefix ARG, preview or clear image for all fragments in the
  17396. current subtree or in the whole buffer when used before the first
  17397. headline. With a double prefix ARG \\[universal-argument] \
  17398. \\[universal-argument] preview or clear images
  17399. for all fragments in the buffer."
  17400. (interactive "P")
  17401. (when (display-graphic-p)
  17402. (catch 'exit
  17403. (save-excursion
  17404. (let (beg end msg)
  17405. (cond
  17406. ((or (equal arg '(16))
  17407. (and (equal arg '(4))
  17408. (org-with-limited-levels (org-before-first-heading-p))))
  17409. (if (org-remove-latex-fragment-image-overlays)
  17410. (progn (message "LaTeX fragments images removed from buffer")
  17411. (throw 'exit nil))
  17412. (setq msg "Creating images for buffer...")))
  17413. ((equal arg '(4))
  17414. (org-with-limited-levels (org-back-to-heading t))
  17415. (setq beg (point))
  17416. (setq end (progn (org-end-of-subtree t) (point)))
  17417. (if (org-remove-latex-fragment-image-overlays beg end)
  17418. (progn
  17419. (message "LaTeX fragment images removed from subtree")
  17420. (throw 'exit nil))
  17421. (setq msg "Creating images for subtree...")))
  17422. ((let ((datum (org-element-context)))
  17423. (when (memq (org-element-type datum)
  17424. '(latex-environment latex-fragment))
  17425. (setq beg (org-element-property :begin datum))
  17426. (setq end (org-element-property :end datum))
  17427. (if (org-remove-latex-fragment-image-overlays beg end)
  17428. (progn (message "LaTeX fragment image removed")
  17429. (throw 'exit nil))
  17430. (setq msg "Creating image...")))))
  17431. (t
  17432. (org-with-limited-levels
  17433. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17434. (outline-previous-heading)
  17435. (point)))
  17436. (setq end (progn (outline-next-heading) (point)))
  17437. (if (org-remove-latex-fragment-image-overlays beg end)
  17438. (progn
  17439. (message "LaTeX fragment images removed from section")
  17440. (throw 'exit nil))
  17441. (setq msg "Creating images for section...")))))
  17442. (let ((file (buffer-file-name (buffer-base-buffer))))
  17443. (org-format-latex
  17444. (concat org-preview-latex-image-directory "org-ltximg")
  17445. beg end
  17446. ;; Emacs cannot overlay images from remote hosts. Create
  17447. ;; it in `temporary-file-directory' instead.
  17448. (if (or (not file) (file-remote-p file))
  17449. temporary-file-directory
  17450. default-directory)
  17451. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17452. (message (concat msg "done")))))))
  17453. (defun org-format-latex
  17454. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17455. "Replace LaTeX fragments with links to an image.
  17456. The function takes care of creating the replacement image.
  17457. Only consider fragments between BEG and END when those are
  17458. provided.
  17459. When optional argument OVERLAYS is non-nil, display the image on
  17460. top of the fragment instead of replacing it.
  17461. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17462. Some of the options can be changed using the variable
  17463. `org-format-latex-options', which see."
  17464. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17465. (unless (eq processing-type 'verbatim)
  17466. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17467. (cnt 0)
  17468. checkdir-flag)
  17469. (goto-char (or beg (point-min)))
  17470. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17471. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17472. (overlay-recenter (or end (point-max))))
  17473. (while (re-search-forward math-regexp end t)
  17474. (unless (and overlays
  17475. (eq (get-char-property (point) 'org-overlay-type)
  17476. 'org-latex-overlay))
  17477. (let* ((context (org-element-context))
  17478. (type (org-element-type context)))
  17479. (when (memq type '(latex-environment latex-fragment))
  17480. (let ((block-type (eq type 'latex-environment))
  17481. (value (org-element-property :value context))
  17482. (beg (org-element-property :begin context))
  17483. (end (save-excursion
  17484. (goto-char (org-element-property :end context))
  17485. (skip-chars-backward " \r\t\n")
  17486. (point))))
  17487. (cond
  17488. ((eq processing-type 'mathjax)
  17489. ;; Prepare for MathJax processing.
  17490. (if (not (string-match "\\`\\$\\$?" value))
  17491. (goto-char end)
  17492. (delete-region beg end)
  17493. (if (string= (match-string 0 value) "$$")
  17494. (insert "\\[" (substring value 2 -2) "\\]")
  17495. (insert "\\(" (substring value 1 -1) "\\)"))))
  17496. ((assq processing-type org-preview-latex-process-alist)
  17497. ;; Process to an image.
  17498. (cl-incf cnt)
  17499. (goto-char beg)
  17500. (let* ((processing-info
  17501. (cdr (assq processing-type org-preview-latex-process-alist)))
  17502. (face (face-at-point))
  17503. ;; Get the colors from the face at point.
  17504. (fg
  17505. (let ((color (plist-get org-format-latex-options
  17506. :foreground)))
  17507. (if (and forbuffer (eq color 'auto))
  17508. (face-attribute face :foreground nil 'default)
  17509. color)))
  17510. (bg
  17511. (let ((color (plist-get org-format-latex-options
  17512. :background)))
  17513. (if (and forbuffer (eq color 'auto))
  17514. (face-attribute face :background nil 'default)
  17515. color)))
  17516. (hash (sha1 (prin1-to-string
  17517. (list org-format-latex-header
  17518. org-latex-default-packages-alist
  17519. org-latex-packages-alist
  17520. org-format-latex-options
  17521. forbuffer value fg bg))))
  17522. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17523. (absprefix (expand-file-name prefix dir))
  17524. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17525. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17526. (sep (and block-type "\n\n"))
  17527. (link (concat sep "[[file:" linkfile "]]" sep))
  17528. (options
  17529. (org-combine-plists
  17530. org-format-latex-options
  17531. `(:foreground ,fg :background ,bg))))
  17532. (when msg (message msg cnt))
  17533. (unless checkdir-flag ; Ensure the directory exists.
  17534. (setq checkdir-flag t)
  17535. (let ((todir (file-name-directory absprefix)))
  17536. (unless (file-directory-p todir)
  17537. (make-directory todir t))))
  17538. (unless (file-exists-p movefile)
  17539. (org-create-formula-image
  17540. value movefile options forbuffer processing-type))
  17541. (if overlays
  17542. (progn
  17543. (dolist (o (overlays-in beg end))
  17544. (when (eq (overlay-get o 'org-overlay-type)
  17545. 'org-latex-overlay)
  17546. (delete-overlay o)))
  17547. (org--format-latex-make-overlay beg end movefile imagetype)
  17548. (goto-char end))
  17549. (delete-region beg end)
  17550. (insert
  17551. (org-add-props link
  17552. (list 'org-latex-src
  17553. (replace-regexp-in-string "\"" "" value)
  17554. 'org-latex-src-embed-type
  17555. (if block-type 'paragraph 'character)))))))
  17556. ((eq processing-type 'mathml)
  17557. ;; Process to MathML.
  17558. (unless (org-format-latex-mathml-available-p)
  17559. (user-error "LaTeX to MathML converter not configured"))
  17560. (cl-incf cnt)
  17561. (when msg (message msg cnt))
  17562. (goto-char beg)
  17563. (delete-region beg end)
  17564. (insert (org-format-latex-as-mathml
  17565. value block-type prefix dir)))
  17566. (t
  17567. (error "Unknown conversion process %s for LaTeX fragments"
  17568. processing-type)))))))))))
  17569. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17570. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17571. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17572. sucessful, return the portion between \"<math...> </math>\"
  17573. elements otherwise return nil. When MATHML-FILE is specified,
  17574. write the results in to that file. When invoked as an
  17575. interactive command, prompt for LATEX-FRAG, with initial value
  17576. set to the current active region and echo the results for user
  17577. inspection."
  17578. (interactive (list (let ((frag (when (org-region-active-p)
  17579. (buffer-substring-no-properties
  17580. (region-beginning) (region-end)))))
  17581. (read-string "LaTeX Fragment: " frag nil frag))))
  17582. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17583. (let* ((tmp-in-file
  17584. (let ((file (file-relative-name
  17585. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17586. (write-region latex-frag nil file)
  17587. file))
  17588. (tmp-out-file (file-relative-name
  17589. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17590. (cmd (format-spec
  17591. org-latex-to-mathml-convert-command
  17592. `((?j . ,(and org-latex-to-mathml-jar-file
  17593. (shell-quote-argument
  17594. (expand-file-name
  17595. org-latex-to-mathml-jar-file))))
  17596. (?I . ,(shell-quote-argument tmp-in-file))
  17597. (?i . ,latex-frag)
  17598. (?o . ,(shell-quote-argument tmp-out-file)))))
  17599. mathml shell-command-output)
  17600. (when (called-interactively-p 'any)
  17601. (unless (org-format-latex-mathml-available-p)
  17602. (user-error "LaTeX to MathML converter not configured")))
  17603. (message "Running %s" cmd)
  17604. (setq shell-command-output (shell-command-to-string cmd))
  17605. (setq mathml
  17606. (when (file-readable-p tmp-out-file)
  17607. (with-current-buffer (find-file-noselect tmp-out-file t)
  17608. (goto-char (point-min))
  17609. (when (re-search-forward
  17610. (concat
  17611. (regexp-quote
  17612. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17613. "[^>]*?>"
  17614. "\\(.\\|\n\\)*"
  17615. "</math>")
  17616. nil t)
  17617. (prog1 (match-string 0) (kill-buffer))))))
  17618. (cond
  17619. (mathml
  17620. (setq mathml
  17621. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17622. (when mathml-file
  17623. (write-region mathml nil mathml-file))
  17624. (when (called-interactively-p 'any)
  17625. (message mathml)))
  17626. ((message "LaTeX to MathML conversion failed")
  17627. (message shell-command-output)))
  17628. (delete-file tmp-in-file)
  17629. (when (file-exists-p tmp-out-file)
  17630. (delete-file tmp-out-file))
  17631. mathml))
  17632. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17633. prefix &optional dir)
  17634. "Use `org-create-math-formula' but check local cache first."
  17635. (let* ((absprefix (expand-file-name prefix dir))
  17636. (print-length nil) (print-level nil)
  17637. (formula-id (concat
  17638. "formula-"
  17639. (sha1
  17640. (prin1-to-string
  17641. (list latex-frag
  17642. org-latex-to-mathml-convert-command)))))
  17643. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17644. (formula-cache-dir (file-name-directory formula-cache)))
  17645. (unless (file-directory-p formula-cache-dir)
  17646. (make-directory formula-cache-dir t))
  17647. (unless (file-exists-p formula-cache)
  17648. (org-create-math-formula latex-frag formula-cache))
  17649. (if (file-exists-p formula-cache)
  17650. ;; Successful conversion. Return the link to MathML file.
  17651. (org-add-props
  17652. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17653. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17654. 'org-latex-src-embed-type (if latex-frag-type
  17655. 'paragraph 'character)))
  17656. ;; Failed conversion. Return the LaTeX fragment verbatim
  17657. latex-frag)))
  17658. (declare-function org-export-get-backend "ox" (name))
  17659. (declare-function org-export--get-global-options "ox" (&optional backend))
  17660. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17661. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17662. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17663. (defun org-create-formula--latex-header ()
  17664. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17665. (let ((info (org-combine-plists (org-export--get-global-options
  17666. (org-export-get-backend 'latex))
  17667. (org-export--get-inbuffer-options
  17668. (org-export-get-backend 'latex)))))
  17669. (org-latex-guess-babel-language
  17670. (org-latex-guess-inputenc
  17671. (org-splice-latex-header
  17672. org-format-latex-header
  17673. org-latex-default-packages-alist
  17674. org-latex-packages-alist t
  17675. (plist-get info :latex-header)))
  17676. info)))
  17677. (defun org--get-display-dpi ()
  17678. "Get the DPI of the display.
  17679. Assumes that the display has the same pixel width in the
  17680. horizontal and vertical directions."
  17681. (if (display-graphic-p)
  17682. (round (/ (display-pixel-height)
  17683. (/ (display-mm-height) 25.4)))
  17684. (error "Attempt to calculate the dpi of a non-graphic display")))
  17685. (defun org-create-formula-image
  17686. (string tofile options buffer &optional processing-type)
  17687. "Create an image from LaTeX source using external processes.
  17688. The LaTeX STRING is saved to a temporary LaTeX file, then
  17689. converted to an image file by process PROCESSING-TYPE defined in
  17690. `org-preview-latex-process-alist'. A nil value defaults to
  17691. `org-preview-latex-default-process'.
  17692. The generated image file is eventually moved to TOFILE.
  17693. The OPTIONS argument controls the size, foreground color and
  17694. background color of the generated image.
  17695. When BUFFER non-nil, this function is used for LaTeX previewing.
  17696. Otherwise, it is used to deal with LaTeX snippets showed in
  17697. a HTML file."
  17698. (let* ((processing-type (or processing-type
  17699. org-preview-latex-default-process))
  17700. (processing-info
  17701. (cdr (assq processing-type org-preview-latex-process-alist)))
  17702. (programs (plist-get processing-info :programs))
  17703. (error-message (or (plist-get processing-info :message) ""))
  17704. (use-xcolor (plist-get processing-info :use-xcolor))
  17705. (image-input-type (plist-get processing-info :image-input-type))
  17706. (image-output-type (plist-get processing-info :image-output-type))
  17707. (post-clean (or (plist-get processing-info :post-clean)
  17708. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17709. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17710. (latex-header (or (plist-get processing-info :latex-header)
  17711. (org-create-formula--latex-header)))
  17712. (latex-compiler (plist-get processing-info :latex-compiler))
  17713. (image-converter (plist-get processing-info :image-converter))
  17714. (tmpdir temporary-file-directory)
  17715. (texfilebase (make-temp-name
  17716. (expand-file-name "orgtex" tmpdir)))
  17717. (texfile (concat texfilebase ".tex"))
  17718. (font-height (face-attribute 'default :height nil))
  17719. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17720. '(1.0 . 1.0)))
  17721. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17722. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17723. (dpi (* scale (floor (if buffer font-height 140.0))))
  17724. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17725. "Black"))
  17726. (bg (or (plist-get options (if buffer :background :html-background))
  17727. "Transparent"))
  17728. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17729. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17730. (dolist (program programs)
  17731. (org-check-external-command program error-message))
  17732. (if use-xcolor
  17733. (progn (if (eq fg 'default)
  17734. (setq fg (org-latex-color :foreground))
  17735. (setq fg (org-latex-color-format fg)))
  17736. (if (eq bg 'default)
  17737. (setq bg (org-latex-color :background))
  17738. (setq bg (org-latex-color-format
  17739. (if (string= bg "Transparent") "white" bg))))
  17740. (with-temp-file texfile
  17741. (insert latex-header)
  17742. (insert "\n\\begin{document}\n"
  17743. "\\definecolor{fg}{rgb}{" fg "}\n"
  17744. "\\definecolor{bg}{rgb}{" bg "}\n"
  17745. "\n\\pagecolor{bg}\n"
  17746. "\n{\\color{fg}\n"
  17747. string
  17748. "\n}\n"
  17749. "\n\\end{document}\n")))
  17750. (if (eq fg 'default)
  17751. (setq fg (org-dvipng-color :foreground))
  17752. (unless (string= fg "Transparent")
  17753. (setq fg (org-dvipng-color-format fg))))
  17754. (if (eq bg 'default)
  17755. (setq bg (org-dvipng-color :background))
  17756. (unless (string= bg "Transparent")
  17757. (setq bg (org-dvipng-color-format bg))))
  17758. (with-temp-file texfile
  17759. (insert latex-header)
  17760. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17761. (let* ((err-msg (format "Please adjust '%s' part of \
  17762. `org-preview-latex-process-alist'."
  17763. processing-type))
  17764. (image-input-file
  17765. (org-compile-file
  17766. texfile latex-compiler image-input-type err-msg log-buf))
  17767. (image-output-file
  17768. (org-compile-file
  17769. image-input-file image-converter image-output-type err-msg log-buf
  17770. `((?F . ,(shell-quote-argument fg))
  17771. (?B . ,(shell-quote-argument bg))
  17772. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17773. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17774. (copy-file image-output-file tofile 'replace)
  17775. (dolist (e post-clean)
  17776. (when (file-exists-p (concat texfilebase e))
  17777. (delete-file (concat texfilebase e))))
  17778. image-output-file)))
  17779. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17780. "Fill a LaTeX header template TPL.
  17781. In the template, the following place holders will be recognized:
  17782. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17783. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17784. [PACKAGES] \\usepackage statements for PKG
  17785. [NO-PACKAGES] do not include PKG
  17786. [EXTRA] the string EXTRA
  17787. [NO-EXTRA] do not include EXTRA
  17788. For backward compatibility, if both the positive and the negative place
  17789. holder is missing, the positive one (without the \"NO-\") will be
  17790. assumed to be present at the end of the template.
  17791. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17792. EXTRA is a string.
  17793. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17794. (let (rpl (end ""))
  17795. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17796. (setq rpl (if (or (match-end 1) (not def-pkg))
  17797. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17798. tpl (replace-match rpl t t tpl))
  17799. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17800. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17801. (setq rpl (if (or (match-end 1) (not pkg))
  17802. "" (org-latex-packages-to-string pkg snippets-p t))
  17803. tpl (replace-match rpl t t tpl))
  17804. (when pkg (setq end
  17805. (concat end "\n"
  17806. (org-latex-packages-to-string pkg snippets-p)))))
  17807. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17808. (setq rpl (if (or (match-end 1) (not extra))
  17809. "" (concat extra "\n"))
  17810. tpl (replace-match rpl t t tpl))
  17811. (when (and extra (string-match "\\S-" extra))
  17812. (setq end (concat end "\n" extra))))
  17813. (if (string-match "\\S-" end)
  17814. (concat tpl "\n" end)
  17815. tpl)))
  17816. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17817. "Turn an alist of packages into a string with the \\usepackage macros."
  17818. (setq pkg (mapconcat (lambda(p)
  17819. (cond
  17820. ((stringp p) p)
  17821. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17822. (format "%% Package %s omitted" (cadr p)))
  17823. ((equal "" (car p))
  17824. (format "\\usepackage{%s}" (cadr p)))
  17825. (t
  17826. (format "\\usepackage[%s]{%s}"
  17827. (car p) (cadr p)))))
  17828. pkg
  17829. "\n"))
  17830. (if newline (concat pkg "\n") pkg))
  17831. (defun org-dvipng-color (attr)
  17832. "Return a RGB color specification for dvipng."
  17833. (apply #'format "rgb %s %s %s"
  17834. (mapcar #'org-normalize-color
  17835. (color-values (face-attribute 'default attr nil)))))
  17836. (defun org-dvipng-color-format (color-name)
  17837. "Convert COLOR-NAME to a RGB color value for dvipng."
  17838. (apply 'format "rgb %s %s %s"
  17839. (mapcar 'org-normalize-color
  17840. (color-values color-name))))
  17841. (defun org-latex-color (attr)
  17842. "Return a RGB color for the LaTeX color package."
  17843. (apply #'format "%s,%s,%s"
  17844. (mapcar #'org-normalize-color
  17845. (color-values (face-attribute 'default attr nil)))))
  17846. (defun org-latex-color-format (color-name)
  17847. "Convert COLOR-NAME to a RGB color value."
  17848. (apply 'format "%s,%s,%s"
  17849. (mapcar 'org-normalize-color
  17850. (color-values color-name))))
  17851. (defun org-normalize-color (value)
  17852. "Return string to be used as color value for an RGB component."
  17853. (format "%g" (/ value 65535.0)))
  17854. ;; Image display
  17855. (defvar-local org-inline-image-overlays nil)
  17856. (defun org-toggle-inline-images (&optional include-linked)
  17857. "Toggle the display of inline images.
  17858. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17859. (interactive "P")
  17860. (if org-inline-image-overlays
  17861. (progn
  17862. (org-remove-inline-images)
  17863. (when (called-interactively-p 'interactive)
  17864. (message "Inline image display turned off")))
  17865. (org-display-inline-images include-linked)
  17866. (when (called-interactively-p 'interactive)
  17867. (message (if org-inline-image-overlays
  17868. (format "%d images displayed inline"
  17869. (length org-inline-image-overlays))
  17870. "No images to display inline")))))
  17871. (defun org-redisplay-inline-images ()
  17872. "Refresh the display of inline images."
  17873. (interactive)
  17874. (if (not org-inline-image-overlays)
  17875. (org-toggle-inline-images)
  17876. (org-toggle-inline-images)
  17877. (org-toggle-inline-images)))
  17878. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17879. "Display inline images.
  17880. An inline image is a link which follows either of these
  17881. conventions:
  17882. 1. Its path is a file with an extension matching return value
  17883. from `image-file-name-regexp' and it has no contents.
  17884. 2. Its description consists in a single link of the previous
  17885. type.
  17886. When optional argument INCLUDE-LINKED is non-nil, also links with
  17887. a text description part will be inlined. This can be nice for
  17888. a quick look at those images, but it does not reflect what
  17889. exported files will look like.
  17890. When optional argument REFRESH is non-nil, refresh existing
  17891. images between BEG and END. This will create new image displays
  17892. only if necessary. BEG and END default to the buffer
  17893. boundaries."
  17894. (interactive "P")
  17895. (when (display-graphic-p)
  17896. (unless refresh
  17897. (org-remove-inline-images)
  17898. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17899. (org-with-wide-buffer
  17900. (goto-char (or beg (point-min)))
  17901. (let ((case-fold-search t)
  17902. (file-extension-re (image-file-name-regexp)))
  17903. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17904. (let ((link (save-match-data (org-element-context))))
  17905. ;; Check if we're at an inline image.
  17906. (when (and (equal (org-element-property :type link) "file")
  17907. (or include-linked
  17908. (not (org-element-property :contents-begin link)))
  17909. (let ((parent (org-element-property :parent link)))
  17910. (or (not (eq (org-element-type parent) 'link))
  17911. (not (cdr (org-element-contents parent)))))
  17912. (org-string-match-p file-extension-re
  17913. (org-element-property :path link)))
  17914. (let ((file (expand-file-name
  17915. (org-link-unescape
  17916. (org-element-property :path link)))))
  17917. (when (file-exists-p file)
  17918. (let ((width
  17919. ;; Apply `org-image-actual-width' specifications.
  17920. (cond
  17921. ((not (image-type-available-p 'imagemagick)) nil)
  17922. ((eq org-image-actual-width t) nil)
  17923. ((listp org-image-actual-width)
  17924. (or
  17925. ;; First try to find a width among
  17926. ;; attributes associated to the paragraph
  17927. ;; containing link.
  17928. (let ((paragraph
  17929. (let ((e link))
  17930. (while (and (setq e (org-element-property
  17931. :parent e))
  17932. (not (eq (org-element-type e)
  17933. 'paragraph))))
  17934. e)))
  17935. (when paragraph
  17936. (save-excursion
  17937. (goto-char (org-element-property :begin paragraph))
  17938. (when
  17939. (re-search-forward
  17940. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17941. (org-element-property
  17942. :post-affiliated paragraph)
  17943. t)
  17944. (string-to-number (match-string 1))))))
  17945. ;; Otherwise, fall-back to provided number.
  17946. (car org-image-actual-width)))
  17947. ((numberp org-image-actual-width)
  17948. org-image-actual-width)))
  17949. (old (get-char-property-and-overlay
  17950. (org-element-property :begin link)
  17951. 'org-image-overlay)))
  17952. (if (and (car-safe old) refresh)
  17953. (image-refresh (overlay-get (cdr old) 'display))
  17954. (let ((image (create-image file
  17955. (and width 'imagemagick)
  17956. nil
  17957. :width width)))
  17958. (when image
  17959. (let* ((link
  17960. ;; If inline image is the description
  17961. ;; of another link, be sure to
  17962. ;; consider the latter as the one to
  17963. ;; apply the overlay on.
  17964. (let ((parent
  17965. (org-element-property :parent link)))
  17966. (if (eq (org-element-type parent) 'link)
  17967. parent
  17968. link)))
  17969. (ov (make-overlay
  17970. (org-element-property :begin link)
  17971. (progn
  17972. (goto-char
  17973. (org-element-property :end link))
  17974. (skip-chars-backward " \t")
  17975. (point)))))
  17976. (overlay-put ov 'display image)
  17977. (overlay-put ov 'face 'default)
  17978. (overlay-put ov 'org-image-overlay t)
  17979. (overlay-put
  17980. ov 'modification-hooks
  17981. (list 'org-display-inline-remove-overlay))
  17982. (push ov org-inline-image-overlays)))))))))))))))
  17983. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17984. "Remove inline-display overlay if a corresponding region is modified."
  17985. (let ((inhibit-modification-hooks t))
  17986. (when (and ov after)
  17987. (delete ov org-inline-image-overlays)
  17988. (delete-overlay ov))))
  17989. (defun org-remove-inline-images ()
  17990. "Remove inline display of images."
  17991. (interactive)
  17992. (mapc #'delete-overlay org-inline-image-overlays)
  17993. (setq org-inline-image-overlays nil))
  17994. ;;;; Key bindings
  17995. ;; Outline functions from `outline-mode-prefix-map'
  17996. ;; that can be remapped in Org:
  17997. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17998. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17999. (define-key org-mode-map [remap outline-forward-same-level]
  18000. 'org-forward-heading-same-level)
  18001. (define-key org-mode-map [remap outline-backward-same-level]
  18002. 'org-backward-heading-same-level)
  18003. (define-key org-mode-map [remap outline-show-branches]
  18004. 'org-kill-note-or-show-branches)
  18005. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18006. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18007. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18008. (define-key org-mode-map [remap outline-next-visible-heading]
  18009. 'org-next-visible-heading)
  18010. (define-key org-mode-map [remap outline-previous-visible-heading]
  18011. 'org-previous-visible-heading)
  18012. (define-key org-mode-map [remap show-children] 'org-show-children)
  18013. ;; Outline functions from `outline-mode-prefix-map' that can not
  18014. ;; be remapped in Org:
  18015. ;; - the column "key binding" shows whether the Outline function is still
  18016. ;; available in Org mode on the same key that it has been bound to in
  18017. ;; Outline mode:
  18018. ;; - "overridden": key used for a different functionality in Org mode
  18019. ;; - else: key still bound to the same Outline function in Org mode
  18020. ;; | Outline function | key binding | Org replacement |
  18021. ;; |------------------------------------+-------------+--------------------------|
  18022. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18023. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18024. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18025. ;; | `show-entry' | overridden | no replacement |
  18026. ;; | `show-branches' | `C-c C-k' | still same function |
  18027. ;; | `show-subtree' | overridden | visibility cycling |
  18028. ;; | `show-all' | overridden | no replacement |
  18029. ;; | `hide-subtree' | overridden | visibility cycling |
  18030. ;; | `hide-body' | overridden | no replacement |
  18031. ;; | `hide-entry' | overridden | visibility cycling |
  18032. ;; | `hide-leaves' | overridden | no replacement |
  18033. ;; | `hide-sublevels' | overridden | no replacement |
  18034. ;; | `hide-other' | overridden | no replacement |
  18035. ;; Make `C-c C-x' a prefix key
  18036. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18037. ;; TAB key with modifiers
  18038. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18039. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18040. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18041. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18042. ;; The following line is necessary under Suse GNU/Linux
  18043. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18044. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18045. (define-key org-mode-map [backtab] 'org-shifttab)
  18046. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18047. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18048. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18049. ;; Cursor keys with modifiers
  18050. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18051. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18052. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18053. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18054. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18055. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18056. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18057. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18058. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18059. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18060. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18061. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18062. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18063. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18064. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18065. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18066. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18067. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18068. ;; Babel keys
  18069. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18070. (dolist (pair org-babel-key-bindings)
  18071. (define-key org-babel-map (car pair) (cdr pair)))
  18072. ;;; Extra keys for tty access.
  18073. ;; We only set them when really needed because otherwise the
  18074. ;; menus don't show the simple keys
  18075. (when (or org-use-extra-keys (not window-system))
  18076. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18077. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18078. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18079. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18080. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18081. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18082. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18083. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18084. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18085. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18086. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18087. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18088. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18089. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18090. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18091. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18092. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18093. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18094. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18095. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18096. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18097. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18098. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18099. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18100. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18101. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18102. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18103. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18104. ;; All the other keys
  18105. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18106. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18107. (if (boundp 'narrow-map)
  18108. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18109. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18110. (if (boundp 'narrow-map)
  18111. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18112. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18113. (if (boundp 'narrow-map)
  18114. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18115. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18116. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18117. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18118. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18119. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18120. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18121. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18122. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18123. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18124. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18125. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18126. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18127. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18128. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18129. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18130. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18131. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18132. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18133. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18134. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18135. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18136. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18137. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18138. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18139. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18140. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18141. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18142. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18143. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18144. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18145. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18146. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18147. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18148. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18149. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18150. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18151. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18152. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18153. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18154. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18155. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18156. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18157. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18158. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18159. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18160. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18161. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18162. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18163. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18164. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18165. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18166. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18167. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18168. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18169. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18170. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18171. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18172. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18173. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18174. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18175. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18176. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18177. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18178. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18179. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18180. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18181. (org-defkey org-mode-map "\C-m" 'org-return)
  18182. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18183. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18184. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18185. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18186. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18187. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18188. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18189. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18190. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18191. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18192. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18193. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18194. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18195. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18196. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18197. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18198. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18199. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18200. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18201. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18202. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18203. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18204. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18205. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18206. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18207. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18208. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18209. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18210. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18211. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18212. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18213. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18214. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18215. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18216. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18217. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18218. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18219. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18220. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18221. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18222. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18223. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18224. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18225. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18226. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18227. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18228. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18229. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18230. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18231. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18232. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18233. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18234. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18235. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18236. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18237. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18238. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18239. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18240. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18241. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18242. (defconst org-speed-commands-default
  18243. '(
  18244. ("Outline Navigation")
  18245. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18246. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18247. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18248. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18249. ("F" . org-next-block)
  18250. ("B" . org-previous-block)
  18251. ("u" . (org-speed-move-safe 'outline-up-heading))
  18252. ("j" . org-goto)
  18253. ("g" . (org-refile t))
  18254. ("Outline Visibility")
  18255. ("c" . org-cycle)
  18256. ("C" . org-shifttab)
  18257. (" " . org-display-outline-path)
  18258. ("s" . org-narrow-to-subtree)
  18259. ("=" . org-columns)
  18260. ("Outline Structure Editing")
  18261. ("U" . org-metaup)
  18262. ("D" . org-metadown)
  18263. ("r" . org-metaright)
  18264. ("l" . org-metaleft)
  18265. ("R" . org-shiftmetaright)
  18266. ("L" . org-shiftmetaleft)
  18267. ("i" . (progn (forward-char 1) (call-interactively
  18268. 'org-insert-heading-respect-content)))
  18269. ("^" . org-sort)
  18270. ("w" . org-refile)
  18271. ("a" . org-archive-subtree-default-with-confirmation)
  18272. ("@" . org-mark-subtree)
  18273. ("#" . org-toggle-comment)
  18274. ("Clock Commands")
  18275. ("I" . org-clock-in)
  18276. ("O" . org-clock-out)
  18277. ("Meta Data Editing")
  18278. ("t" . org-todo)
  18279. ("," . (org-priority))
  18280. ("0" . (org-priority ?\ ))
  18281. ("1" . (org-priority ?A))
  18282. ("2" . (org-priority ?B))
  18283. ("3" . (org-priority ?C))
  18284. (":" . org-set-tags-command)
  18285. ("e" . org-set-effort)
  18286. ("E" . org-inc-effort)
  18287. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18288. (org-entry-put (point) "APPT_WARNTIME" m)))
  18289. ("Agenda Views etc")
  18290. ("v" . org-agenda)
  18291. ("/" . org-sparse-tree)
  18292. ("Misc")
  18293. ("o" . org-open-at-point)
  18294. ("?" . org-speed-command-help)
  18295. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18296. (">" . (org-agenda-remove-restriction-lock))
  18297. )
  18298. "The default speed commands.")
  18299. (defun org-print-speed-command (e)
  18300. (if (> (length (car e)) 1)
  18301. (progn
  18302. (princ "\n")
  18303. (princ (car e))
  18304. (princ "\n")
  18305. (princ (make-string (length (car e)) ?-))
  18306. (princ "\n"))
  18307. (princ (car e))
  18308. (princ " ")
  18309. (if (symbolp (cdr e))
  18310. (princ (symbol-name (cdr e)))
  18311. (prin1 (cdr e)))
  18312. (princ "\n")))
  18313. (defun org-speed-command-help ()
  18314. "Show the available speed commands."
  18315. (interactive)
  18316. (if (not org-use-speed-commands)
  18317. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18318. (with-output-to-temp-buffer "*Help*"
  18319. (princ "User-defined Speed commands\n===========================\n")
  18320. (mapc #'org-print-speed-command org-speed-commands-user)
  18321. (princ "\n")
  18322. (princ "Built-in Speed commands\n=======================\n")
  18323. (mapc #'org-print-speed-command org-speed-commands-default))
  18324. (with-current-buffer "*Help*"
  18325. (setq truncate-lines t))))
  18326. (defun org-speed-move-safe (cmd)
  18327. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18328. If not, return to the original position and throw an error."
  18329. (interactive)
  18330. (let ((pos (point)))
  18331. (call-interactively cmd)
  18332. (unless (and (bolp) (org-at-heading-p))
  18333. (goto-char pos)
  18334. (error "Boundary reached while executing %s" cmd))))
  18335. (defvar org-self-insert-command-undo-counter 0)
  18336. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18337. (defvar org-speed-command nil)
  18338. (defun org-speed-command-activate (keys)
  18339. "Hook for activating single-letter speed commands.
  18340. `org-speed-commands-default' specifies a minimal command set.
  18341. Use `org-speed-commands-user' for further customization."
  18342. (when (or (and (bolp) (looking-at org-outline-regexp))
  18343. (and (functionp org-use-speed-commands)
  18344. (funcall org-use-speed-commands)))
  18345. (cdr (assoc keys (append org-speed-commands-user
  18346. org-speed-commands-default)))))
  18347. (defun org-babel-speed-command-activate (keys)
  18348. "Hook for activating single-letter code block commands."
  18349. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18350. (cdr (assoc keys org-babel-key-bindings))))
  18351. (defcustom org-speed-command-hook
  18352. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18353. "Hook for activating speed commands at strategic locations.
  18354. Hook functions are called in sequence until a valid handler is
  18355. found.
  18356. Each hook takes a single argument, a user-pressed command key
  18357. which is also a `self-insert-command' from the global map.
  18358. Within the hook, examine the cursor position and the command key
  18359. and return nil or a valid handler as appropriate. Handler could
  18360. be one of an interactive command, a function, or a form.
  18361. Set `org-use-speed-commands' to non-nil value to enable this
  18362. hook. The default setting is `org-speed-command-activate'."
  18363. :group 'org-structure
  18364. :version "24.1"
  18365. :type 'hook)
  18366. (defun org-self-insert-command (N)
  18367. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18368. If the cursor is in a table looking at whitespace, the whitespace is
  18369. overwritten, and the table is not marked as requiring realignment."
  18370. (interactive "p")
  18371. (org-check-before-invisible-edit 'insert)
  18372. (cond
  18373. ((and org-use-speed-commands
  18374. (let ((kv (this-command-keys-vector)))
  18375. (setq org-speed-command
  18376. (run-hook-with-args-until-success
  18377. 'org-speed-command-hook
  18378. (make-string 1 (aref kv (1- (length kv))))))))
  18379. (cond
  18380. ((commandp org-speed-command)
  18381. (setq this-command org-speed-command)
  18382. (call-interactively org-speed-command))
  18383. ((functionp org-speed-command)
  18384. (funcall org-speed-command))
  18385. ((and org-speed-command (listp org-speed-command))
  18386. (eval org-speed-command))
  18387. (t (let (org-use-speed-commands)
  18388. (call-interactively 'org-self-insert-command)))))
  18389. ((and
  18390. (org-at-table-p)
  18391. (progn
  18392. ;; Check if we blank the field, and if that triggers align.
  18393. (and (featurep 'org-table) org-table-auto-blank-field
  18394. (memq last-command
  18395. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18396. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18397. ;; Got extra space, this field does not determine
  18398. ;; column width.
  18399. (let (org-table-may-need-update) (org-table-blank-field))
  18400. ;; No extra space, this field may determine column
  18401. ;; width.
  18402. (org-table-blank-field)))
  18403. t)
  18404. (eq N 1)
  18405. (looking-at "[^|\n]* \\( \\)|"))
  18406. ;; There is room for insertion without re-aligning the table.
  18407. (delete-region (match-beginning 1) (match-end 1))
  18408. (self-insert-command N))
  18409. (t
  18410. (setq org-table-may-need-update t)
  18411. (self-insert-command N)
  18412. (org-fix-tags-on-the-fly)
  18413. (when org-self-insert-cluster-for-undo
  18414. (if (not (eq last-command 'org-self-insert-command))
  18415. (setq org-self-insert-command-undo-counter 1)
  18416. (if (>= org-self-insert-command-undo-counter 20)
  18417. (setq org-self-insert-command-undo-counter 1)
  18418. (and (> org-self-insert-command-undo-counter 0)
  18419. buffer-undo-list (listp buffer-undo-list)
  18420. (not (cadr buffer-undo-list)) ; remove nil entry
  18421. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18422. (setq org-self-insert-command-undo-counter
  18423. (1+ org-self-insert-command-undo-counter))))))))
  18424. (defun org-check-before-invisible-edit (kind)
  18425. "Check is editing if kind KIND would be dangerous with invisible text around.
  18426. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18427. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18428. (when (and org-catch-invisible-edits
  18429. (or (not (boundp 'visible-mode)) (not visible-mode))
  18430. (or (get-char-property (point) 'invisible)
  18431. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18432. ;; OK, we need to take a closer look
  18433. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18434. (invisible-before-point (unless (bobp) (get-char-property
  18435. (1- (point)) 'invisible)))
  18436. (border-and-ok-direction
  18437. (or
  18438. ;; Check if we are acting predictably before invisible text
  18439. (and invisible-at-point (not invisible-before-point)
  18440. (memq kind '(insert delete-backward)))
  18441. ;; Check if we are acting predictably after invisible text
  18442. ;; This works not well, and I have turned it off. It seems
  18443. ;; better to always show and stop after invisible text.
  18444. ;; (and (not invisible-at-point) invisible-before-point
  18445. ;; (memq kind '(insert delete)))
  18446. )))
  18447. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18448. (memq invisible-before-point '(outline org-hide-block t)))
  18449. (when (eq org-catch-invisible-edits 'error)
  18450. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18451. (if (and org-custom-properties-overlays
  18452. (y-or-n-p "Display invisible properties in this buffer? "))
  18453. (org-toggle-custom-properties-visibility)
  18454. ;; Make the area visible
  18455. (save-excursion
  18456. (when invisible-before-point
  18457. (goto-char (previous-single-char-property-change
  18458. (point) 'invisible)))
  18459. (outline-show-subtree))
  18460. (cond
  18461. ((eq org-catch-invisible-edits 'show)
  18462. ;; That's it, we do the edit after showing
  18463. (message
  18464. "Unfolding invisible region around point before editing")
  18465. (sit-for 1))
  18466. ((and (eq org-catch-invisible-edits 'smart)
  18467. border-and-ok-direction)
  18468. (message "Unfolding invisible region around point before editing"))
  18469. (t
  18470. ;; Don't do the edit, make the user repeat it in full visibility
  18471. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18472. (defun org-fix-tags-on-the-fly ()
  18473. (when (and (equal (char-after (point-at-bol)) ?*)
  18474. (org-at-heading-p))
  18475. (org-align-tags-here org-tags-column)))
  18476. (defun org-delete-backward-char (N)
  18477. "Like `delete-backward-char', insert whitespace at field end in tables.
  18478. When deleting backwards, in tables this function will insert whitespace in
  18479. front of the next \"|\" separator, to keep the table aligned. The table will
  18480. still be marked for re-alignment if the field did fill the entire column,
  18481. because, in this case the deletion might narrow the column."
  18482. (interactive "p")
  18483. (save-match-data
  18484. (org-check-before-invisible-edit 'delete-backward)
  18485. (if (and (org-at-table-p)
  18486. (eq N 1)
  18487. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18488. (looking-at ".*?|"))
  18489. (let ((pos (point))
  18490. (noalign (looking-at "[^|\n\r]* |"))
  18491. (c org-table-may-need-update))
  18492. (backward-delete-char N)
  18493. (unless overwrite-mode
  18494. (skip-chars-forward "^|")
  18495. (insert " ")
  18496. (goto-char (1- pos)))
  18497. ;; noalign: if there were two spaces at the end, this field
  18498. ;; does not determine the width of the column.
  18499. (when noalign (setq org-table-may-need-update c)))
  18500. (backward-delete-char N)
  18501. (org-fix-tags-on-the-fly))))
  18502. (defun org-delete-char (N)
  18503. "Like `delete-char', but insert whitespace at field end in tables.
  18504. When deleting characters, in tables this function will insert whitespace in
  18505. front of the next \"|\" separator, to keep the table aligned. The table will
  18506. still be marked for re-alignment if the field did fill the entire column,
  18507. because, in this case the deletion might narrow the column."
  18508. (interactive "p")
  18509. (save-match-data
  18510. (org-check-before-invisible-edit 'delete)
  18511. (if (and (org-at-table-p)
  18512. (not (bolp))
  18513. (not (= (char-after) ?|))
  18514. (eq N 1))
  18515. (if (looking-at ".*?|")
  18516. (let ((pos (point))
  18517. (noalign (looking-at "[^|\n\r]* |"))
  18518. (c org-table-may-need-update))
  18519. (replace-match
  18520. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18521. (goto-char pos)
  18522. ;; noalign: if there were two spaces at the end, this field
  18523. ;; does not determine the width of the column.
  18524. (when noalign (setq org-table-may-need-update c)))
  18525. (delete-char N))
  18526. (delete-char N)
  18527. (org-fix-tags-on-the-fly))))
  18528. ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
  18529. (put 'org-self-insert-command 'delete-selection
  18530. (lambda ()
  18531. (not (run-hook-with-args-until-success
  18532. 'self-insert-uses-region-functions))))
  18533. (put 'orgtbl-self-insert-command 'delete-selection
  18534. (lambda ()
  18535. (not (run-hook-with-args-until-success
  18536. 'self-insert-uses-region-functions))))
  18537. (put 'org-delete-char 'delete-selection 'supersede)
  18538. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18539. (put 'org-yank 'delete-selection 'yank)
  18540. ;; Make `flyspell-mode' delay after some commands
  18541. (put 'org-self-insert-command 'flyspell-delayed t)
  18542. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18543. (put 'org-delete-char 'flyspell-delayed t)
  18544. (put 'org-delete-backward-char 'flyspell-delayed t)
  18545. ;; Make pabbrev-mode expand after org-mode commands
  18546. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18547. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18548. (defun org-remap (map &rest commands)
  18549. "In MAP, remap the functions given in COMMANDS.
  18550. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18551. (let (new old)
  18552. (while commands
  18553. (setq old (pop commands) new (pop commands))
  18554. (if (fboundp 'command-remapping)
  18555. (org-defkey map (vector 'remap old) new)
  18556. (substitute-key-definition old new map global-map)))))
  18557. (defun org-transpose-words ()
  18558. "Transpose words for Org.
  18559. This uses the `org-mode-transpose-word-syntax-table' syntax
  18560. table, which interprets characters in `org-emphasis-alist' as
  18561. word constituents."
  18562. (interactive)
  18563. (with-syntax-table org-mode-transpose-word-syntax-table
  18564. (call-interactively 'transpose-words)))
  18565. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18566. (when (eq org-enable-table-editor 'optimized)
  18567. ;; If the user wants maximum table support, we need to hijack
  18568. ;; some standard editing functions
  18569. (org-remap org-mode-map
  18570. 'self-insert-command 'org-self-insert-command
  18571. 'delete-char 'org-delete-char
  18572. 'delete-backward-char 'org-delete-backward-char)
  18573. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18574. (defvar org-ctrl-c-ctrl-c-hook nil
  18575. "Hook for functions attaching themselves to `C-c C-c'.
  18576. This can be used to add additional functionality to the C-c C-c
  18577. key which executes context-dependent commands. This hook is run
  18578. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18579. run after the last test.
  18580. Each function will be called with no arguments. The function
  18581. must check if the context is appropriate for it to act. If yes,
  18582. it should do its thing and then return a non-nil value. If the
  18583. context is wrong, just do nothing and return nil.")
  18584. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18585. "Hook for functions attaching themselves to `C-c C-c'.
  18586. This can be used to add additional functionality to the C-c C-c
  18587. key which executes context-dependent commands. This hook is run
  18588. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18589. before the first test.
  18590. Each function will be called with no arguments. The function
  18591. must check if the context is appropriate for it to act. If yes,
  18592. it should do its thing and then return a non-nil value. If the
  18593. context is wrong, just do nothing and return nil.")
  18594. (defvar org-tab-first-hook nil
  18595. "Hook for functions to attach themselves to TAB.
  18596. See `org-ctrl-c-ctrl-c-hook' for more information.
  18597. This hook runs as the first action when TAB is pressed, even before
  18598. `org-cycle' messes around with the `outline-regexp' to cater for
  18599. inline tasks and plain list item folding.
  18600. If any function in this hook returns t, any other actions that
  18601. would have been caused by TAB (such as table field motion or visibility
  18602. cycling) will not occur.")
  18603. (defvar org-tab-after-check-for-table-hook nil
  18604. "Hook for functions to attach themselves to TAB.
  18605. See `org-ctrl-c-ctrl-c-hook' for more information.
  18606. This hook runs after it has been established that the cursor is not in a
  18607. table, but before checking if the cursor is in a headline or if global cycling
  18608. should be done.
  18609. If any function in this hook returns t, not other actions like visibility
  18610. cycling will be done.")
  18611. (defvar org-tab-after-check-for-cycling-hook nil
  18612. "Hook for functions to attach themselves to TAB.
  18613. See `org-ctrl-c-ctrl-c-hook' for more information.
  18614. This hook runs after it has been established that not table field motion and
  18615. not visibility should be done because of current context. This is probably
  18616. the place where a package like yasnippets can hook in.")
  18617. (defvar org-tab-before-tab-emulation-hook nil
  18618. "Hook for functions to attach themselves to TAB.
  18619. See `org-ctrl-c-ctrl-c-hook' for more information.
  18620. This hook runs after every other options for TAB have been exhausted, but
  18621. before indentation and \t insertion takes place.")
  18622. (defvar org-metaleft-hook nil
  18623. "Hook for functions attaching themselves to `M-left'.
  18624. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18625. (defvar org-metaright-hook nil
  18626. "Hook for functions attaching themselves to `M-right'.
  18627. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18628. (defvar org-metaup-hook nil
  18629. "Hook for functions attaching themselves to `M-up'.
  18630. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18631. (defvar org-metadown-hook nil
  18632. "Hook for functions attaching themselves to `M-down'.
  18633. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18634. (defvar org-shiftmetaleft-hook nil
  18635. "Hook for functions attaching themselves to `M-S-left'.
  18636. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18637. (defvar org-shiftmetaright-hook nil
  18638. "Hook for functions attaching themselves to `M-S-right'.
  18639. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18640. (defvar org-shiftmetaup-hook nil
  18641. "Hook for functions attaching themselves to `M-S-up'.
  18642. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18643. (defvar org-shiftmetadown-hook nil
  18644. "Hook for functions attaching themselves to `M-S-down'.
  18645. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18646. (defvar org-metareturn-hook nil
  18647. "Hook for functions attaching themselves to `M-RET'.
  18648. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18649. (defvar org-shiftup-hook nil
  18650. "Hook for functions attaching themselves to `S-up'.
  18651. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18652. (defvar org-shiftup-final-hook nil
  18653. "Hook for functions attaching themselves to `S-up'.
  18654. This one runs after all other options except shift-select have been excluded.
  18655. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18656. (defvar org-shiftdown-hook nil
  18657. "Hook for functions attaching themselves to `S-down'.
  18658. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18659. (defvar org-shiftdown-final-hook nil
  18660. "Hook for functions attaching themselves to `S-down'.
  18661. This one runs after all other options except shift-select have been excluded.
  18662. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18663. (defvar org-shiftleft-hook nil
  18664. "Hook for functions attaching themselves to `S-left'.
  18665. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18666. (defvar org-shiftleft-final-hook nil
  18667. "Hook for functions attaching themselves to `S-left'.
  18668. This one runs after all other options except shift-select have been excluded.
  18669. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18670. (defvar org-shiftright-hook nil
  18671. "Hook for functions attaching themselves to `S-right'.
  18672. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18673. (defvar org-shiftright-final-hook nil
  18674. "Hook for functions attaching themselves to `S-right'.
  18675. This one runs after all other options except shift-select have been excluded.
  18676. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18677. (defun org-modifier-cursor-error ()
  18678. "Throw an error, a modified cursor command was applied in wrong context."
  18679. (user-error "This command is active in special context like tables, headlines or items"))
  18680. (defun org-shiftselect-error ()
  18681. "Throw an error because Shift-Cursor command was applied in wrong context."
  18682. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18683. (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
  18684. (user-error "This command works only in special context like headlines or timestamps")))
  18685. (defun org-call-for-shift-select (cmd)
  18686. (let ((this-command-keys-shift-translated t))
  18687. (call-interactively cmd)))
  18688. (defun org-shifttab (&optional arg)
  18689. "Global visibility cycling or move to previous table field.
  18690. Call `org-table-previous-field' within a table.
  18691. When ARG is nil, cycle globally through visibility states.
  18692. When ARG is a numeric prefix, show contents of this level."
  18693. (interactive "P")
  18694. (cond
  18695. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18696. ((integerp arg)
  18697. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18698. (message "Content view to level: %d" arg)
  18699. (org-content (prefix-numeric-value arg2))
  18700. (org-cycle-show-empty-lines t)
  18701. (setq org-cycle-global-status 'overview)))
  18702. (t (call-interactively 'org-global-cycle))))
  18703. (defun org-shiftmetaleft ()
  18704. "Promote subtree or delete table column.
  18705. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18706. `org-table-delete-column', depending on context. See the
  18707. individual commands for more information."
  18708. (interactive)
  18709. (cond
  18710. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18711. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18712. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18713. ((if (not (org-region-active-p)) (org-at-item-p)
  18714. (save-excursion (goto-char (region-beginning))
  18715. (org-at-item-p)))
  18716. (call-interactively 'org-outdent-item-tree))
  18717. (t (org-modifier-cursor-error))))
  18718. (defun org-shiftmetaright ()
  18719. "Demote subtree or insert table column.
  18720. Calls `org-demote-subtree', `org-indent-item-tree', or
  18721. `org-table-insert-column', depending on context. See the
  18722. individual commands for more information."
  18723. (interactive)
  18724. (cond
  18725. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18726. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18727. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18728. ((if (not (org-region-active-p)) (org-at-item-p)
  18729. (save-excursion (goto-char (region-beginning))
  18730. (org-at-item-p)))
  18731. (call-interactively 'org-indent-item-tree))
  18732. (t (org-modifier-cursor-error))))
  18733. (defun org-shiftmetaup (&optional _arg)
  18734. "Drag the line at point up.
  18735. In a table, kill the current row.
  18736. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18737. but also adjust the previous clocked item in the clock history.
  18738. Everywhere else, drag the line at point up."
  18739. (interactive "P")
  18740. (cond
  18741. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18742. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18743. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18744. (call-interactively 'org-timestamp-up)))
  18745. (t (call-interactively 'org-drag-line-backward))))
  18746. (defun org-shiftmetadown (&optional _arg)
  18747. "Drag the line at point down.
  18748. In a table, insert an empty row at the current line.
  18749. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18750. but also adjust the previous clocked item in the clock history.
  18751. Everywhere else, drag the line at point down."
  18752. (interactive "P")
  18753. (cond
  18754. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18755. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18756. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18757. (call-interactively 'org-timestamp-down)))
  18758. (t (call-interactively 'org-drag-line-forward))))
  18759. (defsubst org-hidden-tree-error ()
  18760. (user-error
  18761. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18762. (defun org-metaleft (&optional _arg)
  18763. "Promote heading, list item at point or move table column left.
  18764. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18765. depending on context. With no specific context, calls the Emacs
  18766. default `backward-word'. See the individual commands for more
  18767. information.
  18768. This function runs the hook `org-metaleft-hook' as a first step,
  18769. and returns at first non-nil value."
  18770. (interactive "P")
  18771. (cond
  18772. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18773. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18774. ((org-with-limited-levels
  18775. (or (org-at-heading-p)
  18776. (and (org-region-active-p)
  18777. (save-excursion
  18778. (goto-char (region-beginning))
  18779. (org-at-heading-p)))))
  18780. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18781. (call-interactively 'org-do-promote))
  18782. ;; At an inline task.
  18783. ((org-at-heading-p)
  18784. (call-interactively 'org-inlinetask-promote))
  18785. ((or (org-at-item-p)
  18786. (and (org-region-active-p)
  18787. (save-excursion
  18788. (goto-char (region-beginning))
  18789. (org-at-item-p))))
  18790. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18791. (call-interactively 'org-outdent-item))
  18792. (t (call-interactively 'backward-word))))
  18793. (defun org-metaright (&optional _arg)
  18794. "Demote heading, list item at point or move table column right.
  18795. In front of a drawer or a block keyword, indent it correctly.
  18796. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18797. `org-indnet-drawer' or `org-indent-block' depending on context.
  18798. With no specific context, calls the Emacs default `forward-word'.
  18799. See the individual commands for more information.
  18800. This function runs the hook `org-metaright-hook' as a first step,
  18801. and returns at first non-nil value."
  18802. (interactive "P")
  18803. (cond
  18804. ((run-hook-with-args-until-success 'org-metaright-hook))
  18805. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18806. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18807. ((org-at-block-p) (call-interactively 'org-indent-block))
  18808. ((org-with-limited-levels
  18809. (or (org-at-heading-p)
  18810. (and (org-region-active-p)
  18811. (save-excursion
  18812. (goto-char (region-beginning))
  18813. (org-at-heading-p)))))
  18814. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18815. (call-interactively 'org-do-demote))
  18816. ;; At an inline task.
  18817. ((org-at-heading-p)
  18818. (call-interactively 'org-inlinetask-demote))
  18819. ((or (org-at-item-p)
  18820. (and (org-region-active-p)
  18821. (save-excursion
  18822. (goto-char (region-beginning))
  18823. (org-at-item-p))))
  18824. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18825. (call-interactively 'org-indent-item))
  18826. (t (call-interactively 'forward-word))))
  18827. (defun org-check-for-hidden (what)
  18828. "Check if there are hidden headlines/items in the current visual line.
  18829. WHAT can be either `headlines' or `items'. If the current line is
  18830. an outline or item heading and it has a folded subtree below it,
  18831. this function returns t, nil otherwise."
  18832. (let ((re (cond
  18833. ((eq what 'headlines) org-outline-regexp-bol)
  18834. ((eq what 'items) (org-item-beginning-re))
  18835. (t (error "This should not happen"))))
  18836. beg end)
  18837. (save-excursion
  18838. (catch 'exit
  18839. (unless (org-region-active-p)
  18840. (setq beg (point-at-bol))
  18841. (beginning-of-line 2)
  18842. (while (and (not (eobp)) ;; this is like `next-line'
  18843. (get-char-property (1- (point)) 'invisible))
  18844. (beginning-of-line 2))
  18845. (setq end (point))
  18846. (goto-char beg)
  18847. (goto-char (point-at-eol))
  18848. (setq end (max end (point)))
  18849. (while (re-search-forward re end t)
  18850. (when (get-char-property (match-beginning 0) 'invisible)
  18851. (throw 'exit t))))
  18852. nil))))
  18853. (defun org-metaup (&optional _arg)
  18854. "Move subtree up or move table row up.
  18855. Calls `org-move-subtree-up' or `org-table-move-row' or
  18856. `org-move-item-up', depending on context. See the individual commands
  18857. for more information."
  18858. (interactive "P")
  18859. (cond
  18860. ((run-hook-with-args-until-success 'org-metaup-hook))
  18861. ((org-region-active-p)
  18862. (let* ((a (min (region-beginning) (region-end)))
  18863. (b (1- (max (region-beginning) (region-end))))
  18864. (c (save-excursion (goto-char a)
  18865. (move-beginning-of-line 0)))
  18866. (d (save-excursion (goto-char a)
  18867. (move-end-of-line 0) (point))))
  18868. (transpose-regions a b c d)
  18869. (goto-char c)))
  18870. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18871. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18872. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18873. (t (org-drag-element-backward))))
  18874. (defun org-metadown (&optional _arg)
  18875. "Move subtree down or move table row down.
  18876. Calls `org-move-subtree-down' or `org-table-move-row' or
  18877. `org-move-item-down', depending on context. See the individual
  18878. commands for more information."
  18879. (interactive "P")
  18880. (cond
  18881. ((run-hook-with-args-until-success 'org-metadown-hook))
  18882. ((org-region-active-p)
  18883. (let* ((a (min (region-beginning) (region-end)))
  18884. (b (max (region-beginning) (region-end)))
  18885. (c (save-excursion (goto-char b)
  18886. (move-beginning-of-line 1)))
  18887. (d (save-excursion (goto-char b)
  18888. (move-end-of-line 1) (1+ (point)))))
  18889. (transpose-regions a b c d)
  18890. (goto-char d)))
  18891. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18892. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18893. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18894. (t (org-drag-element-forward))))
  18895. (defun org-shiftup (&optional arg)
  18896. "Increase item in timestamp or increase priority of current headline.
  18897. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18898. depending on context. See the individual commands for more information."
  18899. (interactive "P")
  18900. (cond
  18901. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18902. ((and org-support-shift-select (org-region-active-p))
  18903. (org-call-for-shift-select 'previous-line))
  18904. ((org-at-timestamp-p t)
  18905. (call-interactively (if org-edit-timestamp-down-means-later
  18906. 'org-timestamp-down 'org-timestamp-up)))
  18907. ((and (not (eq org-support-shift-select 'always))
  18908. org-enable-priority-commands
  18909. (org-at-heading-p))
  18910. (call-interactively 'org-priority-up))
  18911. ((and (not org-support-shift-select) (org-at-item-p))
  18912. (call-interactively 'org-previous-item))
  18913. ((org-clocktable-try-shift 'up arg))
  18914. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18915. (org-support-shift-select
  18916. (org-call-for-shift-select 'previous-line))
  18917. (t (org-shiftselect-error))))
  18918. (defun org-shiftdown (&optional arg)
  18919. "Decrease item in timestamp or decrease priority of current headline.
  18920. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18921. depending on context. See the individual commands for more information."
  18922. (interactive "P")
  18923. (cond
  18924. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18925. ((and org-support-shift-select (org-region-active-p))
  18926. (org-call-for-shift-select 'next-line))
  18927. ((org-at-timestamp-p t)
  18928. (call-interactively (if org-edit-timestamp-down-means-later
  18929. 'org-timestamp-up 'org-timestamp-down)))
  18930. ((and (not (eq org-support-shift-select 'always))
  18931. org-enable-priority-commands
  18932. (org-at-heading-p))
  18933. (call-interactively 'org-priority-down))
  18934. ((and (not org-support-shift-select) (org-at-item-p))
  18935. (call-interactively 'org-next-item))
  18936. ((org-clocktable-try-shift 'down arg))
  18937. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18938. (org-support-shift-select
  18939. (org-call-for-shift-select 'next-line))
  18940. (t (org-shiftselect-error))))
  18941. (defun org-shiftright (&optional arg)
  18942. "Cycle the thing at point or in the current line, depending on context.
  18943. Depending on context, this does one of the following:
  18944. - switch a timestamp at point one day into the future
  18945. - on a headline, switch to the next TODO keyword.
  18946. - on an item, switch entire list to the next bullet type
  18947. - on a property line, switch to the next allowed value
  18948. - on a clocktable definition line, move time block into the future"
  18949. (interactive "P")
  18950. (cond
  18951. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18952. ((and org-support-shift-select (org-region-active-p))
  18953. (org-call-for-shift-select 'forward-char))
  18954. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  18955. ((and (not (eq org-support-shift-select 'always))
  18956. (org-at-heading-p))
  18957. (let ((org-inhibit-logging
  18958. (not org-treat-S-cursor-todo-selection-as-state-change))
  18959. (org-inhibit-blocking
  18960. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18961. (org-call-with-arg 'org-todo 'right)))
  18962. ((or (and org-support-shift-select
  18963. (not (eq org-support-shift-select 'always))
  18964. (org-at-item-bullet-p))
  18965. (and (not org-support-shift-select) (org-at-item-p)))
  18966. (org-call-with-arg 'org-cycle-list-bullet nil))
  18967. ((and (not (eq org-support-shift-select 'always))
  18968. (org-at-property-p))
  18969. (call-interactively 'org-property-next-allowed-value))
  18970. ((org-clocktable-try-shift 'right arg))
  18971. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18972. (org-support-shift-select
  18973. (org-call-for-shift-select 'forward-char))
  18974. (t (org-shiftselect-error))))
  18975. (defun org-shiftleft (&optional arg)
  18976. "Cycle the thing at point or in the current line, depending on context.
  18977. Depending on context, this does one of the following:
  18978. - switch a timestamp at point one day into the past
  18979. - on a headline, switch to the previous TODO keyword.
  18980. - on an item, switch entire list to the previous bullet type
  18981. - on a property line, switch to the previous allowed value
  18982. - on a clocktable definition line, move time block into the past"
  18983. (interactive "P")
  18984. (cond
  18985. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18986. ((and org-support-shift-select (org-region-active-p))
  18987. (org-call-for-shift-select 'backward-char))
  18988. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  18989. ((and (not (eq org-support-shift-select 'always))
  18990. (org-at-heading-p))
  18991. (let ((org-inhibit-logging
  18992. (not org-treat-S-cursor-todo-selection-as-state-change))
  18993. (org-inhibit-blocking
  18994. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18995. (org-call-with-arg 'org-todo 'left)))
  18996. ((or (and org-support-shift-select
  18997. (not (eq org-support-shift-select 'always))
  18998. (org-at-item-bullet-p))
  18999. (and (not org-support-shift-select) (org-at-item-p)))
  19000. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19001. ((and (not (eq org-support-shift-select 'always))
  19002. (org-at-property-p))
  19003. (call-interactively 'org-property-previous-allowed-value))
  19004. ((org-clocktable-try-shift 'left arg))
  19005. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19006. (org-support-shift-select
  19007. (org-call-for-shift-select 'backward-char))
  19008. (t (org-shiftselect-error))))
  19009. (defun org-shiftcontrolright ()
  19010. "Switch to next TODO set."
  19011. (interactive)
  19012. (cond
  19013. ((and org-support-shift-select (org-region-active-p))
  19014. (org-call-for-shift-select 'forward-word))
  19015. ((and (not (eq org-support-shift-select 'always))
  19016. (org-at-heading-p))
  19017. (org-call-with-arg 'org-todo 'nextset))
  19018. (org-support-shift-select
  19019. (org-call-for-shift-select 'forward-word))
  19020. (t (org-shiftselect-error))))
  19021. (defun org-shiftcontrolleft ()
  19022. "Switch to previous TODO set."
  19023. (interactive)
  19024. (cond
  19025. ((and org-support-shift-select (org-region-active-p))
  19026. (org-call-for-shift-select 'backward-word))
  19027. ((and (not (eq org-support-shift-select 'always))
  19028. (org-at-heading-p))
  19029. (org-call-with-arg 'org-todo 'previousset))
  19030. (org-support-shift-select
  19031. (org-call-for-shift-select 'backward-word))
  19032. (t (org-shiftselect-error))))
  19033. (defun org-shiftcontrolup (&optional n)
  19034. "Change timestamps synchronously up in CLOCK log lines.
  19035. Optional argument N tells to change by that many units."
  19036. (interactive "P")
  19037. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19038. (let (org-support-shift-select)
  19039. (org-clock-timestamps-up n))
  19040. (user-error "Not at a clock log")))
  19041. (defun org-shiftcontroldown (&optional n)
  19042. "Change timestamps synchronously down in CLOCK log lines.
  19043. Optional argument N tells to change by that many units."
  19044. (interactive "P")
  19045. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19046. (let (org-support-shift-select)
  19047. (org-clock-timestamps-down n))
  19048. (user-error "Not at a clock log")))
  19049. (defun org-increase-number-at-point (&optional inc)
  19050. "Increment the number at point.
  19051. With an optional prefix numeric argument INC, increment using
  19052. this numeric value."
  19053. (interactive "p")
  19054. (if (not (number-at-point))
  19055. (user-error "Not on a number")
  19056. (unless inc (setq inc 1))
  19057. (let ((pos (point))
  19058. (beg (skip-chars-backward "-+^/*0-9eE."))
  19059. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19060. (setq nap (buffer-substring-no-properties
  19061. (+ pos beg) (+ pos beg end)))
  19062. (delete-region (+ pos beg) (+ pos beg end))
  19063. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19064. (when (org-at-table-p)
  19065. (org-table-align)
  19066. (org-table-end-of-field 1))))
  19067. (defun org-decrease-number-at-point (&optional inc)
  19068. "Decrement the number at point.
  19069. With an optional prefix numeric argument INC, decrement using
  19070. this numeric value."
  19071. (interactive "p")
  19072. (org-increase-number-at-point (- (or inc 1))))
  19073. (defun org-ctrl-c-ret ()
  19074. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19075. (interactive)
  19076. (cond
  19077. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19078. (t (call-interactively 'org-insert-heading))))
  19079. (defun org-find-visible ()
  19080. (let ((s (point)))
  19081. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19082. (get-char-property s 'invisible)))
  19083. s))
  19084. (defun org-find-invisible ()
  19085. (let ((s (point)))
  19086. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19087. (not (get-char-property s 'invisible))))
  19088. s))
  19089. (defun org-copy-visible (beg end)
  19090. "Copy the visible parts of the region."
  19091. (interactive "r")
  19092. (let (snippets s)
  19093. (save-excursion
  19094. (save-restriction
  19095. (narrow-to-region beg end)
  19096. (setq s (goto-char (point-min)))
  19097. (while (not (= (point) (point-max)))
  19098. (goto-char (org-find-invisible))
  19099. (push (buffer-substring s (point)) snippets)
  19100. (setq s (goto-char (org-find-visible))))))
  19101. (kill-new (apply 'concat (nreverse snippets)))))
  19102. (defun org-copy-special ()
  19103. "Copy region in table or copy current subtree.
  19104. Calls `org-table-copy' or `org-copy-subtree', depending on context.
  19105. See the individual commands for more information."
  19106. (interactive)
  19107. (call-interactively
  19108. (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
  19109. (defun org-cut-special ()
  19110. "Cut region in table or cut current subtree.
  19111. Calls `org-table-copy' or `org-cut-subtree', depending on context.
  19112. See the individual commands for more information."
  19113. (interactive)
  19114. (call-interactively
  19115. (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
  19116. (defun org-paste-special (arg)
  19117. "Paste rectangular region into table, or past subtree relative to level.
  19118. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19119. See the individual commands for more information."
  19120. (interactive "P")
  19121. (if (org-at-table-p)
  19122. (org-table-paste-rectangle)
  19123. (org-paste-subtree arg)))
  19124. (defsubst org-in-fixed-width-region-p ()
  19125. "Is point in a fixed-width region?"
  19126. (save-match-data
  19127. (eq 'fixed-width (org-element-type (org-element-at-point)))))
  19128. (defun org-edit-special (&optional arg)
  19129. "Call a special editor for the element at point.
  19130. When at a table, call the formula editor with `org-table-edit-formulas'.
  19131. When in a source code block, call `org-edit-src-code'.
  19132. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19133. When in an export block, call `org-edit-export-block'.
  19134. When at an #+INCLUDE keyword, visit the included file.
  19135. When at a footnote reference, call `org-edit-footnote-reference'
  19136. On a link, call `ffap' to visit the link at point.
  19137. Otherwise, return a user error."
  19138. (interactive "P")
  19139. (let ((element (org-element-at-point)))
  19140. (cl-assert (not buffer-read-only) nil
  19141. "Buffer is read-only: %s" (buffer-name))
  19142. (pcase (org-element-type element)
  19143. (`src-block
  19144. (if (not arg) (org-edit-src-code)
  19145. (let* ((info (org-babel-get-src-block-info))
  19146. (lang (nth 0 info))
  19147. (params (nth 2 info))
  19148. (session (cdr (assq :session params))))
  19149. (if (not session) (org-edit-src-code)
  19150. ;; At a src-block with a session and function called with
  19151. ;; an ARG: switch to the buffer related to the inferior
  19152. ;; process.
  19153. (switch-to-buffer
  19154. (funcall (intern (concat "org-babel-prep-session:" lang))
  19155. session params))))))
  19156. (`keyword
  19157. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19158. (org-open-link-from-string
  19159. (format "[[%s]]"
  19160. (expand-file-name
  19161. (let ((value (org-element-property :value element)))
  19162. (cond ((not (org-string-nw-p value))
  19163. (user-error "No file to edit"))
  19164. ((string-match "\\`\"\\(.*?\\)\"" value)
  19165. (match-string 1 value))
  19166. ((string-match "\\`[^ \t\"]\\S-*" value)
  19167. (match-string 0 value))
  19168. (t (user-error "No valid file specified")))))))
  19169. (user-error "No special environment to edit here")))
  19170. (`table
  19171. (if (eq (org-element-property :type element) 'table.el)
  19172. (org-edit-table.el)
  19173. (call-interactively 'org-table-edit-formulas)))
  19174. ;; Only Org tables contain `table-row' type elements.
  19175. (`table-row (call-interactively 'org-table-edit-formulas))
  19176. (`example-block (org-edit-src-code))
  19177. (`export-block (org-edit-export-block))
  19178. (`fixed-width (org-edit-fixed-width-region))
  19179. (_
  19180. ;; No notable element at point. Though, we may be at a link or
  19181. ;; a footnote reference, which are objects. Thus, scan deeper.
  19182. (let ((context (org-element-context element)))
  19183. (pcase (org-element-type context)
  19184. (`footnote-reference (org-edit-footnote-reference))
  19185. (`inline-src-block (org-edit-inline-src-code))
  19186. (`link (call-interactively #'ffap))
  19187. (_ (user-error "No special environment to edit here"))))))))
  19188. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19189. (defun org-ctrl-c-ctrl-c (&optional arg)
  19190. "Set tags in headline, or update according to changed information at point.
  19191. This command does many different things, depending on context:
  19192. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19193. this is what we do.
  19194. - If the cursor is on a statistics cookie, update it.
  19195. - If the cursor is in a headline, prompt for tags and insert them
  19196. into the current line, aligned to `org-tags-column'. When called
  19197. with prefix arg, realign all tags in the current buffer.
  19198. - If the cursor is in one of the special #+KEYWORD lines, this
  19199. triggers scanning the buffer for these lines and updating the
  19200. information.
  19201. - If the cursor is inside a table, realign the table. This command
  19202. works even if the automatic table editor has been turned off.
  19203. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19204. the entire table.
  19205. - If the cursor is at a footnote reference or definition, jump to
  19206. the corresponding definition or references, respectively.
  19207. - If the cursor is a the beginning of a dynamic block, update it.
  19208. - If the current buffer is a capture buffer, close note and file it.
  19209. - If the cursor is on a <<<target>>>, update radio targets and
  19210. corresponding links in this buffer.
  19211. - If the cursor is on a numbered item in a plain list, renumber the
  19212. ordered list.
  19213. - If the cursor is on a checkbox, toggle it.
  19214. - If the cursor is on a code block, evaluate it. The variable
  19215. `org-confirm-babel-evaluate' can be used to control prompting
  19216. before code block evaluation, by default every code block
  19217. evaluation requires confirmation. Code block evaluation can be
  19218. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19219. (interactive "P")
  19220. (cond
  19221. ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
  19222. org-occur-highlights)
  19223. (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19224. (org-remove-occur-highlights)
  19225. (message "Temporary highlights/overlays removed from current buffer"))
  19226. ((and (local-variable-p 'org-finish-function (current-buffer))
  19227. (fboundp org-finish-function))
  19228. (funcall org-finish-function))
  19229. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19230. (t
  19231. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  19232. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19233. (user-error "C-c C-c can do nothing useful at this location"))
  19234. (let* ((context (org-element-context))
  19235. (type (org-element-type context)))
  19236. (cl-case type
  19237. ;; When at a link, act according to the parent instead.
  19238. (link (setq context (org-element-property :parent context))
  19239. (setq type (org-element-type context)))
  19240. ;; Unsupported object types: refer to the first supported
  19241. ;; element or object containing it.
  19242. ((bold code entity export-snippet inline-babel-call inline-src-block
  19243. italic latex-fragment line-break macro strike-through subscript
  19244. superscript underline verbatim)
  19245. (setq context
  19246. (org-element-lineage
  19247. context '(radio-target paragraph verse-block table-cell)))))
  19248. ;; For convenience: at the first line of a paragraph on the
  19249. ;; same line as an item, apply function on that item instead.
  19250. (when (eq type 'paragraph)
  19251. (let ((parent (org-element-property :parent context)))
  19252. (when (and (eq (org-element-type parent) 'item)
  19253. (= (line-beginning-position)
  19254. (org-element-property :begin parent)))
  19255. (setq context parent type 'item))))
  19256. ;; Act according to type of element or object at point.
  19257. (cl-case type
  19258. (clock (org-clock-update-time-maybe))
  19259. (dynamic-block
  19260. (save-excursion
  19261. (goto-char (org-element-property :post-affiliated context))
  19262. (org-update-dblock)))
  19263. (footnote-definition
  19264. (goto-char (org-element-property :post-affiliated context))
  19265. (call-interactively 'org-footnote-action))
  19266. (footnote-reference (call-interactively 'org-footnote-action))
  19267. ((headline inlinetask)
  19268. (save-excursion (goto-char (org-element-property :begin context))
  19269. (call-interactively 'org-set-tags)))
  19270. (item
  19271. ;; At an item: a double C-u set checkbox to "[-]"
  19272. ;; unconditionally, whereas a single one will toggle its
  19273. ;; presence. Without a universal argument, if the item
  19274. ;; has a checkbox, toggle it. Otherwise repair the list.
  19275. (let* ((box (org-element-property :checkbox context))
  19276. (struct (org-element-property :structure context))
  19277. (old-struct (copy-tree struct))
  19278. (parents (org-list-parents-alist struct))
  19279. (prevs (org-list-prevs-alist struct))
  19280. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19281. (org-list-set-checkbox
  19282. (org-element-property :begin context) struct
  19283. (cond ((equal arg '(16)) "[-]")
  19284. ((and (not box) (equal arg '(4))) "[ ]")
  19285. ((or (not box) (equal arg '(4))) nil)
  19286. ((eq box 'on) "[ ]")
  19287. (t "[X]")))
  19288. ;; Mimic `org-list-write-struct' but with grabbing
  19289. ;; a return value from `org-list-struct-fix-box'.
  19290. (org-list-struct-fix-ind struct parents 2)
  19291. (org-list-struct-fix-item-end struct)
  19292. (org-list-struct-fix-bul struct prevs)
  19293. (org-list-struct-fix-ind struct parents)
  19294. (let ((block-item
  19295. (org-list-struct-fix-box struct parents prevs orderedp)))
  19296. (if (and box (equal struct old-struct))
  19297. (if (equal arg '(16))
  19298. (message "Checkboxes already reset")
  19299. (user-error "Cannot toggle this checkbox: %s"
  19300. (if (eq box 'on)
  19301. "all subitems checked"
  19302. "unchecked subitems")))
  19303. (org-list-struct-apply-struct struct old-struct)
  19304. (org-update-checkbox-count-maybe))
  19305. (when block-item
  19306. (message "Checkboxes were removed due to empty box at line %d"
  19307. (org-current-line block-item))))))
  19308. (keyword
  19309. (let ((org-inhibit-startup-visibility-stuff t)
  19310. (org-startup-align-all-tables nil))
  19311. (when (boundp 'org-table-coordinate-overlays)
  19312. (mapc #'delete-overlay org-table-coordinate-overlays)
  19313. (setq org-table-coordinate-overlays nil))
  19314. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19315. (message "Local setup has been refreshed"))
  19316. (plain-list
  19317. ;; At a plain list, with a double C-u argument, set
  19318. ;; checkboxes of each item to "[-]", whereas a single one
  19319. ;; will toggle their presence according to the state of the
  19320. ;; first item in the list. Without an argument, repair the
  19321. ;; list.
  19322. (let* ((begin (org-element-property :contents-begin context))
  19323. (beginm (move-marker (make-marker) begin))
  19324. (struct (org-element-property :structure context))
  19325. (old-struct (copy-tree struct))
  19326. (first-box (save-excursion
  19327. (goto-char begin)
  19328. (looking-at org-list-full-item-re)
  19329. (match-string-no-properties 3)))
  19330. (new-box (cond ((equal arg '(16)) "[-]")
  19331. ((equal arg '(4)) (unless first-box "[ ]"))
  19332. ((equal first-box "[X]") "[ ]")
  19333. (t "[X]"))))
  19334. (cond
  19335. (arg
  19336. (dolist (pos
  19337. (org-list-get-all-items
  19338. begin struct (org-list-prevs-alist struct)))
  19339. (org-list-set-checkbox pos struct new-box)))
  19340. ((and first-box (eq (point) begin))
  19341. ;; For convenience, when point is at bol on the first
  19342. ;; item of the list and no argument is provided, simply
  19343. ;; toggle checkbox of that item, if any.
  19344. (org-list-set-checkbox begin struct new-box)))
  19345. (org-list-write-struct
  19346. struct (org-list-parents-alist struct) old-struct)
  19347. (org-update-checkbox-count-maybe)
  19348. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19349. ((property-drawer node-property)
  19350. (call-interactively 'org-property-action))
  19351. ((radio-target target)
  19352. (call-interactively 'org-update-radio-target-regexp))
  19353. (statistics-cookie
  19354. (call-interactively 'org-update-statistics-cookies))
  19355. ((table table-cell table-row)
  19356. ;; At a table, recalculate every field and align it. Also
  19357. ;; send the table if necessary. If the table has
  19358. ;; a `table.el' type, just give up. At a table row or
  19359. ;; cell, maybe recalculate line but always align table.
  19360. (if (eq (org-element-property :type context) 'table.el)
  19361. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19362. Use \\[org-edit-special] to edit table.el tables"))
  19363. (let ((org-enable-table-editor t))
  19364. (if (or (eq type 'table)
  19365. ;; Check if point is at a TBLFM line.
  19366. (and (eq type 'table-row)
  19367. (= (point) (org-element-property :end context))))
  19368. (save-excursion
  19369. (if (org-at-TBLFM-p)
  19370. (progn (require 'org-table)
  19371. (org-table-calc-current-TBLFM))
  19372. (goto-char (org-element-property :contents-begin context))
  19373. (org-call-with-arg 'org-table-recalculate (or arg t))
  19374. (orgtbl-send-table 'maybe)))
  19375. (org-table-maybe-eval-formula)
  19376. (cond (arg (call-interactively 'org-table-recalculate))
  19377. ((org-table-maybe-recalculate-line))
  19378. (t (org-table-align)))))))
  19379. (timestamp (org-timestamp-change 0 'day))
  19380. (otherwise
  19381. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19382. (user-error
  19383. "C-c C-c can do nothing useful at this location")))))))))
  19384. (defun org-mode-restart ()
  19385. (interactive)
  19386. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19387. (funcall major-mode)
  19388. (hack-local-variables)
  19389. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19390. (org-indent-mode -1)))
  19391. (message "%s restarted" major-mode))
  19392. (defun org-kill-note-or-show-branches ()
  19393. "If this is a Note buffer, abort storing the note. Else call `show-branches'."
  19394. (interactive)
  19395. (if (not org-finish-function)
  19396. (progn
  19397. (outline-hide-subtree)
  19398. (call-interactively 'outline-show-branches))
  19399. (let ((org-note-abort t))
  19400. (funcall org-finish-function))))
  19401. (defun org-delete-indentation (&optional ARG)
  19402. "Join current line to previous and fix whitespace at join.
  19403. If previous line is a headline add to headline title. Otherwise
  19404. the function calls `delete-indentation'.
  19405. With argument, join this line to following line."
  19406. (interactive "*P")
  19407. (if (save-excursion
  19408. (if ARG (beginning-of-line)
  19409. (forward-line -1))
  19410. (looking-at org-complex-heading-regexp))
  19411. ;; At headline.
  19412. (let ((tags-column (when (match-beginning 5)
  19413. (save-excursion (goto-char (match-beginning 5))
  19414. (current-column))))
  19415. (string (concat " " (progn (when ARG (forward-line 1))
  19416. (org-trim (delete-and-extract-region
  19417. (line-beginning-position)
  19418. (line-end-position)))))))
  19419. (unless (bobp) (delete-region (point) (1- (point))))
  19420. (goto-char (or (match-end 4)
  19421. (match-beginning 5)
  19422. (match-end 0)))
  19423. (skip-chars-backward " \t")
  19424. (save-excursion (insert string))
  19425. ;; Adjust alignment of tags.
  19426. (when tags-column
  19427. (org-align-tags-here (if org-auto-align-tags
  19428. org-tags-column
  19429. tags-column))))
  19430. (delete-indentation ARG)))
  19431. (defun org-open-line (n)
  19432. "Insert a new row in tables, call `open-line' elsewhere.
  19433. If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
  19434. (interactive "*p")
  19435. (cond
  19436. ((not org-special-ctrl-o)
  19437. (open-line n))
  19438. ((org-at-table-p)
  19439. (org-table-insert-row))
  19440. (t
  19441. (open-line n))))
  19442. (defun org-return (&optional indent)
  19443. "Goto next table row or insert a newline.
  19444. Calls `org-table-next-row' or `newline', depending on context.
  19445. When optional INDENT argument is non-nil, call
  19446. `newline-and-indent' instead of `newline'.
  19447. When `org-return-follows-link' is non-nil and point is on
  19448. a timestamp or a link, call `org-open-at-point'. However, it
  19449. will not happen if point is in a table or on a \"dead\"
  19450. object (e.g., within a comment). In these case, you need to use
  19451. `org-open-at-point' directly."
  19452. (interactive)
  19453. (let ((context (if org-return-follows-link (org-element-context)
  19454. (org-element-at-point))))
  19455. (cond
  19456. ;; In a table, call `org-table-next-row'.
  19457. ((or (and (eq (org-element-type context) 'table)
  19458. (>= (point) (org-element-property :contents-begin context))
  19459. (< (point) (org-element-property :contents-end context)))
  19460. (org-element-lineage context '(table-row table-cell) t))
  19461. (org-table-justify-field-maybe)
  19462. (call-interactively #'org-table-next-row))
  19463. ;; On a link or a timestamp, call `org-open-at-point' if
  19464. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19465. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19466. ((and org-return-follows-link
  19467. (or (org-in-regexp org-ts-regexp-both nil t)
  19468. (org-in-regexp org-tsr-regexp-both nil t)
  19469. (org-in-regexp org-any-link-re nil t)))
  19470. (call-interactively #'org-open-at-point))
  19471. ;; Insert newline in heading, but preserve tags.
  19472. ((and (not (bolp))
  19473. (save-excursion (beginning-of-line)
  19474. (looking-at org-complex-heading-regexp)))
  19475. ;; At headline. Split line. However, if point is on keyword,
  19476. ;; priority cookie or tags, do not break any of them: add
  19477. ;; a newline after the headline instead.
  19478. (let ((tags-column (and (match-beginning 5)
  19479. (save-excursion (goto-char (match-beginning 5))
  19480. (current-column))))
  19481. (string
  19482. (when (and (match-end 4)
  19483. (>= (point)
  19484. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19485. (<= (point) (match-end 4)))
  19486. (delete-and-extract-region (point) (match-end 4)))))
  19487. (when (and tags-column string) ; Adjust tag alignment.
  19488. (org-align-tags-here
  19489. (if org-auto-align-tags org-tags-column tags-column)))
  19490. (end-of-line)
  19491. (org-show-entry)
  19492. (if indent (newline-and-indent) (newline))
  19493. (when string (save-excursion (insert (org-trim string))))))
  19494. ;; In a list, make sure indenting keeps trailing text within.
  19495. ((and indent
  19496. (not (eolp))
  19497. (org-element-lineage context '(item)))
  19498. (let ((trailing-data
  19499. (delete-and-extract-region (point) (line-end-position))))
  19500. (newline-and-indent)
  19501. (save-excursion (insert trailing-data))))
  19502. (t (if indent (newline-and-indent) (newline))))))
  19503. (defun org-return-indent ()
  19504. "Goto next table row or insert a newline and indent.
  19505. Calls `org-table-next-row' or `newline-and-indent', depending on
  19506. context. See the individual commands for more information."
  19507. (interactive)
  19508. (org-return t))
  19509. (defun org-ctrl-c-star ()
  19510. "Compute table, or change heading status of lines.
  19511. Calls `org-table-recalculate' or `org-toggle-heading',
  19512. depending on context."
  19513. (interactive)
  19514. (cond
  19515. ((org-at-table-p)
  19516. (call-interactively 'org-table-recalculate))
  19517. (t
  19518. ;; Convert all lines in region to list items
  19519. (call-interactively 'org-toggle-heading))))
  19520. (defun org-ctrl-c-minus ()
  19521. "Insert separator line in table or modify bullet status of line.
  19522. Also turns a plain line or a region of lines into list items.
  19523. Calls `org-table-insert-hline', `org-toggle-item', or
  19524. `org-cycle-list-bullet', depending on context."
  19525. (interactive)
  19526. (cond
  19527. ((org-at-table-p)
  19528. (call-interactively 'org-table-insert-hline))
  19529. ((org-region-active-p)
  19530. (call-interactively 'org-toggle-item))
  19531. ((org-in-item-p)
  19532. (call-interactively 'org-cycle-list-bullet))
  19533. (t
  19534. (call-interactively 'org-toggle-item))))
  19535. (defun org-toggle-item (arg)
  19536. "Convert headings or normal lines to items, items to normal lines.
  19537. If there is no active region, only the current line is considered.
  19538. If the first non blank line in the region is a headline, convert
  19539. all headlines to items, shifting text accordingly.
  19540. If it is an item, convert all items to normal lines.
  19541. If it is normal text, change region into a list of items.
  19542. With a prefix argument ARG, change the region in a single item."
  19543. (interactive "P")
  19544. (let ((shift-text
  19545. (function
  19546. ;; Shift text in current section to IND, from point to END.
  19547. ;; The function leaves point to END line.
  19548. (lambda (ind end)
  19549. (let ((min-i 1000) (end (copy-marker end)))
  19550. ;; First determine the minimum indentation (MIN-I) of
  19551. ;; the text.
  19552. (save-excursion
  19553. (catch 'exit
  19554. (while (< (point) end)
  19555. (let ((i (org-get-indentation)))
  19556. (cond
  19557. ;; Skip blank lines and inline tasks.
  19558. ((looking-at "^[ \t]*$"))
  19559. ((looking-at org-outline-regexp-bol))
  19560. ;; We can't find less than 0 indentation.
  19561. ((zerop i) (throw 'exit (setq min-i 0)))
  19562. ((< i min-i) (setq min-i i))))
  19563. (forward-line))))
  19564. ;; Then indent each line so that a line indented to
  19565. ;; MIN-I becomes indented to IND. Ignore blank lines
  19566. ;; and inline tasks in the process.
  19567. (let ((delta (- ind min-i)))
  19568. (while (< (point) end)
  19569. (unless (or (looking-at "^[ \t]*$")
  19570. (looking-at org-outline-regexp-bol))
  19571. (indent-line-to (+ (org-get-indentation) delta)))
  19572. (forward-line)))))))
  19573. (skip-blanks
  19574. (function
  19575. ;; Return beginning of first non-blank line, starting from
  19576. ;; line at POS.
  19577. (lambda (pos)
  19578. (save-excursion
  19579. (goto-char pos)
  19580. (skip-chars-forward " \r\t\n")
  19581. (point-at-bol)))))
  19582. beg end)
  19583. ;; Determine boundaries of changes.
  19584. (if (org-region-active-p)
  19585. (setq beg (funcall skip-blanks (region-beginning))
  19586. end (copy-marker (region-end)))
  19587. (setq beg (funcall skip-blanks (point-at-bol))
  19588. end (copy-marker (point-at-eol))))
  19589. ;; Depending on the starting line, choose an action on the text
  19590. ;; between BEG and END.
  19591. (org-with-limited-levels
  19592. (save-excursion
  19593. (goto-char beg)
  19594. (cond
  19595. ;; Case 1. Start at an item: de-itemize. Note that it only
  19596. ;; happens when a region is active: `org-ctrl-c-minus'
  19597. ;; would call `org-cycle-list-bullet' otherwise.
  19598. ((org-at-item-p)
  19599. (while (< (point) end)
  19600. (when (org-at-item-p)
  19601. (skip-chars-forward " \t")
  19602. (delete-region (point) (match-end 0)))
  19603. (forward-line)))
  19604. ;; Case 2. Start at an heading: convert to items.
  19605. ((org-at-heading-p)
  19606. (let* ((bul (org-list-bullet-string "-"))
  19607. (bul-len (length bul))
  19608. (done (org-entry-is-done-p))
  19609. (todo (org-entry-is-todo-p))
  19610. ;; Indentation of the first heading. It should be
  19611. ;; relative to the indentation of its parent, if any.
  19612. (start-ind (save-excursion
  19613. (cond
  19614. ((not org-adapt-indentation) 0)
  19615. ((not (outline-previous-heading)) 0)
  19616. (t (length (match-string 0))))))
  19617. ;; Level of first heading. Further headings will be
  19618. ;; compared to it to determine hierarchy in the list.
  19619. (ref-level (org-reduced-level (org-outline-level))))
  19620. (when (or done todo) (org-todo ""))
  19621. (while (< (point) end)
  19622. (let* ((level (org-reduced-level (org-outline-level)))
  19623. (delta (max 0 (- level ref-level))))
  19624. ;; If current headline is less indented than the first
  19625. ;; one, set it as reference, in order to preserve
  19626. ;; subtrees.
  19627. (when (< level ref-level) (setq ref-level level))
  19628. (replace-match bul t t)
  19629. (indent-line-to (+ start-ind (* delta bul-len)))
  19630. (when (or done todo)
  19631. (let* ((struct (org-list-struct))
  19632. (old (copy-tree struct)))
  19633. (org-list-set-checkbox (line-beginning-position)
  19634. struct
  19635. (if done "[X]" "[ ]"))
  19636. (org-list-write-struct struct
  19637. (org-list-parents-alist struct)
  19638. old)))
  19639. ;; Ensure all text down to END (or SECTION-END) belongs
  19640. ;; to the newly created item.
  19641. (let ((section-end (save-excursion
  19642. (or (outline-next-heading) (point)))))
  19643. (forward-line)
  19644. (funcall shift-text
  19645. (+ start-ind (* (1+ delta) bul-len))
  19646. (min end section-end)))))))
  19647. ;; Case 3. Normal line with ARG: make the first line of region
  19648. ;; an item, and shift indentation of others lines to
  19649. ;; set them as item's body.
  19650. (arg (let* ((bul (org-list-bullet-string "-"))
  19651. (bul-len (length bul))
  19652. (ref-ind (org-get-indentation)))
  19653. (skip-chars-forward " \t")
  19654. (insert bul)
  19655. (forward-line)
  19656. (while (< (point) end)
  19657. ;; Ensure that lines less indented than first one
  19658. ;; still get included in item body.
  19659. (funcall shift-text
  19660. (+ ref-ind bul-len)
  19661. (min end (save-excursion (or (outline-next-heading)
  19662. (point)))))
  19663. (forward-line))))
  19664. ;; Case 4. Normal line without ARG: turn each non-item line
  19665. ;; into an item.
  19666. (t
  19667. (while (< (point) end)
  19668. (unless (or (org-at-heading-p) (org-at-item-p))
  19669. (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
  19670. (replace-match
  19671. (concat "\\1" (org-list-bullet-string "-") "\\2"))))
  19672. (forward-line))))))))
  19673. (defun org-toggle-heading (&optional nstars)
  19674. "Convert headings to normal text, or items or text to headings.
  19675. If there is no active region, only convert the current line.
  19676. With a \\[universal-argument] prefix, convert the whole list at
  19677. point into heading.
  19678. In a region:
  19679. - If the first non blank line is a headline, remove the stars
  19680. from all headlines in the region.
  19681. - If it is a normal line, turn each and every normal line (i.e.,
  19682. not an heading or an item) in the region into headings. If you
  19683. want to convert only the first line of this region, use one
  19684. universal prefix argument.
  19685. - If it is a plain list item, turn all plain list items into headings.
  19686. When converting a line into a heading, the number of stars is chosen
  19687. such that the lines become children of the current entry. However,
  19688. when a numeric prefix argument is given, its value determines the
  19689. number of stars to add."
  19690. (interactive "P")
  19691. (let ((skip-blanks
  19692. (function
  19693. ;; Return beginning of first non-blank line, starting from
  19694. ;; line at POS.
  19695. (lambda (pos)
  19696. (save-excursion
  19697. (goto-char pos)
  19698. (while (org-at-comment-p) (forward-line))
  19699. (skip-chars-forward " \r\t\n")
  19700. (point-at-bol)))))
  19701. beg end toggled)
  19702. ;; Determine boundaries of changes. If a universal prefix has
  19703. ;; been given, put the list in a region. If region ends at a bol,
  19704. ;; do not consider the last line to be in the region.
  19705. (when (and current-prefix-arg (org-at-item-p))
  19706. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19707. (org-mark-element))
  19708. (if (org-region-active-p)
  19709. (setq beg (funcall skip-blanks (region-beginning))
  19710. end (copy-marker (save-excursion
  19711. (goto-char (region-end))
  19712. (if (bolp) (point) (point-at-eol)))))
  19713. (setq beg (funcall skip-blanks (point-at-bol))
  19714. end (copy-marker (point-at-eol))))
  19715. ;; Ensure inline tasks don't count as headings.
  19716. (org-with-limited-levels
  19717. (save-excursion
  19718. (goto-char beg)
  19719. (cond
  19720. ;; Case 1. Started at an heading: de-star headings.
  19721. ((org-at-heading-p)
  19722. (while (< (point) end)
  19723. (when (org-at-heading-p t)
  19724. (looking-at org-outline-regexp) (replace-match "")
  19725. (setq toggled t))
  19726. (forward-line)))
  19727. ;; Case 2. Started at an item: change items into headlines.
  19728. ;; One star will be added by `org-list-to-subtree'.
  19729. ((org-at-item-p)
  19730. (while (< (point) end)
  19731. (when (org-at-item-p)
  19732. ;; Pay attention to cases when region ends before list.
  19733. (let* ((struct (org-list-struct))
  19734. (list-end
  19735. (min (org-list-get-bottom-point struct) (1+ end))))
  19736. (save-restriction
  19737. (narrow-to-region (point) list-end)
  19738. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19739. (setq toggled t))
  19740. (forward-line)))
  19741. ;; Case 3. Started at normal text: make every line an heading,
  19742. ;; skipping headlines and items.
  19743. (t (let* ((stars
  19744. (make-string
  19745. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19746. (add-stars
  19747. (cond (nstars "") ; stars from prefix only
  19748. ((equal stars "") "*") ; before first heading
  19749. (org-odd-levels-only "**") ; inside heading, odd
  19750. (t "*"))) ; inside heading, oddeven
  19751. (rpl (concat stars add-stars " "))
  19752. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19753. (while (< (point) (if (equal nstars '(4)) lend end))
  19754. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19755. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19756. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19757. (forward-line)))))))
  19758. (unless toggled (message "Cannot toggle heading from here"))))
  19759. (defun org-meta-return (&optional _arg)
  19760. "Insert a new heading or wrap a region in a table.
  19761. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19762. on context. See the individual commands for more information."
  19763. (interactive)
  19764. (org-check-before-invisible-edit 'insert)
  19765. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19766. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19767. #'org-insert-heading))))
  19768. ;;; Menu entries
  19769. (defsubst org-in-subtree-not-table-p ()
  19770. "Are we in a subtree and not in a table?"
  19771. (and (not (org-before-first-heading-p))
  19772. (not (org-at-table-p))))
  19773. ;; Define the Org-mode menus
  19774. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19775. '("Tbl"
  19776. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19777. ["Next Field" org-cycle (org-at-table-p)]
  19778. ["Previous Field" org-shifttab (org-at-table-p)]
  19779. ["Next Row" org-return (org-at-table-p)]
  19780. "--"
  19781. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19782. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19783. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19784. "--"
  19785. ("Column"
  19786. ["Move Column Left" org-metaleft (org-at-table-p)]
  19787. ["Move Column Right" org-metaright (org-at-table-p)]
  19788. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19789. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19790. ("Row"
  19791. ["Move Row Up" org-metaup (org-at-table-p)]
  19792. ["Move Row Down" org-metadown (org-at-table-p)]
  19793. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19794. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19795. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19796. "--"
  19797. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19798. ("Rectangle"
  19799. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19800. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19801. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19802. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19803. "--"
  19804. ("Calculate"
  19805. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19806. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19807. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19808. "--"
  19809. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19810. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19811. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19812. "--"
  19813. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19814. "--"
  19815. ["Sum Column/Rectangle" org-table-sum
  19816. (or (org-at-table-p) (org-region-active-p))]
  19817. ["Which Column?" org-table-current-column (org-at-table-p)])
  19818. ["Debug Formulas"
  19819. org-table-toggle-formula-debugger
  19820. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19821. ["Show Col/Row Numbers"
  19822. org-table-toggle-coordinate-overlays
  19823. :style toggle
  19824. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19825. "--"
  19826. ["Create" org-table-create (and (not (org-at-table-p))
  19827. org-enable-table-editor)]
  19828. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19829. ["Import from File" org-table-import (not (org-at-table-p))]
  19830. ["Export to File" org-table-export (org-at-table-p)]
  19831. "--"
  19832. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19833. "--"
  19834. ("Plot"
  19835. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19836. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19837. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19838. '("Org"
  19839. ("Show/Hide"
  19840. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19841. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19842. ["Sparse Tree..." org-sparse-tree t]
  19843. ["Reveal Context" org-reveal t]
  19844. ["Show All" outline-show-all t]
  19845. "--"
  19846. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19847. "--"
  19848. ["New Heading" org-insert-heading t]
  19849. ("Navigate Headings"
  19850. ["Up" outline-up-heading t]
  19851. ["Next" outline-next-visible-heading t]
  19852. ["Previous" outline-previous-visible-heading t]
  19853. ["Next Same Level" outline-forward-same-level t]
  19854. ["Previous Same Level" outline-backward-same-level t]
  19855. "--"
  19856. ["Jump" org-goto t])
  19857. ("Edit Structure"
  19858. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19859. "--"
  19860. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19861. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19862. "--"
  19863. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19864. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19865. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19866. "--"
  19867. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19868. "--"
  19869. ["Copy visible text" org-copy-visible t]
  19870. "--"
  19871. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19872. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19873. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19874. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19875. "--"
  19876. ["Sort Region/Children" org-sort t]
  19877. "--"
  19878. ["Convert to odd levels" org-convert-to-odd-levels t]
  19879. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19880. ("Editing"
  19881. ["Emphasis..." org-emphasize t]
  19882. ["Edit Source Example" org-edit-special t]
  19883. "--"
  19884. ["Footnote new/jump" org-footnote-action t]
  19885. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19886. ("Archive"
  19887. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19888. "--"
  19889. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19890. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19891. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19892. )
  19893. "--"
  19894. ("Hyperlinks"
  19895. ["Store Link (Global)" org-store-link t]
  19896. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19897. ["Insert Link" org-insert-link t]
  19898. ["Follow Link" org-open-at-point t]
  19899. "--"
  19900. ["Next link" org-next-link t]
  19901. ["Previous link" org-previous-link t]
  19902. "--"
  19903. ["Descriptive Links"
  19904. org-toggle-link-display
  19905. :style radio
  19906. :selected org-descriptive-links
  19907. ]
  19908. ["Literal Links"
  19909. org-toggle-link-display
  19910. :style radio
  19911. :selected (not org-descriptive-links)])
  19912. "--"
  19913. ("TODO Lists"
  19914. ["TODO/DONE/-" org-todo t]
  19915. ("Select keyword"
  19916. ["Next keyword" org-shiftright (org-at-heading-p)]
  19917. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19918. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19919. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19920. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19921. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19922. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19923. "--"
  19924. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19925. :selected org-enforce-todo-dependencies :style toggle :active t]
  19926. "Settings for tree at point"
  19927. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19928. :selected (org-entry-get nil "ORDERED")
  19929. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19930. ["Do Children parallel" org-toggle-ordered-property :style radio
  19931. :selected (not (org-entry-get nil "ORDERED"))
  19932. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19933. "--"
  19934. ["Set Priority" org-priority t]
  19935. ["Priority Up" org-shiftup t]
  19936. ["Priority Down" org-shiftdown t]
  19937. "--"
  19938. ["Get news from all feeds" org-feed-update-all t]
  19939. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19940. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19941. ("TAGS and Properties"
  19942. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19943. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19944. "--"
  19945. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19946. ["Column view of properties" org-columns t]
  19947. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19948. ("Dates and Scheduling"
  19949. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19950. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19951. ("Change Date"
  19952. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19953. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19954. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19955. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19956. ["Compute Time Range" org-evaluate-time-range t]
  19957. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19958. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19959. "--"
  19960. ["Custom time format" org-toggle-time-stamp-overlays
  19961. :style radio :selected org-display-custom-times]
  19962. "--"
  19963. ["Goto Calendar" org-goto-calendar t]
  19964. ["Date from Calendar" org-date-from-calendar t]
  19965. "--"
  19966. ["Start/Restart Timer" org-timer-start t]
  19967. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19968. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19969. ["Insert Timer String" org-timer t]
  19970. ["Insert Timer Item" org-timer-item t])
  19971. ("Logging work"
  19972. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19973. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19974. ["Clock out" org-clock-out t]
  19975. ["Clock cancel" org-clock-cancel t]
  19976. "--"
  19977. ["Mark as default task" org-clock-mark-default-task t]
  19978. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19979. ["Goto running clock" org-clock-goto t]
  19980. "--"
  19981. ["Display times" org-clock-display t]
  19982. ["Create clock table" org-clock-report t]
  19983. "--"
  19984. ["Record DONE time"
  19985. (progn (setq org-log-done (not org-log-done))
  19986. (message "Switching to %s will %s record a timestamp"
  19987. (car org-done-keywords)
  19988. (if org-log-done "automatically" "not")))
  19989. :style toggle :selected org-log-done])
  19990. "--"
  19991. ["Agenda Command..." org-agenda t]
  19992. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19993. ("File List for Agenda")
  19994. ("Special views current file"
  19995. ["TODO Tree" org-show-todo-tree t]
  19996. ["Check Deadlines" org-check-deadlines t]
  19997. ["Timeline" org-timeline t]
  19998. ["Tags/Property tree" org-match-sparse-tree t])
  19999. "--"
  20000. ["Export/Publish..." org-export-dispatch t]
  20001. ("LaTeX"
  20002. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  20003. :selected org-cdlatex-mode]
  20004. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  20005. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  20006. ["Modify math symbol" org-cdlatex-math-modify
  20007. (org-inside-LaTeX-fragment-p)]
  20008. ["Insert citation" org-reftex-citation t])
  20009. "--"
  20010. ("MobileOrg"
  20011. ["Push Files and Views" org-mobile-push t]
  20012. ["Get Captured and Flagged" org-mobile-pull t]
  20013. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  20014. "--"
  20015. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  20016. "--"
  20017. ("Documentation"
  20018. ["Show Version" org-version t]
  20019. ["Info Documentation" org-info t])
  20020. ("Customize"
  20021. ["Browse Org Group" org-customize t]
  20022. "--"
  20023. ["Expand This Menu" org-create-customize-menu
  20024. (fboundp 'customize-menu-create)])
  20025. ["Send bug report" org-submit-bug-report t]
  20026. "--"
  20027. ("Refresh/Reload"
  20028. ["Refresh setup current buffer" org-mode-restart t]
  20029. ["Reload Org (after update)" org-reload t]
  20030. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20031. ))
  20032. (defun org-info (&optional node)
  20033. "Read documentation for Org-mode in the info system.
  20034. With optional NODE, go directly to that node."
  20035. (interactive)
  20036. (info (format "(org)%s" (or node ""))))
  20037. ;;;###autoload
  20038. (defun org-submit-bug-report ()
  20039. "Submit a bug report on Org-mode via mail.
  20040. Don't hesitate to report any problems or inaccurate documentation.
  20041. If you don't have setup sending mail from (X)Emacs, please copy the
  20042. output buffer into your mail program, as it gives us important
  20043. information about your Org-mode version and configuration."
  20044. (interactive)
  20045. (require 'reporter)
  20046. (defvar reporter-prompt-for-summary-p)
  20047. (org-load-modules-maybe)
  20048. (org-require-autoloaded-modules)
  20049. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20050. (reporter-submit-bug-report
  20051. "emacs-orgmode@gnu.org"
  20052. (org-version nil 'full)
  20053. (let (list)
  20054. (save-window-excursion
  20055. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20056. (delete-other-windows)
  20057. (erase-buffer)
  20058. (insert "You are about to submit a bug report to the Org-mode mailing list.
  20059. We would like to add your full Org-mode and Outline configuration to the
  20060. bug report. This greatly simplifies the work of the maintainer and
  20061. other experts on the mailing list.
  20062. HOWEVER, some variables you have customized may contain private
  20063. information. The names of customers, colleagues, or friends, might
  20064. appear in the form of file names, tags, todo states, or search strings.
  20065. If you answer yes to the prompt, you might want to check and remove
  20066. such private information before sending the email.")
  20067. (add-text-properties (point-min) (point-max) '(face org-warning))
  20068. (when (yes-or-no-p "Include your Org-mode configuration ")
  20069. (mapatoms
  20070. (lambda (v)
  20071. (and (boundp v)
  20072. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20073. (or (and (symbol-value v)
  20074. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20075. (and
  20076. (get v 'custom-type) (get v 'standard-value)
  20077. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20078. (push v list)))))
  20079. (kill-buffer (get-buffer "*Warn about privacy*"))
  20080. list))
  20081. nil nil
  20082. "Remember to cover the basics, that is, what you expected to happen and
  20083. what in fact did happen. You don't know how to make a good report? See
  20084. http://orgmode.org/manual/Feedback.html#Feedback
  20085. Your bug report will be posted to the Org-mode mailing list.
  20086. ------------------------------------------------------------------------")
  20087. (save-excursion
  20088. (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20089. (replace-match "\\1Bug: \\3 [\\2]")))))
  20090. (defun org-install-agenda-files-menu ()
  20091. (let ((bl (buffer-list)))
  20092. (save-excursion
  20093. (while bl
  20094. (set-buffer (pop bl))
  20095. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20096. (when (derived-mode-p 'org-mode)
  20097. (easy-menu-change
  20098. '("Org") "File List for Agenda"
  20099. (append
  20100. (list
  20101. ["Edit File List" (org-edit-agenda-file-list) t]
  20102. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20103. ["Remove Current File from List" org-remove-file t]
  20104. ["Cycle through agenda files" org-cycle-agenda-files t]
  20105. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20106. "--")
  20107. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20108. ;;;; Documentation
  20109. (defun org-require-autoloaded-modules ()
  20110. (interactive)
  20111. (mapc #'require
  20112. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20113. org-table org-timer)))
  20114. ;;;###autoload
  20115. (defun org-reload (&optional uncompiled)
  20116. "Reload all org lisp files.
  20117. With prefix arg UNCOMPILED, load the uncompiled versions."
  20118. (interactive "P")
  20119. (require 'loadhist)
  20120. (let* ((org-dir (org-find-library-dir "org"))
  20121. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20122. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20123. (remove-re (format "\\`%s\\'"
  20124. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20125. (feats (delete-dups
  20126. (mapcar 'file-name-sans-extension
  20127. (mapcar 'file-name-nondirectory
  20128. (delq nil
  20129. (mapcar 'feature-file
  20130. features))))))
  20131. (lfeat (append
  20132. (sort
  20133. (setq feats
  20134. (delq nil (mapcar
  20135. (lambda (f)
  20136. (if (and (string-match feature-re f)
  20137. (not (string-match remove-re f)))
  20138. f nil))
  20139. feats)))
  20140. 'string-lessp)
  20141. (list "org-version" "org")))
  20142. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20143. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20144. load-uncore load-misses)
  20145. (setq load-misses
  20146. (delq 't
  20147. (mapcar (lambda (f)
  20148. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20149. (and (string= org-dir contrib-dir)
  20150. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20151. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20152. (add-to-list 'load-uncore f 'append)
  20153. 't)
  20154. f))
  20155. lfeat)))
  20156. (when load-uncore
  20157. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20158. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20159. (if load-misses
  20160. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20161. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20162. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20163. ;;;###autoload
  20164. (defun org-customize ()
  20165. "Call the customize function with org as argument."
  20166. (interactive)
  20167. (org-load-modules-maybe)
  20168. (org-require-autoloaded-modules)
  20169. (customize-browse 'org))
  20170. (defun org-create-customize-menu ()
  20171. "Create a full customization menu for Org-mode, insert it into the menu."
  20172. (interactive)
  20173. (org-load-modules-maybe)
  20174. (org-require-autoloaded-modules)
  20175. (if (fboundp 'customize-menu-create)
  20176. (progn
  20177. (easy-menu-change
  20178. '("Org") "Customize"
  20179. `(["Browse Org group" org-customize t]
  20180. "--"
  20181. ,(customize-menu-create 'org)
  20182. ["Set" Custom-set t]
  20183. ["Save" Custom-save t]
  20184. ["Reset to Current" Custom-reset-current t]
  20185. ["Reset to Saved" Custom-reset-saved t]
  20186. ["Reset to Standard Settings" Custom-reset-standard t]))
  20187. (message "\"Org\"-menu now contains full customization menu"))
  20188. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20189. ;;;; Miscellaneous stuff
  20190. ;;; Generally useful functions
  20191. (defun org-get-at-eol (property n)
  20192. "Get text property PROPERTY at the end of line less N characters."
  20193. (get-text-property (- (point-at-eol) n) property))
  20194. (defun org-find-text-property-in-string (prop s)
  20195. "Return the first non-nil value of property PROP in string S."
  20196. (or (get-text-property 0 prop s)
  20197. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20198. prop s)))
  20199. (defun org-display-warning (message) ;; Copied from Emacs-Muse
  20200. "Display the given MESSAGE as a warning."
  20201. (if (fboundp 'display-warning)
  20202. (display-warning 'org message :warning)
  20203. (let ((buf (get-buffer-create "*Org warnings*")))
  20204. (with-current-buffer buf
  20205. (goto-char (point-max))
  20206. (insert "Warning (Org): " message)
  20207. (unless (bolp)
  20208. (newline)))
  20209. (display-buffer buf)
  20210. (sit-for 0))))
  20211. (defun org-eval (form)
  20212. "Eval FORM and return result."
  20213. (condition-case error
  20214. (eval form)
  20215. (error (format "%%![Error: %s]" error))))
  20216. (defun org-in-clocktable-p ()
  20217. "Check if the cursor is in a clocktable."
  20218. (let ((pos (point)) start)
  20219. (save-excursion
  20220. (end-of-line 1)
  20221. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20222. (setq start (match-beginning 0))
  20223. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20224. (>= (match-end 0) pos)
  20225. start))))
  20226. (defun org-in-verbatim-emphasis ()
  20227. (save-match-data
  20228. (and (org-in-regexp org-emph-re 2)
  20229. (>= (point) (match-beginning 3))
  20230. (<= (point) (match-end 4))
  20231. (member (match-string 3) '("=" "~")))))
  20232. (defun org-overlay-display (ovl text &optional face evap)
  20233. "Make overlay OVL display TEXT with face FACE."
  20234. (overlay-put ovl 'display text)
  20235. (if face (overlay-put ovl 'face face))
  20236. (if evap (overlay-put ovl 'evaporate t)))
  20237. (defun org-overlay-before-string (ovl text &optional face evap)
  20238. "Make overlay OVL display TEXT with face FACE."
  20239. (if face (org-add-props text nil 'face face))
  20240. (overlay-put ovl 'before-string text)
  20241. (if evap (overlay-put ovl 'evaporate t)))
  20242. (defun org-find-overlays (prop &optional pos delete)
  20243. "Find all overlays specifying PROP at POS or point.
  20244. If DELETE is non-nil, delete all those overlays."
  20245. (let (found)
  20246. (dolist (ov (overlays-at (or pos (point))) found)
  20247. (cond ((not (overlay-get ov prop)))
  20248. (delete (delete-overlay ov))
  20249. (t (push ov found))))))
  20250. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20251. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20252. (if (and marker (marker-buffer marker)
  20253. (buffer-live-p (marker-buffer marker)))
  20254. (progn
  20255. (pop-to-buffer-same-window (marker-buffer marker))
  20256. (when (or (> marker (point-max)) (< marker (point-min)))
  20257. (widen))
  20258. (goto-char marker)
  20259. (org-show-context 'org-goto))
  20260. (if bookmark
  20261. (bookmark-jump bookmark)
  20262. (error "Cannot find location"))))
  20263. (defun org-quote-csv-field (s)
  20264. "Quote field for inclusion in CSV material."
  20265. (if (string-match "[\",]" s)
  20266. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20267. s))
  20268. (defun org-force-self-insert (N)
  20269. "Needed to enforce self-insert under remapping."
  20270. (interactive "p")
  20271. (self-insert-command N))
  20272. (defun org-string-width (s)
  20273. "Compute width of string, ignoring invisible characters.
  20274. This ignores character with invisibility property `org-link', and also
  20275. characters with property `org-cwidth', because these will become invisible
  20276. upon the next fontification round."
  20277. (let (b l)
  20278. (when (or (eq t buffer-invisibility-spec)
  20279. (assq 'org-link buffer-invisibility-spec))
  20280. (while (setq b (text-property-any 0 (length s)
  20281. 'invisible 'org-link s))
  20282. (setq s (concat (substring s 0 b)
  20283. (substring s (or (next-single-property-change
  20284. b 'invisible s)
  20285. (length s)))))))
  20286. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20287. (setq s (concat (substring s 0 b)
  20288. (substring s (or (next-single-property-change
  20289. b 'org-cwidth s)
  20290. (length s))))))
  20291. (setq l (string-width s) b -1)
  20292. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20293. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20294. l))
  20295. (defun org-shorten-string (s maxlength)
  20296. "Shorten string S so tht it is no longer than MAXLENGTH characters.
  20297. If the string is shorter or has length MAXLENGTH, just return the
  20298. original string. If it is longer, the functions finds a space in the
  20299. string, breaks this string off at that locations and adds three dots
  20300. as ellipsis. Including the ellipsis, the string will not be longer
  20301. than MAXLENGTH. If finding a good breaking point in the string does
  20302. not work, the string is just chopped off in the middle of a word
  20303. if necessary."
  20304. (if (<= (length s) maxlength)
  20305. s
  20306. (let* ((n (max (- maxlength 4) 1))
  20307. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20308. (if (string-match re s)
  20309. (concat (match-string 1 s) "...")
  20310. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20311. (defun org-get-indentation (&optional line)
  20312. "Get the indentation of the current line, interpreting tabs.
  20313. When LINE is given, assume it represents a line and compute its indentation."
  20314. (if line
  20315. (when (string-match "^ *" (org-remove-tabs line))
  20316. (match-end 0))
  20317. (save-excursion
  20318. (beginning-of-line 1)
  20319. (skip-chars-forward " \t")
  20320. (current-column))))
  20321. (defun org-get-string-indentation (s)
  20322. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20323. (let ((n -1) (i 0) (w tab-width) c)
  20324. (catch 'exit
  20325. (while (< (setq n (1+ n)) (length s))
  20326. (setq c (aref s n))
  20327. (cond ((= c ?\ ) (setq i (1+ i)))
  20328. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20329. (t (throw 'exit t)))))
  20330. i))
  20331. (defun org-remove-tabs (s &optional width)
  20332. "Replace tabulators in S with spaces.
  20333. Assumes that s is a single line, starting in column 0."
  20334. (setq width (or width tab-width))
  20335. (while (string-match "\t" s)
  20336. (setq s (replace-match
  20337. (make-string
  20338. (- (* width (/ (+ (match-beginning 0) width) width))
  20339. (match-beginning 0)) ?\ )
  20340. t t s)))
  20341. s)
  20342. (defun org-fix-indentation (line ind)
  20343. "Fix indentation in LINE.
  20344. IND is a cons cell with target and minimum indentation.
  20345. If the current indentation in LINE is smaller than the minimum,
  20346. leave it alone. If it is larger than ind, set it to the target."
  20347. (let* ((l (org-remove-tabs line))
  20348. (i (org-get-indentation l))
  20349. (i1 (car ind)) (i2 (cdr ind)))
  20350. (when (>= i i2) (setq l (substring line i2)))
  20351. (if (> i1 0)
  20352. (concat (make-string i1 ?\ ) l)
  20353. l)))
  20354. (defun org-remove-indentation (code &optional n)
  20355. "Remove maximum common indentation in string CODE and return it.
  20356. N may optionally be the number of columns to remove. Return CODE
  20357. as-is if removal failed."
  20358. (with-temp-buffer
  20359. (insert code)
  20360. (if (org-do-remove-indentation n) (buffer-string) code)))
  20361. (defun org-do-remove-indentation (&optional n)
  20362. "Remove the maximum common indentation from the buffer.
  20363. When optional argument N is a positive integer, remove exactly
  20364. that much characters from indentation, if possible. Return nil
  20365. if it fails."
  20366. (catch :exit
  20367. (goto-char (point-min))
  20368. ;; Find maximum common indentation, if not specified.
  20369. (let ((n (or n
  20370. (let ((min-ind (point-max)))
  20371. (save-excursion
  20372. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20373. (let ((ind (1- (current-column))))
  20374. (if (zerop ind) (throw :exit nil)
  20375. (setq min-ind (min min-ind ind))))))
  20376. min-ind))))
  20377. (if (zerop n) (throw :exit nil)
  20378. ;; Remove exactly N indentation, but give up if not possible.
  20379. (while (not (eobp))
  20380. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20381. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20382. ((< ind n) (throw :exit nil))
  20383. (t (indent-line-to (- ind n))))
  20384. (forward-line)))
  20385. ;; Signal success.
  20386. t))))
  20387. (defun org-fill-template (template alist)
  20388. "Find each %key of ALIST in TEMPLATE and replace it."
  20389. (let ((case-fold-search nil))
  20390. (dolist (entry (sort (copy-sequence alist)
  20391. (lambda (a b) (< (length (car a)) (length (car b))))))
  20392. (setq template
  20393. (replace-regexp-in-string
  20394. (concat "%" (regexp-quote (car entry)))
  20395. (or (cdr entry) "") template t t)))
  20396. template))
  20397. (defun org-base-buffer (buffer)
  20398. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20399. (if (not buffer)
  20400. buffer
  20401. (or (buffer-base-buffer buffer)
  20402. buffer)))
  20403. (defun org-wrap (string &optional width lines)
  20404. "Wrap string to either a number of lines, or a width in characters.
  20405. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20406. that costs. If there is a word longer than WIDTH, the text is actually
  20407. wrapped to the length of that word.
  20408. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20409. many lines, whatever width that takes.
  20410. The return value is a list of lines, without newlines at the end."
  20411. (let* ((words (org-split-string string "[ \t\n]+"))
  20412. (maxword (apply 'max (mapcar 'org-string-width words)))
  20413. w ll)
  20414. (cond (width
  20415. (org-do-wrap words (max maxword width)))
  20416. (lines
  20417. (setq w maxword)
  20418. (setq ll (org-do-wrap words maxword))
  20419. (if (<= (length ll) lines)
  20420. ll
  20421. (setq ll words)
  20422. (while (> (length ll) lines)
  20423. (setq w (1+ w))
  20424. (setq ll (org-do-wrap words w)))
  20425. ll))
  20426. (t (error "Cannot wrap this")))))
  20427. (defun org-do-wrap (words width)
  20428. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20429. (let (lines line)
  20430. (while words
  20431. (setq line (pop words))
  20432. (while (and words (< (+ (length line) (length (car words))) width))
  20433. (setq line (concat line " " (pop words))))
  20434. (setq lines (push line lines)))
  20435. (nreverse lines)))
  20436. (defun org-split-string (string &optional separators)
  20437. "Splits STRING into substrings at SEPARATORS.
  20438. SEPARATORS is a regular expression.
  20439. No empty strings are returned if there are matches at the beginning
  20440. and end of string."
  20441. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20442. (let ((start 0) notfirst list)
  20443. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20444. (if (and notfirst
  20445. (= start (match-beginning 0))
  20446. (< start (length string)))
  20447. (1+ start) start))
  20448. (< (match-beginning 0) (length string)))
  20449. (setq notfirst t)
  20450. (or (eq (match-beginning 0) 0)
  20451. (and (eq (match-beginning 0) (match-end 0))
  20452. (eq (match-beginning 0) start))
  20453. (push (substring string start (match-beginning 0)) list))
  20454. (setq start (match-end 0)))
  20455. (or (eq start (length string))
  20456. (push (substring string start) list))
  20457. (nreverse list)))
  20458. (defun org-quote-vert (s)
  20459. "Replace \"|\" with \"\\vert\"."
  20460. (while (string-match "|" s)
  20461. (setq s (replace-match "\\vert" t t s)))
  20462. s)
  20463. (defun org-uuidgen-p (s)
  20464. "Is S an ID created by UUIDGEN?"
  20465. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20466. (defun org-in-src-block-p (&optional inside)
  20467. "Whether point is in a code source block.
  20468. When INSIDE is non-nil, don't consider we are within a src block
  20469. when point is at #+BEGIN_SRC or #+END_SRC."
  20470. (let ((case-fold-search t))
  20471. (or (and (eq (get-char-property (point) 'src-block) t))
  20472. (and (not inside)
  20473. (save-match-data
  20474. (save-excursion
  20475. (beginning-of-line)
  20476. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20477. (defun org-context ()
  20478. "Return a list of contexts of the current cursor position.
  20479. If several contexts apply, all are returned.
  20480. Each context entry is a list with a symbol naming the context, and
  20481. two positions indicating start and end of the context. Possible
  20482. contexts are:
  20483. :headline anywhere in a headline
  20484. :headline-stars on the leading stars in a headline
  20485. :todo-keyword on a TODO keyword (including DONE) in a headline
  20486. :tags on the TAGS in a headline
  20487. :priority on the priority cookie in a headline
  20488. :item on the first line of a plain list item
  20489. :item-bullet on the bullet/number of a plain list item
  20490. :checkbox on the checkbox in a plain list item
  20491. :table in an org-mode table
  20492. :table-special on a special filed in a table
  20493. :table-table in a table.el table
  20494. :clocktable in a clocktable
  20495. :src-block in a source block
  20496. :link on a hyperlink
  20497. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20498. :target on a <<target>>
  20499. :radio-target on a <<<radio-target>>>
  20500. :latex-fragment on a LaTeX fragment
  20501. :latex-preview on a LaTeX fragment with overlaid preview image
  20502. This function expects the position to be visible because it uses font-lock
  20503. faces as a help to recognize the following contexts: :table-special, :link,
  20504. and :keyword."
  20505. (let* ((f (get-text-property (point) 'face))
  20506. (faces (if (listp f) f (list f)))
  20507. (case-fold-search t)
  20508. (p (point)) clist o)
  20509. ;; First the large context
  20510. (cond
  20511. ((org-at-heading-p t)
  20512. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20513. (when (progn
  20514. (beginning-of-line 1)
  20515. (looking-at org-todo-line-tags-regexp))
  20516. (push (org-point-in-group p 1 :headline-stars) clist)
  20517. (push (org-point-in-group p 2 :todo-keyword) clist)
  20518. (push (org-point-in-group p 4 :tags) clist))
  20519. (goto-char p)
  20520. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20521. (when (looking-at "\\[#[A-Z0-9]\\]")
  20522. (push (org-point-in-group p 0 :priority) clist)))
  20523. ((org-at-item-p)
  20524. (push (org-point-in-group p 2 :item-bullet) clist)
  20525. (push (list :item (point-at-bol)
  20526. (save-excursion (org-end-of-item) (point)))
  20527. clist)
  20528. (and (org-at-item-checkbox-p)
  20529. (push (org-point-in-group p 0 :checkbox) clist)))
  20530. ((org-at-table-p)
  20531. (push (list :table (org-table-begin) (org-table-end)) clist)
  20532. (when (memq 'org-formula faces)
  20533. (push (list :table-special
  20534. (previous-single-property-change p 'face)
  20535. (next-single-property-change p 'face)) clist)))
  20536. ((org-at-table-p 'any)
  20537. (push (list :table-table) clist)))
  20538. (goto-char p)
  20539. (let ((case-fold-search t))
  20540. ;; New the "medium" contexts: clocktables, source blocks
  20541. (cond ((org-in-clocktable-p)
  20542. (push (list :clocktable
  20543. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20544. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20545. (match-beginning 1))
  20546. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20547. (match-end 0))) clist))
  20548. ((org-in-src-block-p)
  20549. (push (list :src-block
  20550. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20551. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20552. (match-beginning 1))
  20553. (and (search-forward "#+END_SRC" nil t)
  20554. (match-beginning 0))) clist))))
  20555. (goto-char p)
  20556. ;; Now the small context
  20557. (cond
  20558. ((org-at-timestamp-p)
  20559. (push (org-point-in-group p 0 :timestamp) clist))
  20560. ((memq 'org-link faces)
  20561. (push (list :link
  20562. (previous-single-property-change p 'face)
  20563. (next-single-property-change p 'face)) clist))
  20564. ((memq 'org-special-keyword faces)
  20565. (push (list :keyword
  20566. (previous-single-property-change p 'face)
  20567. (next-single-property-change p 'face)) clist))
  20568. ((org-at-target-p)
  20569. (push (org-point-in-group p 0 :target) clist)
  20570. (goto-char (1- (match-beginning 0)))
  20571. (when (looking-at org-radio-target-regexp)
  20572. (push (org-point-in-group p 0 :radio-target) clist))
  20573. (goto-char p))
  20574. ((setq o (cl-some
  20575. (lambda (o)
  20576. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20577. o))
  20578. (overlays-at (point))))
  20579. (push (list :latex-fragment
  20580. (overlay-start o) (overlay-end o)) clist)
  20581. (push (list :latex-preview
  20582. (overlay-start o) (overlay-end o)) clist))
  20583. ((org-inside-LaTeX-fragment-p)
  20584. ;; FIXME: positions wrong.
  20585. (push (list :latex-fragment (point) (point)) clist)))
  20586. (setq clist (nreverse (delq nil clist)))
  20587. clist))
  20588. (defun org-in-regexp (regexp &optional nlines visually)
  20589. "Check if point is inside a match of REGEXP.
  20590. Normally only the current line is checked, but you can include
  20591. NLINES extra lines around point into the search. If VISUALLY is
  20592. set, require that the cursor is not after the match but really
  20593. on, so that the block visually is on the match.
  20594. Return nil or a cons cell (BEG . END) where BEG and END are,
  20595. respectively, the positions at the beginning and the end of the
  20596. match."
  20597. (catch :exit
  20598. (let ((pos (point))
  20599. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20600. (save-excursion
  20601. (beginning-of-line (- 1 (or nlines 0)))
  20602. (while (and (re-search-forward regexp eol t)
  20603. (<= (match-beginning 0) pos))
  20604. (let ((end (match-end 0)))
  20605. (when (or (> end pos) (and (= end pos) (not visually)))
  20606. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20607. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20608. "Non-nil when point is between matches of START-RE and END-RE.
  20609. Also return a non-nil value when point is on one of the matches.
  20610. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20611. buffer positions. Default values are the positions of headlines
  20612. surrounding the point.
  20613. The functions returns a cons cell whose car (resp. cdr) is the
  20614. position before START-RE (resp. after END-RE)."
  20615. (save-match-data
  20616. (let ((pos (point))
  20617. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20618. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20619. beg end)
  20620. (save-excursion
  20621. ;; Point is on a block when on START-RE or if START-RE can be
  20622. ;; found before it...
  20623. (and (or (org-in-regexp start-re)
  20624. (re-search-backward start-re limit-up t))
  20625. (setq beg (match-beginning 0))
  20626. ;; ... and END-RE after it...
  20627. (goto-char (match-end 0))
  20628. (re-search-forward end-re limit-down t)
  20629. (> (setq end (match-end 0)) pos)
  20630. ;; ... without another START-RE in-between.
  20631. (goto-char (match-beginning 0))
  20632. (not (re-search-backward start-re (1+ beg) t))
  20633. ;; Return value.
  20634. (cons beg end))))))
  20635. (defun org-in-block-p (names)
  20636. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20637. NAMES is a list of strings containing names of blocks.
  20638. Return first block name matched, or nil. Beware that in case of
  20639. nested blocks, the returned name may not belong to the closest
  20640. block from point."
  20641. (save-match-data
  20642. (catch 'exit
  20643. (let ((case-fold-search t)
  20644. (lim-up (save-excursion (outline-previous-heading)))
  20645. (lim-down (save-excursion (outline-next-heading))))
  20646. (dolist (name names)
  20647. (let ((n (regexp-quote name)))
  20648. (when (org-between-regexps-p
  20649. (concat "^[ \t]*#\\+begin_" n)
  20650. (concat "^[ \t]*#\\+end_" n)
  20651. lim-up lim-down)
  20652. (throw 'exit n)))))
  20653. nil)))
  20654. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20655. "Call `multi-occur' with buffers for all agenda files."
  20656. (interactive "sOrg-files matching: ")
  20657. (let* ((files (org-agenda-files))
  20658. (tnames (mapcar #'file-truename files))
  20659. (extra org-agenda-text-search-extra-files))
  20660. (when (eq (car extra) 'agenda-archives)
  20661. (setq extra (cdr extra))
  20662. (setq files (org-add-archive-files files)))
  20663. (dolist (f extra)
  20664. (unless (member (file-truename f) tnames)
  20665. (unless (member f files) (setq files (append files (list f))))
  20666. (setq tnames (append tnames (list (file-truename f))))))
  20667. (multi-occur
  20668. (mapcar (lambda (x)
  20669. (with-current-buffer
  20670. ;; FIXME: Why not just (find-file-noselect x)?
  20671. ;; Is it to avoid the "revert buffer" prompt?
  20672. (or (get-file-buffer x) (find-file-noselect x))
  20673. (widen)
  20674. (current-buffer)))
  20675. files)
  20676. regexp)))
  20677. (add-hook 'occur-mode-find-occurrence-hook
  20678. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20679. (defun org-occur-link-in-agenda-files ()
  20680. "Create a link and search for it in the agendas.
  20681. The link is not stored in `org-stored-links', it is just created
  20682. for the search purpose."
  20683. (interactive)
  20684. (let ((link (condition-case nil
  20685. (org-store-link nil)
  20686. (error "Unable to create a link to here"))))
  20687. (org-occur-in-agenda-files (regexp-quote link))))
  20688. (defun org-reverse-string (string)
  20689. "Return the reverse of STRING."
  20690. (apply 'string (reverse (string-to-list string))))
  20691. ;; defsubst org-uniquify must be defined before first use
  20692. (defun org-uniquify-alist (alist)
  20693. "Merge elements of ALIST with the same key.
  20694. For example, in this alist:
  20695. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20696. => \\='((a 1 3) (b 2))
  20697. merge (a 1) and (a 3) into (a 1 3).
  20698. The function returns the new ALIST."
  20699. (let (rtn)
  20700. (dolist (e alist rtn)
  20701. (let (n)
  20702. (if (not (assoc (car e) rtn))
  20703. (push e rtn)
  20704. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20705. (setq rtn (assq-delete-all (car e) rtn))
  20706. (push n rtn))))))
  20707. (defun org-delete-all (elts list)
  20708. "Remove all elements in ELTS from LIST.
  20709. Comparison is done with `equal'. It is a destructive operation
  20710. that may remove elements by altering the list structure."
  20711. (while elts
  20712. (setq list (delete (pop elts) list)))
  20713. list)
  20714. (defun org-back-over-empty-lines ()
  20715. "Move backwards over whitespace, to the beginning of the first empty line.
  20716. Returns the number of empty lines passed."
  20717. (let ((pos (point)))
  20718. (if (cdr (assoc 'heading org-blank-before-new-entry))
  20719. (skip-chars-backward " \t\n\r")
  20720. (unless (eobp)
  20721. (forward-line -1)))
  20722. (beginning-of-line 2)
  20723. (goto-char (min (point) pos))
  20724. (count-lines (point) pos)))
  20725. (defun org-skip-whitespace ()
  20726. (skip-chars-forward " \t\n\r"))
  20727. (defun org-point-in-group (point group &optional context)
  20728. "Check if POINT is in match-group GROUP.
  20729. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20730. match. If the match group does not exist or point is not inside it,
  20731. return nil."
  20732. (and (match-beginning group)
  20733. (>= point (match-beginning group))
  20734. (<= point (match-end group))
  20735. (if context
  20736. (list context (match-beginning group) (match-end group))
  20737. t)))
  20738. (defun org-switch-to-buffer-other-window (&rest args)
  20739. "Switch to buffer in a second window on the current frame.
  20740. In particular, do not allow pop-up frames.
  20741. Returns the newly created buffer."
  20742. (org-no-popups
  20743. (apply 'switch-to-buffer-other-window args)))
  20744. (defun org-combine-plists (&rest plists)
  20745. "Create a single property list from all plists in PLISTS.
  20746. The process starts by copying the first list, and then setting properties
  20747. from the other lists. Settings in the last list are the most significant
  20748. ones and overrule settings in the other lists."
  20749. (let ((rtn (copy-sequence (pop plists)))
  20750. p v ls)
  20751. (while plists
  20752. (setq ls (pop plists))
  20753. (while ls
  20754. (setq p (pop ls) v (pop ls))
  20755. (setq rtn (plist-put rtn p v))))
  20756. rtn))
  20757. (defun org-replace-escapes (string table)
  20758. "Replace %-escapes in STRING with values in TABLE.
  20759. TABLE is an association list with keys like \"%a\" and string values.
  20760. The sequences in STRING may contain normal field width and padding information,
  20761. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20762. so values can contain further %-escapes if they are define later in TABLE."
  20763. (let ((tbl (copy-alist table))
  20764. (case-fold-search nil)
  20765. (pchg 0)
  20766. re rpl)
  20767. (dolist (e tbl)
  20768. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20769. (when (and (cdr e) (string-match re (cdr e)))
  20770. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20771. (safe "SREF"))
  20772. (add-text-properties 0 3 (list 'sref sref) safe)
  20773. (setcdr e (replace-match safe t t (cdr e)))))
  20774. (while (string-match re string)
  20775. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20776. (cdr e)))
  20777. (setq string (replace-match rpl t t string))))
  20778. (while (setq pchg (next-property-change pchg string))
  20779. (let ((sref (get-text-property pchg 'sref string)))
  20780. (when (and sref (string-match "SREF" string pchg))
  20781. (setq string (replace-match sref t t string)))))
  20782. string))
  20783. (defun org-sublist (list start end)
  20784. "Return a section of LIST, from START to END.
  20785. Counting starts at 1."
  20786. (cl-subseq list (1- start) end))
  20787. (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
  20788. (defun org-find-base-buffer-visiting (file)
  20789. "Like `find-buffer-visiting' but always return the base buffer and
  20790. not an indirect buffer."
  20791. (let ((buf (or (get-file-buffer file)
  20792. (find-buffer-visiting file))))
  20793. (if buf
  20794. (or (buffer-base-buffer buf) buf)
  20795. nil)))
  20796. ;;; TODO: Only called once, from ox-odt which should probably use
  20797. ;;; org-export-inline-image-p or something.
  20798. (defun org-file-image-p (file)
  20799. "Return non-nil if FILE is an image."
  20800. (save-match-data
  20801. (string-match (image-file-name-regexp) file)))
  20802. (defun org-get-cursor-date (&optional with-time)
  20803. "Return the date at cursor in as a time.
  20804. This works in the calendar and in the agenda, anywhere else it just
  20805. returns the current time.
  20806. If WITH-TIME is non-nil, returns the time of the event at point (in
  20807. the agenda) or the current time of the day."
  20808. (let (date day defd tp hod mod)
  20809. (when with-time
  20810. (setq tp (get-text-property (point) 'time))
  20811. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20812. (setq hod (string-to-number (match-string 1 tp))
  20813. mod (string-to-number (match-string 2 tp))))
  20814. (or tp (let ((now (decode-time)))
  20815. (setq hod (nth 2 now)
  20816. mod (nth 1 now)))))
  20817. (cond
  20818. ((eq major-mode 'calendar-mode)
  20819. (setq date (calendar-cursor-to-date)
  20820. defd (encode-time 0 (or mod 0) (or hod 0)
  20821. (nth 1 date) (nth 0 date) (nth 2 date))))
  20822. ((eq major-mode 'org-agenda-mode)
  20823. (setq day (get-text-property (point) 'day))
  20824. (when day
  20825. (setq date (calendar-gregorian-from-absolute day)
  20826. defd (encode-time 0 (or mod 0) (or hod 0)
  20827. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20828. (or defd (current-time))))
  20829. (defun org-mark-subtree (&optional up)
  20830. "Mark the current subtree.
  20831. This puts point at the start of the current subtree, and mark at
  20832. the end. If a numeric prefix UP is given, move up into the
  20833. hierarchy of headlines by UP levels before marking the subtree."
  20834. (interactive "P")
  20835. (org-with-limited-levels
  20836. (cond ((org-at-heading-p) (beginning-of-line))
  20837. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20838. (t (outline-previous-visible-heading 1))))
  20839. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20840. (if (called-interactively-p 'any)
  20841. (call-interactively 'org-mark-element)
  20842. (org-mark-element)))
  20843. (defun org-file-newer-than-p (file time)
  20844. "Non-nil if FILE is newer than TIME.
  20845. FILE is a filename, as a string, TIME is a list of integers, as
  20846. returned by, e.g., `current-time'."
  20847. (and (file-exists-p file)
  20848. ;; Only compare times up to whole seconds as some file-systems
  20849. ;; (e.g. HFS+) do not retain any finer granularity. As
  20850. ;; a consequence, make sure we return non-nil when the two
  20851. ;; times are equal.
  20852. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20853. (cl-subseq time 0 2)))))
  20854. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20855. "Compile a SOURCE file using PROCESS.
  20856. PROCESS is either a function or a list of shell commands, as
  20857. strings. EXT is a file extension, without the leading dot, as
  20858. a string. It is used to check if the process actually succeeded.
  20859. PROCESS must create a file with the same base name and directory
  20860. as SOURCE, but ending with EXT. The function then returns its
  20861. filename. Otherwise, it raises an error. The error message can
  20862. then be refined by providing string ERR-MSG, which is appended to
  20863. the standard message.
  20864. If PROCESS is a function, it is called with a single argument:
  20865. the SOURCE file.
  20866. If it is a list of commands, each of them is called using
  20867. `shell-command'. By default, in each command, %b, %f, %F and %o
  20868. are replaced with, respectively, SOURCE base name, name, full
  20869. name and directory. It is possible, however, to use more
  20870. place-holders by specifying them in optional argument SPEC, as an
  20871. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20872. When PROCESS is a list of commands, optional argument LOG-BUF can
  20873. be set to a buffer or a buffer name. `shell-command' then uses
  20874. it for output.
  20875. `default-directory' is set to SOURCE directory during the whole
  20876. process."
  20877. (let* ((source-name (file-name-nondirectory source))
  20878. (base-name (file-name-sans-extension source-name))
  20879. (full-name (file-truename source))
  20880. (out-dir (file-name-directory source))
  20881. ;; Properly set working directory for compilation.
  20882. (default-directory (file-name-directory full-name))
  20883. (time (current-time))
  20884. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20885. (save-window-excursion
  20886. (pcase process
  20887. ((pred functionp) (funcall process (shell-quote-argument source)))
  20888. ((pred consp)
  20889. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20890. (spec (append spec
  20891. `((?b . ,(shell-quote-argument base-name))
  20892. (?f . ,(shell-quote-argument source-name))
  20893. (?F . ,(shell-quote-argument full-name))
  20894. (?o . ,(shell-quote-argument out-dir))))))
  20895. (dolist (command process)
  20896. (shell-command (format-spec command spec) log-buf))))
  20897. (_ (error "No valid command to process %S%s" source err-msg)))
  20898. ;; Check for process failure.
  20899. (let ((output (concat out-dir base-name "." ext)))
  20900. (unless (org-file-newer-than-p output time)
  20901. (error (format "File %S wasn't produced%s" output err-msg)))
  20902. output))))
  20903. ;;; Indentation
  20904. (defun org--get-expected-indentation (element contentsp)
  20905. "Expected indentation column for current line, according to ELEMENT.
  20906. ELEMENT is an element containing point. CONTENTSP is non-nil
  20907. when indentation is to be computed according to contents of
  20908. ELEMENT."
  20909. (let ((type (org-element-type element))
  20910. (start (org-element-property :begin element))
  20911. (post-affiliated (org-element-property :post-affiliated element)))
  20912. (org-with-wide-buffer
  20913. (cond
  20914. (contentsp
  20915. (cl-case type
  20916. ((diary-sexp footnote-definition) 0)
  20917. ((headline inlinetask nil)
  20918. (if (not org-adapt-indentation) 0
  20919. (let ((level (org-current-level)))
  20920. (if level (1+ level) 0))))
  20921. ((item plain-list) (org-list-item-body-column post-affiliated))
  20922. (t
  20923. (goto-char start)
  20924. (org-get-indentation))))
  20925. ((memq type '(headline inlinetask nil))
  20926. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20927. (org--get-expected-indentation element t)
  20928. 0))
  20929. ((memq type '(diary-sexp footnote-definition)) 0)
  20930. ;; First paragraph of a footnote definition or an item.
  20931. ;; Indent like parent.
  20932. ((< (line-beginning-position) start)
  20933. (org--get-expected-indentation
  20934. (org-element-property :parent element) t))
  20935. ;; At first line: indent according to previous sibling, if any,
  20936. ;; ignoring footnote definitions and inline tasks, or parent's
  20937. ;; contents.
  20938. ((= (line-beginning-position) start)
  20939. (catch 'exit
  20940. (while t
  20941. (if (= (point-min) start) (throw 'exit 0)
  20942. (goto-char (1- start))
  20943. (let* ((previous (org-element-at-point))
  20944. (parent previous))
  20945. (while (and parent (<= (org-element-property :end parent) start))
  20946. (setq previous parent
  20947. parent (org-element-property :parent parent)))
  20948. (cond
  20949. ((not previous) (throw 'exit 0))
  20950. ((> (org-element-property :end previous) start)
  20951. (throw 'exit (org--get-expected-indentation previous t)))
  20952. ((memq (org-element-type previous)
  20953. '(footnote-definition inlinetask))
  20954. (setq start (org-element-property :begin previous)))
  20955. (t (goto-char (org-element-property :begin previous))
  20956. (throw 'exit
  20957. (if (bolp) (org-get-indentation)
  20958. ;; At first paragraph in an item or
  20959. ;; a footnote definition.
  20960. (org--get-expected-indentation
  20961. (org-element-property :parent previous) t))))))))))
  20962. ;; Otherwise, move to the first non-blank line above.
  20963. (t
  20964. (beginning-of-line)
  20965. (let ((pos (point)))
  20966. (skip-chars-backward " \r\t\n")
  20967. (cond
  20968. ;; Two blank lines end a footnote definition or a plain
  20969. ;; list. When we indent an empty line after them, the
  20970. ;; containing list or footnote definition is over, so it
  20971. ;; qualifies as a previous sibling. Therefore, we indent
  20972. ;; like its first line.
  20973. ((and (memq type '(footnote-definition plain-list))
  20974. (> (count-lines (point) pos) 2))
  20975. (goto-char start)
  20976. (org-get-indentation))
  20977. ;; Line above is the first one of a paragraph at the
  20978. ;; beginning of an item or a footnote definition. Indent
  20979. ;; like parent.
  20980. ((< (line-beginning-position) start)
  20981. (org--get-expected-indentation
  20982. (org-element-property :parent element) t))
  20983. ;; Line above is the beginning of an element, i.e., point
  20984. ;; was originally on the blank lines between element's start
  20985. ;; and contents.
  20986. ((= (line-beginning-position) post-affiliated)
  20987. (org--get-expected-indentation element t))
  20988. ;; POS is after contents in a greater element. Indent like
  20989. ;; the beginning of the element.
  20990. ;;
  20991. ;; As a special case, if point is at the end of a footnote
  20992. ;; definition or an item, indent like the very last element
  20993. ;; within. If that last element is an item, indent like its
  20994. ;; contents.
  20995. ((and (not (eq type 'paragraph))
  20996. (let ((cend (org-element-property :contents-end element)))
  20997. (and cend (<= cend pos))))
  20998. (if (memq type '(footnote-definition item plain-list))
  20999. (let ((last (org-element-at-point)))
  21000. (org--get-expected-indentation
  21001. last (eq (org-element-type last) 'item)))
  21002. (goto-char start)
  21003. (org-get-indentation)))
  21004. ;; In any other case, indent like the current line.
  21005. (t (org-get-indentation)))))))))
  21006. (defun org--align-node-property ()
  21007. "Align node property at point.
  21008. Alignment is done according to `org-property-format', which see."
  21009. (when (save-excursion
  21010. (beginning-of-line)
  21011. (looking-at org-property-re))
  21012. (replace-match
  21013. (concat (match-string 4)
  21014. (org-trim
  21015. (format org-property-format (match-string 1) (match-string 3))))
  21016. t t)))
  21017. (defun org-indent-line ()
  21018. "Indent line depending on context.
  21019. Indentation is done according to the following rules:
  21020. - Footnote definitions, diary sexps, headlines and inline tasks
  21021. have to start at column 0.
  21022. - On the very first line of an element, consider, in order, the
  21023. next rules until one matches:
  21024. 1. If there's a sibling element before, ignoring footnote
  21025. definitions and inline tasks, indent like its first line.
  21026. 2. If element has a parent, indent like its contents. More
  21027. precisely, if parent is an item, indent after the
  21028. description part, if any, or the bullet (see
  21029. `org-list-description-max-indent'). Else, indent like
  21030. parent's first line.
  21031. 3. Otherwise, indent relatively to current level, if
  21032. `org-adapt-indentation' is non-nil, or to left margin.
  21033. - On a blank line at the end of an element, indent according to
  21034. the type of the element. More precisely
  21035. 1. If element is a plain list, an item, or a footnote
  21036. definition, indent like the very last element within.
  21037. 2. If element is a paragraph, indent like its last non blank
  21038. line.
  21039. 3. Otherwise, indent like its very first line.
  21040. - In the code part of a source block, use language major mode
  21041. to indent current line if `org-src-tab-acts-natively' is
  21042. non-nil. If it is nil, do nothing.
  21043. - Otherwise, indent like the first non-blank line above.
  21044. The function doesn't indent an item as it could break the whole
  21045. list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
  21046. \\[org-shiftmetaright].
  21047. Also align node properties according to `org-property-format'."
  21048. (interactive)
  21049. (cond
  21050. (orgstruct-is-++
  21051. (let ((indent-line-function
  21052. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  21053. (indent-according-to-mode)))
  21054. ((org-at-heading-p) 'noindent)
  21055. (t
  21056. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21057. (type (org-element-type element)))
  21058. (cond ((and (memq type '(plain-list item))
  21059. (= (line-beginning-position)
  21060. (org-element-property :post-affiliated element)))
  21061. 'noindent)
  21062. ((and (eq type 'src-block)
  21063. org-src-tab-acts-natively
  21064. (> (line-beginning-position)
  21065. (org-element-property :post-affiliated element))
  21066. (< (line-beginning-position)
  21067. (org-with-wide-buffer
  21068. (goto-char (org-element-property :end element))
  21069. (skip-chars-backward " \r\t\n")
  21070. (line-beginning-position))))
  21071. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21072. (t
  21073. (let ((column (org--get-expected-indentation element nil)))
  21074. ;; Preserve current column.
  21075. (if (<= (current-column) (current-indentation))
  21076. (indent-line-to column)
  21077. (save-excursion (indent-line-to column))))
  21078. ;; Align node property. Also preserve current column.
  21079. (when (eq type 'node-property)
  21080. (let ((column (current-column)))
  21081. (org--align-node-property)
  21082. (org-move-to-column column)))))))))
  21083. (defun org-indent-region (start end)
  21084. "Indent each non-blank line in the region.
  21085. Called from a program, START and END specify the region to
  21086. indent. The function will not indent contents of example blocks,
  21087. verse blocks and export blocks as leading white spaces are
  21088. assumed to be significant there."
  21089. (interactive "r")
  21090. (save-excursion
  21091. (goto-char start)
  21092. (skip-chars-forward " \r\t\n")
  21093. (unless (eobp) (beginning-of-line))
  21094. (let ((indent-to
  21095. (lambda (ind pos)
  21096. ;; Set IND as indentation for all lines between point and
  21097. ;; POS. Blank lines are ignored. Leave point after POS
  21098. ;; once done.
  21099. (let ((limit (copy-marker pos)))
  21100. (while (< (point) limit)
  21101. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21102. (forward-line))
  21103. (set-marker limit nil))))
  21104. (end (copy-marker end)))
  21105. (while (< (point) end)
  21106. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21107. (let* ((element (org-element-at-point))
  21108. (type (org-element-type element))
  21109. (element-end (copy-marker (org-element-property :end element)))
  21110. (ind (org--get-expected-indentation element nil)))
  21111. (cond
  21112. ((or (memq type '(paragraph table table-row))
  21113. (not (or (org-element-property :contents-begin element)
  21114. (memq type
  21115. '(example-block export-block src-block)))))
  21116. ;; Elements here are indented as a single block. Also
  21117. ;; align node properties.
  21118. (when (eq type 'node-property)
  21119. (org--align-node-property)
  21120. (beginning-of-line))
  21121. (funcall indent-to ind (min element-end end)))
  21122. (t
  21123. ;; Elements in this category consist of three parts:
  21124. ;; before the contents, the contents, and after the
  21125. ;; contents. The contents are treated specially,
  21126. ;; according to the element type, or not indented at
  21127. ;; all. Other parts are indented as a single block.
  21128. (let* ((post (copy-marker
  21129. (org-element-property :post-affiliated element)))
  21130. (cbeg
  21131. (copy-marker
  21132. (cond
  21133. ((not (org-element-property :contents-begin element))
  21134. ;; Fake contents for source blocks.
  21135. (org-with-wide-buffer
  21136. (goto-char post)
  21137. (forward-line)
  21138. (point)))
  21139. ((memq type '(footnote-definition item plain-list))
  21140. ;; Contents in these elements could start on
  21141. ;; the same line as the beginning of the
  21142. ;; element. Make sure we start indenting
  21143. ;; from the second line.
  21144. (org-with-wide-buffer
  21145. (goto-char post)
  21146. (end-of-line)
  21147. (skip-chars-forward " \r\t\n")
  21148. (if (eobp) (point) (line-beginning-position))))
  21149. (t (org-element-property :contents-begin element)))))
  21150. (cend (copy-marker
  21151. (or (org-element-property :contents-end element)
  21152. ;; Fake contents for source blocks.
  21153. (org-with-wide-buffer
  21154. (goto-char element-end)
  21155. (skip-chars-backward " \r\t\n")
  21156. (line-beginning-position)))
  21157. t)))
  21158. ;; Do not change items indentation individually as it
  21159. ;; might break the list as a whole. On the other
  21160. ;; hand, when at a plain list, indent it as a whole.
  21161. (cond ((eq type 'plain-list)
  21162. (let ((offset (- ind (org-get-indentation))))
  21163. (unless (zerop offset)
  21164. (indent-rigidly (org-element-property :begin element)
  21165. (org-element-property :end element)
  21166. offset))
  21167. (goto-char cbeg)))
  21168. ((eq type 'item) (goto-char cbeg))
  21169. (t (funcall indent-to ind (min cbeg end))))
  21170. (when (< (point) end)
  21171. (cl-case type
  21172. ((example-block export-block verse-block))
  21173. (src-block
  21174. ;; In a source block, indent source code
  21175. ;; according to language major mode, but only if
  21176. ;; `org-src-tab-acts-natively' is non-nil.
  21177. (when (and (< (point) end) org-src-tab-acts-natively)
  21178. (ignore-errors
  21179. (org-babel-do-in-edit-buffer
  21180. (indent-region (point-min) (point-max))))))
  21181. (t (org-indent-region (point) (min cend end))))
  21182. (goto-char (min cend end))
  21183. (when (< (point) end)
  21184. (funcall indent-to ind (min element-end end))))
  21185. (set-marker post nil)
  21186. (set-marker cbeg nil)
  21187. (set-marker cend nil))))
  21188. (set-marker element-end nil))))
  21189. (set-marker end nil))))
  21190. (defun org-indent-drawer ()
  21191. "Indent the drawer at point."
  21192. (interactive)
  21193. (unless (save-excursion
  21194. (beginning-of-line)
  21195. (looking-at-p org-drawer-regexp))
  21196. (user-error "Not at a drawer"))
  21197. (let ((element (org-element-at-point)))
  21198. (unless (memq (org-element-type element) '(drawer property-drawer))
  21199. (user-error "Not at a drawer"))
  21200. (org-with-wide-buffer
  21201. (org-indent-region (org-element-property :begin element)
  21202. (org-element-property :end element))))
  21203. (message "Drawer at point indented"))
  21204. (defun org-indent-block ()
  21205. "Indent the block at point."
  21206. (interactive)
  21207. (unless (save-excursion
  21208. (beginning-of-line)
  21209. (let ((case-fold-search t))
  21210. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21211. (user-error "Not at a block"))
  21212. (let ((element (org-element-at-point)))
  21213. (unless (memq (org-element-type element)
  21214. '(comment-block center-block dynamic-block example-block
  21215. export-block quote-block special-block
  21216. src-block verse-block))
  21217. (user-error "Not at a block"))
  21218. (org-with-wide-buffer
  21219. (org-indent-region (org-element-property :begin element)
  21220. (org-element-property :end element))))
  21221. (message "Block at point indented"))
  21222. ;;; Filling
  21223. ;; We use our own fill-paragraph and auto-fill functions.
  21224. ;; `org-fill-paragraph' relies on adaptive filling and context
  21225. ;; checking. Appropriate `fill-prefix' is computed with
  21226. ;; `org-adaptive-fill-function'.
  21227. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21228. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21229. ;; `org-adaptive-fill-function' value. Internally,
  21230. ;; `org-comment-line-break-function' breaks the line.
  21231. ;; `org-setup-filling' installs filling and auto-filling related
  21232. ;; variables during `org-mode' initialization.
  21233. (defvar org-element-paragraph-separate) ; org-element.el
  21234. (defun org-setup-filling ()
  21235. (require 'org-element)
  21236. ;; Prevent auto-fill from inserting unwanted new items.
  21237. (when (boundp 'fill-nobreak-predicate)
  21238. (setq-local
  21239. fill-nobreak-predicate
  21240. (org-uniquify
  21241. (append fill-nobreak-predicate
  21242. '(org-fill-line-break-nobreak-p
  21243. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21244. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21245. (setq-local paragraph-start paragraph-ending)
  21246. (setq-local paragraph-separate paragraph-ending))
  21247. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21248. (setq-local auto-fill-inhibit-regexp nil)
  21249. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21250. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21251. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21252. (defun org-fill-line-break-nobreak-p ()
  21253. "Non-nil when a new line at point would create an Org line break."
  21254. (save-excursion
  21255. (skip-chars-backward "[ \t]")
  21256. (skip-chars-backward "\\\\")
  21257. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21258. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21259. "Non-nil when a new line at point would split a timestamp."
  21260. (and (org-at-timestamp-p t)
  21261. (not (looking-at org-ts-regexp-both))))
  21262. (declare-function message-in-body-p "message" ())
  21263. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21264. (defun org-adaptive-fill-function ()
  21265. "Compute a fill prefix for the current line.
  21266. Return fill prefix, as a string, or nil if current line isn't
  21267. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21268. matches in paragraphs or comments, use it."
  21269. (catch 'exit
  21270. (when (derived-mode-p 'message-mode)
  21271. (save-excursion
  21272. (beginning-of-line)
  21273. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21274. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21275. ((looking-at message-cite-prefix-regexp)
  21276. (throw 'exit (match-string-no-properties 0)))
  21277. ((looking-at org-outline-regexp)
  21278. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21279. (org-with-wide-buffer
  21280. (unless (org-at-heading-p)
  21281. (let* ((p (line-beginning-position))
  21282. (element (save-excursion
  21283. (beginning-of-line)
  21284. (org-element-at-point)))
  21285. (type (org-element-type element))
  21286. (post-affiliated (org-element-property :post-affiliated element)))
  21287. (unless (< p post-affiliated)
  21288. (cl-case type
  21289. (comment
  21290. (save-excursion
  21291. (beginning-of-line)
  21292. (looking-at "[ \t]*")
  21293. (concat (match-string 0) "# ")))
  21294. (footnote-definition "")
  21295. ((item plain-list)
  21296. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21297. (paragraph
  21298. ;; Fill prefix is usually the same as the current line,
  21299. ;; unless the paragraph is at the beginning of an item.
  21300. (let ((parent (org-element-property :parent element)))
  21301. (save-excursion
  21302. (beginning-of-line)
  21303. (cond ((eq (org-element-type parent) 'item)
  21304. (make-string (org-list-item-body-column
  21305. (org-element-property :begin parent))
  21306. ?\s))
  21307. ((and adaptive-fill-regexp
  21308. ;; Locally disable
  21309. ;; `adaptive-fill-function' to let
  21310. ;; `fill-context-prefix' handle
  21311. ;; `adaptive-fill-regexp' variable.
  21312. (let (adaptive-fill-function)
  21313. (fill-context-prefix
  21314. post-affiliated
  21315. (org-element-property :end element)))))
  21316. ((looking-at "[ \t]+") (match-string 0))
  21317. (t "")))))
  21318. (comment-block
  21319. ;; Only fill contents if P is within block boundaries.
  21320. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21321. (forward-line)
  21322. (point)))
  21323. (cend (save-excursion
  21324. (goto-char (org-element-property :end element))
  21325. (skip-chars-backward " \r\t\n")
  21326. (line-beginning-position))))
  21327. (when (and (>= p cbeg) (< p cend))
  21328. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21329. (match-string 0)
  21330. "")))))))))))
  21331. (declare-function message-goto-body "message" ())
  21332. (defvar message-cite-prefix-regexp) ; From message.el
  21333. (defun org-fill-paragraph (&optional justify)
  21334. "Fill element at point, when applicable.
  21335. This function only applies to comment blocks, comments, example
  21336. blocks and paragraphs. Also, as a special case, re-align table
  21337. when point is at one.
  21338. If JUSTIFY is non-nil (interactively, with prefix argument),
  21339. justify as well. If `sentence-end-double-space' is non-nil, then
  21340. period followed by one space does not end a sentence, so don't
  21341. break a line there. The variable `fill-column' controls the
  21342. width for filling.
  21343. For convenience, when point is at a plain list, an item or
  21344. a footnote definition, try to fill the first paragraph within."
  21345. (interactive)
  21346. (if (and (derived-mode-p 'message-mode)
  21347. (or (not (message-in-body-p))
  21348. (save-excursion (move-beginning-of-line 1)
  21349. (looking-at message-cite-prefix-regexp))))
  21350. ;; First ensure filling is correct in message-mode.
  21351. (let ((fill-paragraph-function
  21352. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21353. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21354. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21355. (paragraph-separate
  21356. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21357. (fill-paragraph nil))
  21358. (with-syntax-table org-mode-transpose-word-syntax-table
  21359. ;; Move to end of line in order to get the first paragraph
  21360. ;; within a plain list or a footnote definition.
  21361. (let ((element (save-excursion
  21362. (end-of-line)
  21363. (or (ignore-errors (org-element-at-point))
  21364. (user-error "An element cannot be parsed line %d"
  21365. (line-number-at-pos (point)))))))
  21366. ;; First check if point is in a blank line at the beginning of
  21367. ;; the buffer. In that case, ignore filling.
  21368. (cl-case (org-element-type element)
  21369. ;; Use major mode filling function is src blocks.
  21370. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21371. ;; Align Org tables, leave table.el tables as-is.
  21372. (table-row (org-table-align) t)
  21373. (table
  21374. (when (eq (org-element-property :type element) 'org)
  21375. (save-excursion
  21376. (goto-char (org-element-property :post-affiliated element))
  21377. (org-table-align)))
  21378. t)
  21379. (paragraph
  21380. ;; Paragraphs may contain `line-break' type objects.
  21381. (let ((beg (max (point-min)
  21382. (org-element-property :contents-begin element)))
  21383. (end (min (point-max)
  21384. (org-element-property :contents-end element))))
  21385. ;; Do nothing if point is at an affiliated keyword.
  21386. (if (< (line-end-position) beg) t
  21387. (when (derived-mode-p 'message-mode)
  21388. ;; In `message-mode', do not fill following citation
  21389. ;; in current paragraph nor text before message body.
  21390. (let ((body-start (save-excursion (message-goto-body))))
  21391. (when body-start (setq beg (max body-start beg))))
  21392. (when (save-excursion
  21393. (re-search-forward
  21394. (concat "^" message-cite-prefix-regexp) end t))
  21395. (setq end (match-beginning 0))))
  21396. ;; Fill paragraph, taking line breaks into account.
  21397. (save-excursion
  21398. (goto-char beg)
  21399. (let ((cuts (list beg)))
  21400. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21401. (when (eq 'line-break
  21402. (org-element-type
  21403. (save-excursion (backward-char)
  21404. (org-element-context))))
  21405. (push (point) cuts)))
  21406. (dolist (c (delq end cuts))
  21407. (fill-region-as-paragraph c end justify)
  21408. (setq end c))))
  21409. t)))
  21410. ;; Contents of `comment-block' type elements should be
  21411. ;; filled as plain text, but only if point is within block
  21412. ;; markers.
  21413. (comment-block
  21414. (let* ((case-fold-search t)
  21415. (beg (save-excursion
  21416. (goto-char (org-element-property :begin element))
  21417. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21418. (forward-line)
  21419. (point)))
  21420. (end (save-excursion
  21421. (goto-char (org-element-property :end element))
  21422. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21423. (line-beginning-position))))
  21424. (if (or (< (point) beg) (> (point) end)) t
  21425. (fill-region-as-paragraph
  21426. (save-excursion (end-of-line)
  21427. (re-search-backward "^[ \t]*$" beg 'move)
  21428. (line-beginning-position))
  21429. (save-excursion (beginning-of-line)
  21430. (re-search-forward "^[ \t]*$" end 'move)
  21431. (line-beginning-position))
  21432. justify))))
  21433. ;; Fill comments.
  21434. (comment
  21435. (let ((begin (org-element-property :post-affiliated element))
  21436. (end (org-element-property :end element)))
  21437. (when (and (>= (point) begin) (<= (point) end))
  21438. (let ((begin (save-excursion
  21439. (end-of-line)
  21440. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21441. (progn (forward-line) (point))
  21442. begin)))
  21443. (end (save-excursion
  21444. (end-of-line)
  21445. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21446. (1- (line-beginning-position))
  21447. (skip-chars-backward " \r\t\n")
  21448. (line-end-position)))))
  21449. ;; Do not fill comments when at a blank line.
  21450. (when (> end begin)
  21451. (let ((fill-prefix
  21452. (save-excursion
  21453. (beginning-of-line)
  21454. (looking-at "[ \t]*#")
  21455. (let ((comment-prefix (match-string 0)))
  21456. (goto-char (match-end 0))
  21457. (if (looking-at adaptive-fill-regexp)
  21458. (concat comment-prefix (match-string 0))
  21459. (concat comment-prefix " "))))))
  21460. (save-excursion
  21461. (fill-region-as-paragraph begin end justify))))))
  21462. t))
  21463. ;; Ignore every other element.
  21464. (otherwise t))))))
  21465. (defun org-auto-fill-function ()
  21466. "Auto-fill function."
  21467. ;; Check if auto-filling is meaningful.
  21468. (let ((fc (current-fill-column)))
  21469. (when (and fc (> (current-column) fc))
  21470. (let* ((fill-prefix (org-adaptive-fill-function))
  21471. ;; Enforce empty fill prefix, if required. Otherwise, it
  21472. ;; will be computed again.
  21473. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21474. (when fill-prefix (do-auto-fill))))))
  21475. (defun org-comment-line-break-function (&optional soft)
  21476. "Break line at point and indent, continuing comment if within one.
  21477. The inserted newline is marked hard if variable
  21478. `use-hard-newlines' is true, unless optional argument SOFT is
  21479. non-nil."
  21480. (if soft (insert-and-inherit ?\n) (newline 1))
  21481. (save-excursion (forward-char -1) (delete-horizontal-space))
  21482. (delete-horizontal-space)
  21483. (indent-to-left-margin)
  21484. (insert-before-markers-and-inherit fill-prefix))
  21485. ;;; Fixed Width Areas
  21486. (defun org-toggle-fixed-width ()
  21487. "Toggle fixed-width markup.
  21488. Add or remove fixed-width markup on current line, whenever it
  21489. makes sense. Return an error otherwise.
  21490. If a region is active and if it contains only fixed-width areas
  21491. or blank lines, remove all fixed-width markup in it. If the
  21492. region contains anything else, convert all non-fixed-width lines
  21493. to fixed-width ones.
  21494. Blank lines at the end of the region are ignored unless the
  21495. region only contains such lines."
  21496. (interactive)
  21497. (if (not (org-region-active-p))
  21498. ;; No region:
  21499. ;;
  21500. ;; Remove fixed width marker only in a fixed-with element.
  21501. ;;
  21502. ;; Add fixed width maker in paragraphs, in blank lines after
  21503. ;; elements or at the beginning of a headline or an inlinetask,
  21504. ;; and before any one-line elements (e.g., a clock).
  21505. (progn
  21506. (beginning-of-line)
  21507. (let* ((element (org-element-at-point))
  21508. (type (org-element-type element)))
  21509. (cond
  21510. ((and (eq type 'fixed-width)
  21511. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21512. (replace-match
  21513. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21514. ((and (memq type '(babel-call clock comment diary-sexp headline
  21515. horizontal-rule keyword paragraph
  21516. planning))
  21517. (<= (org-element-property :post-affiliated element) (point)))
  21518. (skip-chars-forward " \t")
  21519. (insert ": "))
  21520. ((and (looking-at-p "[ \t]*$")
  21521. (or (eq type 'inlinetask)
  21522. (save-excursion
  21523. (skip-chars-forward " \r\t\n")
  21524. (<= (org-element-property :end element) (point)))))
  21525. (delete-region (point) (line-end-position))
  21526. (org-indent-line)
  21527. (insert ": "))
  21528. (t (user-error "Cannot insert a fixed-width line here")))))
  21529. ;; Region active.
  21530. (let* ((begin (save-excursion
  21531. (goto-char (region-beginning))
  21532. (line-beginning-position)))
  21533. (end (copy-marker
  21534. (save-excursion
  21535. (goto-char (region-end))
  21536. (unless (eolp) (beginning-of-line))
  21537. (if (save-excursion (re-search-backward "\\S-" begin t))
  21538. (progn (skip-chars-backward " \r\t\n") (point))
  21539. (point)))))
  21540. (all-fixed-width-p
  21541. (catch 'not-all-p
  21542. (save-excursion
  21543. (goto-char begin)
  21544. (skip-chars-forward " \r\t\n")
  21545. (when (eobp) (throw 'not-all-p nil))
  21546. (while (< (point) end)
  21547. (let ((element (org-element-at-point)))
  21548. (if (eq (org-element-type element) 'fixed-width)
  21549. (goto-char (org-element-property :end element))
  21550. (throw 'not-all-p nil))))
  21551. t))))
  21552. (if all-fixed-width-p
  21553. (save-excursion
  21554. (goto-char begin)
  21555. (while (< (point) end)
  21556. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21557. (replace-match
  21558. "" nil nil nil
  21559. (if (= (line-end-position) (match-end 0)) 0 1)))
  21560. (forward-line)))
  21561. (let ((min-ind (point-max)))
  21562. ;; Find minimum indentation across all lines.
  21563. (save-excursion
  21564. (goto-char begin)
  21565. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21566. (setq min-ind 0)
  21567. (catch 'zerop
  21568. (while (< (point) end)
  21569. (unless (looking-at-p "[ \t]*$")
  21570. (let ((ind (org-get-indentation)))
  21571. (setq min-ind (min min-ind ind))
  21572. (when (zerop ind) (throw 'zerop t))))
  21573. (forward-line)))))
  21574. ;; Loop over all lines and add fixed-width markup everywhere
  21575. ;; but in fixed-width lines.
  21576. (save-excursion
  21577. (goto-char begin)
  21578. (while (< (point) end)
  21579. (cond
  21580. ((org-at-heading-p)
  21581. (insert ": ")
  21582. (forward-line)
  21583. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21584. (insert ":")
  21585. (forward-line)))
  21586. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21587. (let* ((element (org-element-at-point))
  21588. (element-end (org-element-property :end element)))
  21589. (if (eq (org-element-type element) 'fixed-width)
  21590. (progn (goto-char element-end)
  21591. (skip-chars-backward " \r\t\n")
  21592. (forward-line))
  21593. (let ((limit (min end element-end)))
  21594. (while (< (point) limit)
  21595. (org-move-to-column min-ind t)
  21596. (insert ": ")
  21597. (forward-line))))))
  21598. (t
  21599. (org-move-to-column min-ind t)
  21600. (insert ": ")
  21601. (forward-line)))))))
  21602. (set-marker end nil))))
  21603. ;;; Comments
  21604. ;; Org comments syntax is quite complex. It requires the entire line
  21605. ;; to be just a comment. Also, even with the right syntax at the
  21606. ;; beginning of line, some some elements (i.e. verse-block or
  21607. ;; example-block) don't accept comments. Usual Emacs comment commands
  21608. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21609. ;; Org still relies on `comment-dwim', but cannot trust
  21610. ;; `comment-only-p'. So, `comment-region-function' and
  21611. ;; `uncomment-region-function' both point
  21612. ;; to`org-comment-or-uncomment-region'. Eventually,
  21613. ;; `org-insert-comment' takes care of insertion of comments at the
  21614. ;; beginning of line.
  21615. ;; `org-setup-comments-handling' install comments related variables
  21616. ;; during `org-mode' initialization.
  21617. (defun org-setup-comments-handling ()
  21618. (interactive)
  21619. (setq-local comment-use-syntax nil)
  21620. (setq-local comment-start "# ")
  21621. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21622. (setq-local comment-insert-comment-function 'org-insert-comment)
  21623. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21624. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21625. (defun org-insert-comment ()
  21626. "Insert an empty comment above current line.
  21627. If the line is empty, insert comment at its beginning. When
  21628. point is within a source block, comment according to the related
  21629. major mode."
  21630. (if (let ((element (org-element-at-point)))
  21631. (and (eq (org-element-type element) 'src-block)
  21632. (< (save-excursion
  21633. (goto-char (org-element-property :post-affiliated element))
  21634. (line-end-position))
  21635. (point))
  21636. (> (save-excursion
  21637. (goto-char (org-element-property :end element))
  21638. (skip-chars-backward " \r\t\n")
  21639. (line-beginning-position))
  21640. (point))))
  21641. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21642. (beginning-of-line)
  21643. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21644. (open-line 1))
  21645. (org-indent-line)
  21646. (insert "# ")))
  21647. (defvar comment-empty-lines) ; From newcomment.el.
  21648. (defun org-comment-or-uncomment-region (beg end &rest _)
  21649. "Comment or uncomment each non-blank line in the region.
  21650. Uncomment each non-blank line between BEG and END if it only
  21651. contains commented lines. Otherwise, comment them. If region is
  21652. strictly within a source block, use appropriate comment syntax."
  21653. (if (let ((element (org-element-at-point)))
  21654. (and (eq (org-element-type element) 'src-block)
  21655. (< (save-excursion
  21656. (goto-char (org-element-property :post-affiliated element))
  21657. (line-end-position))
  21658. beg)
  21659. (>= (save-excursion
  21660. (goto-char (org-element-property :end element))
  21661. (skip-chars-backward " \r\t\n")
  21662. (line-beginning-position))
  21663. end)))
  21664. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21665. (save-restriction
  21666. ;; Restrict region
  21667. (narrow-to-region (save-excursion (goto-char beg)
  21668. (skip-chars-forward " \r\t\n" end)
  21669. (line-beginning-position))
  21670. (save-excursion (goto-char end)
  21671. (skip-chars-backward " \r\t\n" beg)
  21672. (line-end-position)))
  21673. (let ((uncommentp
  21674. ;; UNCOMMENTP is non-nil when every non blank line between
  21675. ;; BEG and END is a comment.
  21676. (save-excursion
  21677. (goto-char (point-min))
  21678. (while (and (not (eobp))
  21679. (let ((element (org-element-at-point)))
  21680. (and (eq (org-element-type element) 'comment)
  21681. (goto-char (min (point-max)
  21682. (org-element-property
  21683. :end element)))))))
  21684. (eobp))))
  21685. (if uncommentp
  21686. ;; Only blank lines and comments in region: uncomment it.
  21687. (save-excursion
  21688. (goto-char (point-min))
  21689. (while (not (eobp))
  21690. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21691. (replace-match "" nil nil nil 1))
  21692. (forward-line)))
  21693. ;; Comment each line in region.
  21694. (let ((min-indent (point-max)))
  21695. ;; First find the minimum indentation across all lines.
  21696. (save-excursion
  21697. (goto-char (point-min))
  21698. (while (and (not (eobp)) (not (zerop min-indent)))
  21699. (unless (looking-at "[ \t]*$")
  21700. (setq min-indent (min min-indent (current-indentation))))
  21701. (forward-line)))
  21702. ;; Then loop over all lines.
  21703. (save-excursion
  21704. (goto-char (point-min))
  21705. (while (not (eobp))
  21706. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21707. ;; Don't get fooled by invisible text (e.g. link path)
  21708. ;; when moving to column MIN-INDENT.
  21709. (let ((buffer-invisibility-spec nil))
  21710. (org-move-to-column min-indent t))
  21711. (insert comment-start))
  21712. (forward-line)))))))))
  21713. (defun org-comment-dwim (_arg)
  21714. "Call `comment-dwim' within a source edit buffer if needed."
  21715. (interactive "*P")
  21716. (if (org-in-src-block-p)
  21717. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21718. (call-interactively 'comment-dwim)))
  21719. ;;; Timestamps API
  21720. ;; This section contains tools to operate on timestamp objects, as
  21721. ;; returned by, e.g. `org-element-context'.
  21722. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21723. "Encode TIMESTAMP object into Emacs internal time.
  21724. Use end of date range or time range when END is non-nil."
  21725. (apply #'encode-time
  21726. (cons 0
  21727. (mapcar
  21728. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21729. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21730. '(:minute-start :hour-start :day-start :month-start
  21731. :year-start))))))
  21732. (defun org-timestamp-has-time-p (timestamp)
  21733. "Non-nil when TIMESTAMP has a time specified."
  21734. (org-element-property :hour-start timestamp))
  21735. (defun org-timestamp-format (timestamp format &optional end utc)
  21736. "Format a TIMESTAMP object into a string.
  21737. FORMAT is a format specifier to be passed to
  21738. `format-time-string'.
  21739. When optional argument END is non-nil, use end of date-range or
  21740. time-range, if possible.
  21741. When optional argument UTC is non-nil, time will be expressed as
  21742. Universal Time."
  21743. (format-time-string
  21744. format (org-timestamp--to-internal-time timestamp end)
  21745. (and utc t)))
  21746. (defun org-timestamp-split-range (timestamp &optional end)
  21747. "Extract a TIMESTAMP object from a date or time range.
  21748. END, when non-nil, means extract the end of the range.
  21749. Otherwise, extract its start.
  21750. Return a new timestamp object."
  21751. (let ((type (org-element-property :type timestamp)))
  21752. (if (memq type '(active inactive diary)) timestamp
  21753. (let ((split-ts (org-element-copy timestamp)))
  21754. ;; Set new type.
  21755. (org-element-put-property
  21756. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21757. ;; Copy start properties over end properties if END is
  21758. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21759. (let ((p-alist '((:minute-start . :minute-end)
  21760. (:hour-start . :hour-end)
  21761. (:day-start . :day-end)
  21762. (:month-start . :month-end)
  21763. (:year-start . :year-end))))
  21764. (dolist (p-cell p-alist)
  21765. (org-element-put-property
  21766. split-ts
  21767. (funcall (if end #'car #'cdr) p-cell)
  21768. (org-element-property
  21769. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21770. ;; Eventually refresh `:raw-value'.
  21771. (org-element-put-property split-ts :raw-value nil)
  21772. (org-element-put-property
  21773. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21774. (defun org-timestamp-translate (timestamp &optional boundary)
  21775. "Translate TIMESTAMP object to custom format.
  21776. Format string is defined in `org-time-stamp-custom-formats',
  21777. which see.
  21778. When optional argument BOUNDARY is non-nil, it is either the
  21779. symbol `start' or `end'. In this case, only translate the
  21780. starting or ending part of TIMESTAMP if it is a date or time
  21781. range. Otherwise, translate both parts.
  21782. Return timestamp as-is if `org-display-custom-times' is nil or if
  21783. it has a `diary' type."
  21784. (let ((type (org-element-property :type timestamp)))
  21785. (if (or (not org-display-custom-times) (eq type 'diary))
  21786. (org-element-interpret-data timestamp)
  21787. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21788. org-time-stamp-custom-formats)))
  21789. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21790. (concat (org-timestamp-format timestamp fmt)
  21791. "--"
  21792. (org-timestamp-format timestamp fmt t))
  21793. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21794. ;;; Other stuff.
  21795. (defvar reftex-docstruct-symbol)
  21796. (defvar reftex-cite-format)
  21797. (defvar org--rds)
  21798. (defun org-reftex-citation ()
  21799. "Use reftex-citation to insert a citation into the buffer.
  21800. This looks for a line like
  21801. #+BIBLIOGRAPHY: foo plain option:-d
  21802. and derives from it that foo.bib is the bibliography file relevant
  21803. for this document. It then installs the necessary environment for RefTeX
  21804. to work in this buffer and calls `reftex-citation' to insert a citation
  21805. into the buffer.
  21806. Export of such citations to both LaTeX and HTML is handled by the contributed
  21807. package ox-bibtex by Taru Karttunen."
  21808. (interactive)
  21809. (let ((reftex-docstruct-symbol 'org--rds)
  21810. (reftex-cite-format "\\cite{%l}")
  21811. org--rds bib)
  21812. (save-excursion
  21813. (save-restriction
  21814. (widen)
  21815. (let ((case-fold-search t)
  21816. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21817. (if (not (save-excursion
  21818. (or (re-search-forward re nil t)
  21819. (re-search-backward re nil t))))
  21820. (user-error "No bibliography defined in file")
  21821. (setq bib (concat (match-string 1) ".bib")
  21822. org--rds (list (list 'bib bib)))))))
  21823. (call-interactively 'reftex-citation)))
  21824. ;;;; Functions extending outline functionality
  21825. (defun org-beginning-of-line (&optional arg)
  21826. "Go to the beginning of the current line. If that is invisible, continue
  21827. to a visible line beginning. This makes the function of C-a more intuitive.
  21828. If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
  21829. first attempt, and only move to after the tags when the cursor is already
  21830. beyond the end of the headline."
  21831. (interactive "P")
  21832. (let ((pos (point))
  21833. (special (if (consp org-special-ctrl-a/e)
  21834. (car org-special-ctrl-a/e)
  21835. org-special-ctrl-a/e))
  21836. deactivate-mark refpos)
  21837. (call-interactively (if (bound-and-true-p visual-line-mode)
  21838. #'beginning-of-visual-line
  21839. #'move-beginning-of-line))
  21840. (cond
  21841. ((or arg (not special)))
  21842. ((and (looking-at org-complex-heading-regexp)
  21843. (eq (char-after (match-end 1)) ?\s))
  21844. (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21845. (point-at-eol)))
  21846. (goto-char
  21847. (if (eq special t)
  21848. (cond ((> pos refpos) refpos)
  21849. ((= pos (point)) refpos)
  21850. (t (point)))
  21851. (cond ((> pos (point)) (point))
  21852. ((not (eq last-command this-command)) (point))
  21853. (t refpos)))))
  21854. ((org-at-item-p)
  21855. ;; Being at an item and not looking at an the item means point
  21856. ;; was previously moved to beginning of a visual line, which
  21857. ;; doesn't contain the item. Therefore, do nothing special,
  21858. ;; just stay here.
  21859. (when (looking-at org-list-full-item-re)
  21860. ;; Set special position at first white space character after
  21861. ;; bullet, and check-box, if any.
  21862. (let ((after-bullet
  21863. (let ((box (match-end 3)))
  21864. (if (not box) (match-end 1)
  21865. (let ((after (char-after box)))
  21866. (if (and after (= after ? )) (1+ box) box))))))
  21867. ;; Special case: Move point to special position when
  21868. ;; currently after it or at beginning of line.
  21869. (if (eq special t)
  21870. (when (or (> pos after-bullet) (= (point) pos))
  21871. (goto-char after-bullet))
  21872. ;; Reversed case: Move point to special position when
  21873. ;; point was already at beginning of line and command is
  21874. ;; repeated.
  21875. (when (and (= (point) pos) (eq last-command this-command))
  21876. (goto-char after-bullet))))))))
  21877. (setq disable-point-adjustment
  21878. (or (not (invisible-p (point)))
  21879. (not (invisible-p (max (point-min) (1- (point))))))))
  21880. (defun org-end-of-line (&optional arg)
  21881. "Go to the end of the line.
  21882. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21883. tags on the first attempt, and only move to after the tags when
  21884. the cursor is already beyond the end of the headline."
  21885. (interactive "P")
  21886. (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
  21887. org-special-ctrl-a/e))
  21888. (move-fun (cond ((bound-and-true-p visual-line-mode)
  21889. 'end-of-visual-line)
  21890. ((fboundp 'move-end-of-line) 'move-end-of-line)
  21891. (t 'end-of-line)))
  21892. deactivate-mark)
  21893. (if (or (not special) arg) (call-interactively move-fun)
  21894. (let* ((element (save-excursion (beginning-of-line)
  21895. (org-element-at-point)))
  21896. (type (org-element-type element)))
  21897. (cond
  21898. ((memq type '(headline inlinetask))
  21899. (let ((pos (point)))
  21900. (beginning-of-line 1)
  21901. (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
  21902. (if (eq special t)
  21903. (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
  21904. (goto-char (match-beginning 1))
  21905. (goto-char (match-end 0)))
  21906. (if (or (< pos (match-end 0))
  21907. (not (eq this-command last-command)))
  21908. (goto-char (match-end 0))
  21909. (goto-char (match-beginning 1))))
  21910. (call-interactively move-fun))))
  21911. ((outline-invisible-p (line-end-position))
  21912. ;; If element is hidden, `move-end-of-line' would put point
  21913. ;; after it. Use `end-of-line' to stay on current line.
  21914. (call-interactively 'end-of-line))
  21915. (t (call-interactively move-fun))))))
  21916. (setq disable-point-adjustment
  21917. (or (not (invisible-p (point)))
  21918. (not (invisible-p (max (point-min) (1- (point))))))))
  21919. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21920. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21921. (defun org-backward-sentence (&optional _arg)
  21922. "Go to beginning of sentence, or beginning of table field.
  21923. This will call `backward-sentence' or `org-table-beginning-of-field',
  21924. depending on context."
  21925. (interactive)
  21926. (let* ((element (org-element-at-point))
  21927. (contents-begin (org-element-property :contents-begin element))
  21928. (table (org-element-lineage element '(table) t)))
  21929. (if (and table
  21930. (> (point) contents-begin)
  21931. (<= (point) (org-element-property :contents-end table)))
  21932. (call-interactively #'org-table-beginning-of-field)
  21933. (save-restriction
  21934. (when (and contents-begin
  21935. (< (point-min) contents-begin)
  21936. (> (point) contents-begin))
  21937. (narrow-to-region contents-begin
  21938. (org-element-property :contents-end element)))
  21939. (call-interactively #'backward-sentence)))))
  21940. (defun org-forward-sentence (&optional _arg)
  21941. "Go to end of sentence, or end of table field.
  21942. This will call `forward-sentence' or `org-table-end-of-field',
  21943. depending on context."
  21944. (interactive)
  21945. (let* ((element (org-element-at-point))
  21946. (contents-end (org-element-property :contents-end element))
  21947. (table (org-element-lineage element '(table) t)))
  21948. (if (and table
  21949. (>= (point) (org-element-property :contents-begin table))
  21950. (< (point) contents-end))
  21951. (call-interactively #'org-table-end-of-field)
  21952. (save-restriction
  21953. (when (and contents-end
  21954. (> (point-max) contents-end)
  21955. ;; Skip blank lines between elements.
  21956. (< (org-element-property :end element)
  21957. (save-excursion (goto-char contents-end)
  21958. (skip-chars-forward " \r\t\n"))))
  21959. (narrow-to-region (org-element-property :contents-begin element)
  21960. contents-end))
  21961. (call-interactively #'forward-sentence)))))
  21962. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21963. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21964. (defun org-kill-line (&optional _arg)
  21965. "Kill line, to tags or end of line."
  21966. (interactive)
  21967. (cond
  21968. ((or (not org-special-ctrl-k)
  21969. (bolp)
  21970. (not (org-at-heading-p)))
  21971. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21972. org-ctrl-k-protect-subtree
  21973. (or (eq org-ctrl-k-protect-subtree 'error)
  21974. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21975. (user-error "C-k aborted as it would kill a hidden subtree"))
  21976. (call-interactively
  21977. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21978. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21979. (kill-region (point) (match-beginning 1))
  21980. (org-set-tags nil t))
  21981. (t (kill-region (point) (point-at-eol)))))
  21982. (define-key org-mode-map "\C-k" 'org-kill-line)
  21983. (defun org-yank (&optional arg)
  21984. "Yank. If the kill is a subtree, treat it specially.
  21985. This command will look at the current kill and check if is a single
  21986. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21987. cursor is at the beginning of a line or after the stars of a currently
  21988. empty headline, then the yank is handled specially. How exactly depends
  21989. on the value of the following variables.
  21990. `org-yank-folded-subtrees'
  21991. By default, this variable is non-nil, which results in subtree(s)
  21992. being folded after insertion, but only if doing so would now
  21993. swallow text after the yanked text.
  21994. `org-yank-adjusted-subtrees'
  21995. When non-nil (the default value is nil), the subtree will be
  21996. promoted or demoted in order to fit into the local outline tree
  21997. structure, which means that the level will be adjusted so that it
  21998. becomes the smaller one of the two *visible* surrounding headings.
  21999. Any prefix to this command will cause `yank' to be called directly with
  22000. no special treatment. In particular, a simple \\[universal-argument] prefix \
  22001. will just
  22002. plainly yank the text as it is.
  22003. \[1] The test checks if the first non-white line is a heading
  22004. and if there are no other headings with fewer stars."
  22005. (interactive "P")
  22006. (org-yank-generic 'yank arg))
  22007. (defun org-yank-generic (command arg)
  22008. "Perform some yank-like command.
  22009. This function implements the behavior described in the `org-yank'
  22010. documentation. However, it has been generalized to work for any
  22011. interactive command with similar behavior."
  22012. ;; pretend to be command COMMAND
  22013. (setq this-command command)
  22014. (if arg
  22015. (call-interactively command)
  22016. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  22017. (and (org-kill-is-subtree-p)
  22018. (or (bolp)
  22019. (and (looking-at "[ \t]*$")
  22020. (string-match
  22021. "\\`\\*+\\'"
  22022. (buffer-substring (point-at-bol) (point)))))))
  22023. swallowp)
  22024. (cond
  22025. ((and subtreep org-yank-folded-subtrees)
  22026. (let ((beg (point))
  22027. end)
  22028. (if (and subtreep org-yank-adjusted-subtrees)
  22029. (org-paste-subtree nil nil 'for-yank)
  22030. (call-interactively command))
  22031. (setq end (point))
  22032. (goto-char beg)
  22033. (when (and (bolp) subtreep
  22034. (not (setq swallowp
  22035. (org-yank-folding-would-swallow-text beg end))))
  22036. (org-with-limited-levels
  22037. (or (looking-at org-outline-regexp)
  22038. (re-search-forward org-outline-regexp-bol end t))
  22039. (while (and (< (point) end) (looking-at org-outline-regexp))
  22040. (outline-hide-subtree)
  22041. (org-cycle-show-empty-lines 'folded)
  22042. (condition-case nil
  22043. (outline-forward-same-level 1)
  22044. (error (goto-char end))))))
  22045. (when swallowp
  22046. (message
  22047. "Inserted text not folded because that would swallow text"))
  22048. (goto-char end)
  22049. (skip-chars-forward " \t\n\r")
  22050. (beginning-of-line 1)
  22051. (push-mark beg 'nomsg)))
  22052. ((and subtreep org-yank-adjusted-subtrees)
  22053. (let ((beg (point-at-bol)))
  22054. (org-paste-subtree nil nil 'for-yank)
  22055. (push-mark beg 'nomsg)))
  22056. (t
  22057. (call-interactively command))))))
  22058. (defun org-yank-folding-would-swallow-text (beg end)
  22059. "Would hide-subtree at BEG swallow any text after END?"
  22060. (let (level)
  22061. (org-with-limited-levels
  22062. (save-excursion
  22063. (goto-char beg)
  22064. (when (or (looking-at org-outline-regexp)
  22065. (re-search-forward org-outline-regexp-bol end t))
  22066. (setq level (org-outline-level)))
  22067. (goto-char end)
  22068. (skip-chars-forward " \t\r\n\v\f")
  22069. (not (or (eobp)
  22070. (and (bolp) (looking-at-p org-outline-regexp)
  22071. (<= (org-outline-level) level))))))))
  22072. (define-key org-mode-map "\C-y" 'org-yank)
  22073. (defun org-truely-invisible-p ()
  22074. "Check if point is at a character currently not visible.
  22075. This version does not only check the character property, but also
  22076. `visible-mode'."
  22077. ;; Early versions of noutline don't have `outline-invisible-p'.
  22078. (unless (bound-and-true-p visible-mode)
  22079. (outline-invisible-p)))
  22080. (defun org-invisible-p2 ()
  22081. "Check if point is at a character currently not visible."
  22082. (save-excursion
  22083. (when (and (eolp) (not (bobp))) (backward-char 1))
  22084. ;; Early versions of noutline don't have `outline-invisible-p'.
  22085. (outline-invisible-p)))
  22086. (defun org-back-to-heading (&optional invisible-ok)
  22087. "Call `outline-back-to-heading', but provide a better error message."
  22088. (condition-case nil
  22089. (outline-back-to-heading invisible-ok)
  22090. (error (error "Before first headline at position %d in buffer %s"
  22091. (point) (current-buffer)))))
  22092. (defun org-before-first-heading-p ()
  22093. "Before first heading?"
  22094. (save-excursion
  22095. (end-of-line)
  22096. (null (re-search-backward org-outline-regexp-bol nil t))))
  22097. (defun org-at-heading-p (&optional ignored)
  22098. (outline-on-heading-p t))
  22099. (defun org-in-commented-heading-p (&optional no-inheritance)
  22100. "Non-nil if point is under a commented heading.
  22101. This function also checks ancestors of the current headline,
  22102. unless optional argument NO-INHERITANCE is non-nil."
  22103. (cond
  22104. ((org-before-first-heading-p) nil)
  22105. ((let ((headline (nth 4 (org-heading-components))))
  22106. (and headline
  22107. (let ((case-fold-search nil))
  22108. (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22109. headline)))))
  22110. (no-inheritance nil)
  22111. (t
  22112. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22113. (defun org-at-comment-p nil
  22114. "Is cursor in a commented line?"
  22115. (save-excursion
  22116. (save-match-data
  22117. (beginning-of-line)
  22118. (looking-at "^[ \t]*# "))))
  22119. (defun org-at-drawer-p nil
  22120. "Is cursor at a drawer keyword?"
  22121. (save-excursion
  22122. (move-beginning-of-line 1)
  22123. (looking-at org-drawer-regexp)))
  22124. (defun org-at-block-p nil
  22125. "Is cursor at a block keyword?"
  22126. (save-excursion
  22127. (move-beginning-of-line 1)
  22128. (looking-at org-block-regexp)))
  22129. (defun org-point-at-end-of-empty-headline ()
  22130. "If point is at the end of an empty headline, return t, else nil.
  22131. If the heading only contains a TODO keyword, it is still still considered
  22132. empty."
  22133. (and (looking-at "[ \t]*$")
  22134. (when org-todo-line-regexp
  22135. (save-excursion
  22136. (beginning-of-line 1)
  22137. (let ((case-fold-search nil))
  22138. (looking-at org-todo-line-regexp)
  22139. (string= (match-string 3) ""))))))
  22140. (defun org-at-heading-or-item-p ()
  22141. (or (org-at-heading-p) (org-at-item-p)))
  22142. (defun org-at-target-p ()
  22143. (or (org-in-regexp org-radio-target-regexp)
  22144. (org-in-regexp org-target-regexp)))
  22145. ;; Compatibility alias with Org versions < 7.8.03
  22146. (defalias 'org-on-target-p 'org-at-target-p)
  22147. (defun org-up-heading-all (arg)
  22148. "Move to the heading line of which the present line is a subheading.
  22149. This function considers both visible and invisible heading lines.
  22150. With argument, move up ARG levels."
  22151. (outline-up-heading arg t))
  22152. (defun org-up-heading-safe ()
  22153. "Move to the heading line of which the present line is a subheading.
  22154. This version will not throw an error. It will return the level of the
  22155. headline found, or nil if no higher level is found.
  22156. Also, this function will be a lot faster than `outline-up-heading',
  22157. because it relies on stars being the outline starters. This can really
  22158. make a significant difference in outlines with very many siblings."
  22159. (when (ignore-errors (org-back-to-heading t))
  22160. (let ((level-up (1- (funcall outline-level))))
  22161. (and (> level-up 0)
  22162. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22163. (funcall outline-level)))))
  22164. (defun org-first-sibling-p ()
  22165. "Is this heading the first child of its parents?"
  22166. (interactive)
  22167. (let ((re org-outline-regexp-bol)
  22168. level l)
  22169. (unless (org-at-heading-p t)
  22170. (user-error "Not at a heading"))
  22171. (setq level (funcall outline-level))
  22172. (save-excursion
  22173. (if (not (re-search-backward re nil t))
  22174. t
  22175. (setq l (funcall outline-level))
  22176. (< l level)))))
  22177. (defun org-goto-sibling (&optional previous)
  22178. "Goto the next sibling, even if it is invisible.
  22179. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22180. when a sibling was found. When none is found, return nil and don't
  22181. move point."
  22182. (let ((fun (if previous 're-search-backward 're-search-forward))
  22183. (pos (point))
  22184. (re org-outline-regexp-bol)
  22185. level l)
  22186. (when (ignore-errors (org-back-to-heading t))
  22187. (setq level (funcall outline-level))
  22188. (catch 'exit
  22189. (or previous (forward-char 1))
  22190. (while (funcall fun re nil t)
  22191. (setq l (funcall outline-level))
  22192. (when (< l level) (goto-char pos) (throw 'exit nil))
  22193. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22194. (goto-char pos)
  22195. nil))))
  22196. (defun org-show-siblings ()
  22197. "Show all siblings of the current headline."
  22198. (save-excursion
  22199. (while (org-goto-sibling) (org-flag-heading nil)))
  22200. (save-excursion
  22201. (while (org-goto-sibling 'previous)
  22202. (org-flag-heading nil))))
  22203. (defun org-goto-first-child ()
  22204. "Goto the first child, even if it is invisible.
  22205. Return t when a child was found. Otherwise don't move point and
  22206. return nil."
  22207. (let (level (pos (point)) (re org-outline-regexp-bol))
  22208. (when (ignore-errors (org-back-to-heading t))
  22209. (setq level (outline-level))
  22210. (forward-char 1)
  22211. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22212. (progn (goto-char (match-beginning 0)) t)
  22213. (goto-char pos) nil))))
  22214. (defun org-show-hidden-entry ()
  22215. "Show an entry where even the heading is hidden."
  22216. (save-excursion
  22217. (org-show-entry)))
  22218. (defun org-flag-heading (flag &optional entry)
  22219. "Flag the current heading. FLAG non-nil means make invisible.
  22220. When ENTRY is non-nil, show the entire entry."
  22221. (save-excursion
  22222. (org-back-to-heading t)
  22223. ;; Check if we should show the entire entry
  22224. (if entry
  22225. (progn
  22226. (org-show-entry)
  22227. (save-excursion
  22228. (and (outline-next-heading)
  22229. (org-flag-heading nil))))
  22230. (outline-flag-region (max (point-min) (1- (point)))
  22231. (save-excursion (outline-end-of-heading) (point))
  22232. flag))))
  22233. (defun org-get-next-sibling ()
  22234. "Move to next heading of the same level, and return point.
  22235. If there is no such heading, return nil.
  22236. This is like outline-next-sibling, but invisible headings are ok."
  22237. (let ((level (funcall outline-level)))
  22238. (outline-next-heading)
  22239. (while (and (not (eobp)) (> (funcall outline-level) level))
  22240. (outline-next-heading))
  22241. (unless (or (eobp) (< (funcall outline-level) level))
  22242. (point))))
  22243. (defun org-get-last-sibling ()
  22244. "Move to previous heading of the same level, and return point.
  22245. If there is no such heading, return nil."
  22246. (let ((opoint (point))
  22247. (level (funcall outline-level)))
  22248. (outline-previous-heading)
  22249. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22250. (while (and (> (funcall outline-level) level)
  22251. (not (bobp)))
  22252. (outline-previous-heading))
  22253. (unless (< (funcall outline-level) level)
  22254. (point)))))
  22255. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22256. "Goto to the end of a subtree."
  22257. ;; This contains an exact copy of the original function, but it uses
  22258. ;; `org-back-to-heading', to make it work also in invisible
  22259. ;; trees. And is uses an invisible-ok argument.
  22260. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22261. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22262. ;; with many children and grandchildren etc, this can be much faster
  22263. ;; than the outline version.
  22264. (org-back-to-heading invisible-ok)
  22265. (let ((first t)
  22266. (level (funcall outline-level)))
  22267. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22268. ;; A true heading (not a plain list item), in Org-mode
  22269. ;; This means we can easily find the end by looking
  22270. ;; only for the right number of stars. Using a regexp to do
  22271. ;; this is so much faster than using a Lisp loop.
  22272. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22273. (forward-char 1)
  22274. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22275. ;; something else, do it the slow way
  22276. (while (and (not (eobp))
  22277. (or first (> (funcall outline-level) level)))
  22278. (setq first nil)
  22279. (outline-next-heading)))
  22280. (unless to-heading
  22281. (when (memq (preceding-char) '(?\n ?\^M))
  22282. ;; Go to end of line before heading
  22283. (forward-char -1)
  22284. (when (memq (preceding-char) '(?\n ?\^M))
  22285. ;; leave blank line before heading
  22286. (forward-char -1)))))
  22287. (point))
  22288. (defun org-end-of-meta-data (&optional full)
  22289. "Skip planning line and properties drawer in current entry.
  22290. When optional argument FULL is non-nil, also skip empty lines,
  22291. clocking lines and regular drawers at the beginning of the
  22292. entry."
  22293. (org-back-to-heading t)
  22294. (forward-line)
  22295. (when (looking-at-p org-planning-line-re) (forward-line))
  22296. (when (looking-at org-property-drawer-re)
  22297. (goto-char (match-end 0))
  22298. (forward-line))
  22299. (when (and full (not (org-at-heading-p)))
  22300. (catch 'exit
  22301. (let ((end (save-excursion (outline-next-heading) (point)))
  22302. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22303. (while (not (eobp))
  22304. (cond ((looking-at-p org-drawer-regexp)
  22305. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22306. (forward-line)
  22307. (throw 'exit t)))
  22308. ((looking-at-p re) (forward-line))
  22309. (t (throw 'exit t))))))))
  22310. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22311. "Move forward to the ARG'th subheading at same level as this one.
  22312. Stop at the first and last subheadings of a superior heading.
  22313. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22314. non-nil it will also look at invisible ones."
  22315. (interactive "p")
  22316. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22317. (if (and arg (< arg 0))
  22318. (goto-char (point-min))
  22319. (outline-next-heading))
  22320. (org-at-heading-p)
  22321. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22322. (f (if (and arg (< arg 0))
  22323. 're-search-backward
  22324. 're-search-forward))
  22325. (count (if arg (abs arg) 1))
  22326. (result (point)))
  22327. (while (and (prog1 (> count 0)
  22328. (forward-char (if (and arg (< arg 0)) -1 1)))
  22329. (funcall f org-outline-regexp-bol nil 'move))
  22330. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22331. (cond ((< l level) (setq count 0))
  22332. ((and (= l level)
  22333. (or invisible-ok
  22334. (progn
  22335. (goto-char (line-beginning-position))
  22336. (not (outline-invisible-p)))))
  22337. (setq count (1- count))
  22338. (when (eq l level)
  22339. (setq result (point)))))))
  22340. (goto-char result))
  22341. (beginning-of-line 1)))
  22342. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22343. "Move backward to the ARG'th subheading at same level as this one.
  22344. Stop at the first and last subheadings of a superior heading."
  22345. (interactive "p")
  22346. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22347. (defun org-next-visible-heading (arg)
  22348. "Move to the next visible heading.
  22349. This function wraps `outline-next-visible-heading' with
  22350. `org-with-limited-levels' in order to skip over inline tasks and
  22351. respect customization of `org-odd-levels-only'."
  22352. (interactive "p")
  22353. (org-with-limited-levels
  22354. (outline-next-visible-heading arg)))
  22355. (defun org-previous-visible-heading (arg)
  22356. "Move to the previous visible heading.
  22357. This function wraps `outline-previous-visible-heading' with
  22358. `org-with-limited-levels' in order to skip over inline tasks and
  22359. respect customization of `org-odd-levels-only'."
  22360. (interactive "p")
  22361. (org-with-limited-levels
  22362. (outline-previous-visible-heading arg)))
  22363. (defun org-next-block (arg &optional backward block-regexp)
  22364. "Jump to the next block.
  22365. With a prefix argument ARG, jump forward ARG many blocks.
  22366. When BACKWARD is non-nil, jump to the previous block.
  22367. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22368. Match data is set according to this regexp when the function
  22369. returns.
  22370. Return point at beginning of the opening line of found block.
  22371. Throw an error if no block is found."
  22372. (interactive "p")
  22373. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22374. (case-fold-search t)
  22375. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22376. (count (or arg 1))
  22377. (origin (point))
  22378. last-element)
  22379. (if backward (beginning-of-line) (end-of-line))
  22380. (while (and (> count 0) (funcall search-fn re nil t))
  22381. (let ((element (save-excursion
  22382. (goto-char (match-beginning 0))
  22383. (save-match-data (org-element-at-point)))))
  22384. (when (and (memq (org-element-type element)
  22385. '(center-block comment-block dynamic-block
  22386. example-block export-block quote-block
  22387. special-block src-block verse-block))
  22388. (<= (match-beginning 0)
  22389. (org-element-property :post-affiliated element)))
  22390. (setq last-element element)
  22391. (cl-decf count))))
  22392. (if (= count 0)
  22393. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22394. (save-match-data (org-show-context)))
  22395. (goto-char origin)
  22396. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22397. (defun org-previous-block (arg &optional block-regexp)
  22398. "Jump to the previous block.
  22399. With a prefix argument ARG, jump backward ARG many source blocks.
  22400. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22401. (interactive "p")
  22402. (org-next-block arg t block-regexp))
  22403. (defun org-forward-paragraph ()
  22404. "Move forward to beginning of next paragraph or equivalent.
  22405. The function moves point to the beginning of the next visible
  22406. structural element, which can be a paragraph, a table, a list
  22407. item, etc. It also provides some special moves for convenience:
  22408. - On an affiliated keyword, jump to the beginning of the
  22409. relative element.
  22410. - On an item or a footnote definition, move to the second
  22411. element inside, if any.
  22412. - On a table or a property drawer, jump after it.
  22413. - On a verse or source block, stop after blank lines."
  22414. (interactive)
  22415. (when (eobp) (user-error "Cannot move further down"))
  22416. (let* ((deactivate-mark nil)
  22417. (element (org-element-at-point))
  22418. (type (org-element-type element))
  22419. (post-affiliated (org-element-property :post-affiliated element))
  22420. (contents-begin (org-element-property :contents-begin element))
  22421. (contents-end (org-element-property :contents-end element))
  22422. (end (let ((end (org-element-property :end element)) (parent element))
  22423. (while (and (setq parent (org-element-property :parent parent))
  22424. (= (org-element-property :contents-end parent) end))
  22425. (setq end (org-element-property :end parent)))
  22426. end)))
  22427. (cond ((not element)
  22428. (skip-chars-forward " \r\t\n")
  22429. (or (eobp) (beginning-of-line)))
  22430. ;; On affiliated keywords, move to element's beginning.
  22431. ((< (point) post-affiliated)
  22432. (goto-char post-affiliated))
  22433. ;; At a table row, move to the end of the table. Similarly,
  22434. ;; at a node property, move to the end of the property
  22435. ;; drawer.
  22436. ((memq type '(node-property table-row))
  22437. (goto-char (org-element-property
  22438. :end (org-element-property :parent element))))
  22439. ((memq type '(property-drawer table)) (goto-char end))
  22440. ;; Consider blank lines as separators in verse and source
  22441. ;; blocks to ease editing.
  22442. ((memq type '(src-block verse-block))
  22443. (when (eq type 'src-block)
  22444. (setq contents-end
  22445. (save-excursion (goto-char end)
  22446. (skip-chars-backward " \r\t\n")
  22447. (line-beginning-position))))
  22448. (beginning-of-line)
  22449. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22450. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22451. (goto-char end)
  22452. (skip-chars-forward " \r\t\n")
  22453. (if (= (point) contents-end) (goto-char end)
  22454. (beginning-of-line))))
  22455. ;; With no contents, just skip element.
  22456. ((not contents-begin) (goto-char end))
  22457. ;; If contents are invisible, skip the element altogether.
  22458. ((outline-invisible-p (line-end-position))
  22459. (cl-case type
  22460. (headline
  22461. (org-with-limited-levels (outline-next-visible-heading 1)))
  22462. ;; At a plain list, make sure we move to the next item
  22463. ;; instead of skipping the whole list.
  22464. (plain-list (forward-char)
  22465. (org-forward-paragraph))
  22466. (otherwise (goto-char end))))
  22467. ((>= (point) contents-end) (goto-char end))
  22468. ((>= (point) contents-begin)
  22469. ;; This can only happen on paragraphs and plain lists.
  22470. (cl-case type
  22471. (paragraph (goto-char end))
  22472. ;; At a plain list, try to move to second element in
  22473. ;; first item, if possible.
  22474. (plain-list (end-of-line)
  22475. (org-forward-paragraph))))
  22476. ;; When contents start on the middle of a line (e.g. in
  22477. ;; items and footnote definitions), try to reach first
  22478. ;; element starting after current line.
  22479. ((> (line-end-position) contents-begin)
  22480. (end-of-line)
  22481. (org-forward-paragraph))
  22482. (t (goto-char contents-begin)))))
  22483. (defun org-backward-paragraph ()
  22484. "Move backward to start of previous paragraph or equivalent.
  22485. The function moves point to the beginning of the current
  22486. structural element, which can be a paragraph, a table, a list
  22487. item, etc., or to the beginning of the previous visible one if
  22488. point is already there. It also provides some special moves for
  22489. convenience:
  22490. - On an affiliated keyword, jump to the first one.
  22491. - On a table or a property drawer, move to its beginning.
  22492. - On a verse or source block, stop before blank lines."
  22493. (interactive)
  22494. (when (bobp) (user-error "Cannot move further up"))
  22495. (let* ((deactivate-mark nil)
  22496. (element (org-element-at-point))
  22497. (type (org-element-type element))
  22498. (contents-begin (org-element-property :contents-begin element))
  22499. (contents-end (org-element-property :contents-end element))
  22500. (post-affiliated (org-element-property :post-affiliated element))
  22501. (begin (org-element-property :begin element)))
  22502. (cond
  22503. ((not element) (goto-char (point-min)))
  22504. ((= (point) begin)
  22505. (backward-char)
  22506. (org-backward-paragraph))
  22507. ((<= (point) post-affiliated) (goto-char begin))
  22508. ((memq type '(node-property table-row))
  22509. (goto-char (org-element-property
  22510. :post-affiliated (org-element-property :parent element))))
  22511. ((memq type '(property-drawer table)) (goto-char begin))
  22512. ((memq type '(src-block verse-block))
  22513. (when (eq type 'src-block)
  22514. (setq contents-begin
  22515. (save-excursion (goto-char begin) (forward-line) (point))))
  22516. (if (= (point) contents-begin) (goto-char post-affiliated)
  22517. ;; Inside a verse block, see blank lines as paragraph
  22518. ;; separators.
  22519. (let ((origin (point)))
  22520. (skip-chars-backward " \r\t\n" contents-begin)
  22521. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22522. (skip-chars-forward " \r\t\n" origin)
  22523. (if (= (point) origin) (goto-char contents-begin)
  22524. (beginning-of-line))))))
  22525. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22526. ((eq type 'paragraph)
  22527. (goto-char contents-begin)
  22528. ;; When at first paragraph in an item or a footnote definition,
  22529. ;; move directly to beginning of line.
  22530. (let ((parent-contents
  22531. (org-element-property
  22532. :contents-begin (org-element-property :parent element))))
  22533. (when (and parent-contents (= parent-contents contents-begin))
  22534. (beginning-of-line))))
  22535. ;; At the end of a greater element, move to the beginning of the
  22536. ;; last element within.
  22537. ((>= (point) contents-end)
  22538. (goto-char (1- contents-end))
  22539. (org-backward-paragraph))
  22540. (t (goto-char (or post-affiliated begin))))
  22541. ;; Ensure we never leave point invisible.
  22542. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22543. (defun org-forward-element ()
  22544. "Move forward by one element.
  22545. Move to the next element at the same level, when possible."
  22546. (interactive)
  22547. (cond ((eobp) (user-error "Cannot move further down"))
  22548. ((org-with-limited-levels (org-at-heading-p))
  22549. (let ((origin (point)))
  22550. (goto-char (org-end-of-subtree nil t))
  22551. (unless (org-with-limited-levels (org-at-heading-p))
  22552. (goto-char origin)
  22553. (user-error "Cannot move further down"))))
  22554. (t
  22555. (let* ((elem (org-element-at-point))
  22556. (end (org-element-property :end elem))
  22557. (parent (org-element-property :parent elem)))
  22558. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22559. (goto-char (org-element-property :end parent)))
  22560. ((integer-or-marker-p end) (goto-char end))
  22561. (t (message "No element at point")))))))
  22562. (defun org-backward-element ()
  22563. "Move backward by one element.
  22564. Move to the previous element at the same level, when possible."
  22565. (interactive)
  22566. (cond ((bobp) (user-error "Cannot move further up"))
  22567. ((org-with-limited-levels (org-at-heading-p))
  22568. ;; At a headline, move to the previous one, if any, or stay
  22569. ;; here.
  22570. (let ((origin (point)))
  22571. (org-with-limited-levels (org-backward-heading-same-level 1))
  22572. ;; When current headline has no sibling above, move to its
  22573. ;; parent.
  22574. (when (= (point) origin)
  22575. (or (org-with-limited-levels (org-up-heading-safe))
  22576. (progn (goto-char origin)
  22577. (user-error "Cannot move further up"))))))
  22578. (t
  22579. (let* ((elem (org-element-at-point))
  22580. (beg (org-element-property :begin elem)))
  22581. (cond
  22582. ;; Move to beginning of current element if point isn't
  22583. ;; there already.
  22584. ((null beg) (message "No element at point"))
  22585. ((/= (point) beg) (goto-char beg))
  22586. (t (goto-char beg)
  22587. (skip-chars-backward " \r\t\n")
  22588. (unless (bobp)
  22589. (let ((prev (org-element-at-point)))
  22590. (goto-char (org-element-property :begin prev))
  22591. (while (and (setq prev (org-element-property :parent prev))
  22592. (<= (org-element-property :end prev) beg))
  22593. (goto-char (org-element-property :begin prev)))))))))))
  22594. (defun org-up-element ()
  22595. "Move to upper element."
  22596. (interactive)
  22597. (if (org-with-limited-levels (org-at-heading-p))
  22598. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22599. (let* ((elem (org-element-at-point))
  22600. (parent (org-element-property :parent elem)))
  22601. (if parent (goto-char (org-element-property :begin parent))
  22602. (if (org-with-limited-levels (org-before-first-heading-p))
  22603. (user-error "No surrounding element")
  22604. (org-with-limited-levels (org-back-to-heading)))))))
  22605. (defvar org-element-greater-elements)
  22606. (defun org-down-element ()
  22607. "Move to inner element."
  22608. (interactive)
  22609. (let ((element (org-element-at-point)))
  22610. (cond
  22611. ((memq (org-element-type element) '(plain-list table))
  22612. (goto-char (org-element-property :contents-begin element))
  22613. (forward-char))
  22614. ((memq (org-element-type element) org-element-greater-elements)
  22615. ;; If contents are hidden, first disclose them.
  22616. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22617. (goto-char (or (org-element-property :contents-begin element)
  22618. (user-error "No content for this element"))))
  22619. (t (user-error "No inner element")))))
  22620. (defun org-drag-element-backward ()
  22621. "Move backward element at point."
  22622. (interactive)
  22623. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22624. (let* ((elem (org-element-at-point))
  22625. (prev-elem
  22626. (save-excursion
  22627. (goto-char (org-element-property :begin elem))
  22628. (skip-chars-backward " \r\t\n")
  22629. (unless (bobp)
  22630. (let* ((beg (org-element-property :begin elem))
  22631. (prev (org-element-at-point))
  22632. (up prev))
  22633. (while (and (setq up (org-element-property :parent up))
  22634. (<= (org-element-property :end up) beg))
  22635. (setq prev up))
  22636. prev)))))
  22637. ;; Error out if no previous element or previous element is
  22638. ;; a parent of the current one.
  22639. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22640. (user-error "Cannot drag element backward")
  22641. (let ((pos (point)))
  22642. (org-element-swap-A-B prev-elem elem)
  22643. (goto-char (+ (org-element-property :begin prev-elem)
  22644. (- pos (org-element-property :begin elem)))))))))
  22645. (defun org-drag-element-forward ()
  22646. "Move forward element at point."
  22647. (interactive)
  22648. (let* ((pos (point))
  22649. (elem (org-element-at-point)))
  22650. (when (= (point-max) (org-element-property :end elem))
  22651. (user-error "Cannot drag element forward"))
  22652. (goto-char (org-element-property :end elem))
  22653. (let ((next-elem (org-element-at-point)))
  22654. (when (or (org-element-nested-p elem next-elem)
  22655. (and (eq (org-element-type next-elem) 'headline)
  22656. (not (eq (org-element-type elem) 'headline))))
  22657. (goto-char pos)
  22658. (user-error "Cannot drag element forward"))
  22659. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22660. ;; body's length (without final blanks) and by the length of
  22661. ;; blanks between ELEM and NEXT-ELEM.
  22662. (let ((size-next (- (save-excursion
  22663. (goto-char (org-element-property :end next-elem))
  22664. (skip-chars-backward " \r\t\n")
  22665. (forward-line)
  22666. ;; Small correction if buffer doesn't end
  22667. ;; with a newline character.
  22668. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22669. (org-element-property :begin next-elem)))
  22670. (size-blank (- (org-element-property :end elem)
  22671. (save-excursion
  22672. (goto-char (org-element-property :end elem))
  22673. (skip-chars-backward " \r\t\n")
  22674. (forward-line)
  22675. (point)))))
  22676. (org-element-swap-A-B elem next-elem)
  22677. (goto-char (+ pos size-next size-blank))))))
  22678. (defun org-drag-line-forward (arg)
  22679. "Drag the line at point ARG lines forward."
  22680. (interactive "p")
  22681. (dotimes (_ (abs arg))
  22682. (let ((c (current-column)))
  22683. (if (< 0 arg)
  22684. (progn
  22685. (beginning-of-line 2)
  22686. (transpose-lines 1)
  22687. (beginning-of-line 0))
  22688. (transpose-lines 1)
  22689. (beginning-of-line -1))
  22690. (org-move-to-column c))))
  22691. (defun org-drag-line-backward (arg)
  22692. "Drag the line at point ARG lines backward."
  22693. (interactive "p")
  22694. (org-drag-line-forward (- arg)))
  22695. (defun org-mark-element ()
  22696. "Put point at beginning of this element, mark at end.
  22697. Interactively, if this command is repeated or (in Transient Mark
  22698. mode) if the mark is active, it marks the next element after the
  22699. ones already marked."
  22700. (interactive)
  22701. (let (deactivate-mark)
  22702. (if (and (called-interactively-p 'any)
  22703. (or (and (eq last-command this-command) (mark t))
  22704. (and transient-mark-mode mark-active)))
  22705. (set-mark
  22706. (save-excursion
  22707. (goto-char (mark))
  22708. (goto-char (org-element-property :end (org-element-at-point)))))
  22709. (let ((element (org-element-at-point)))
  22710. (end-of-line)
  22711. (push-mark (org-element-property :end element) t t)
  22712. (goto-char (org-element-property :begin element))))))
  22713. (defun org-narrow-to-element ()
  22714. "Narrow buffer to current element."
  22715. (interactive)
  22716. (let ((elem (org-element-at-point)))
  22717. (cond
  22718. ((eq (car elem) 'headline)
  22719. (narrow-to-region
  22720. (org-element-property :begin elem)
  22721. (org-element-property :end elem)))
  22722. ((memq (car elem) org-element-greater-elements)
  22723. (narrow-to-region
  22724. (org-element-property :contents-begin elem)
  22725. (org-element-property :contents-end elem)))
  22726. (t
  22727. (narrow-to-region
  22728. (org-element-property :begin elem)
  22729. (org-element-property :end elem))))))
  22730. (defun org-transpose-element ()
  22731. "Transpose current and previous elements, keeping blank lines between.
  22732. Point is moved after both elements."
  22733. (interactive)
  22734. (org-skip-whitespace)
  22735. (let ((end (org-element-property :end (org-element-at-point))))
  22736. (org-drag-element-backward)
  22737. (goto-char end)))
  22738. (defun org-unindent-buffer ()
  22739. "Un-indent the visible part of the buffer.
  22740. Relative indentation (between items, inside blocks, etc.) isn't
  22741. modified."
  22742. (interactive)
  22743. (unless (eq major-mode 'org-mode)
  22744. (user-error "Cannot un-indent a buffer not in Org mode"))
  22745. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22746. (unindent-tree
  22747. (lambda (contents)
  22748. (dolist (element (reverse contents))
  22749. (if (memq (org-element-type element) '(headline section))
  22750. (funcall unindent-tree (org-element-contents element))
  22751. (save-excursion
  22752. (save-restriction
  22753. (narrow-to-region
  22754. (org-element-property :begin element)
  22755. (org-element-property :end element))
  22756. (org-do-remove-indentation))))))))
  22757. (funcall unindent-tree (org-element-contents parse-tree))))
  22758. (defun org-show-children (&optional level)
  22759. "Show all direct subheadings of this heading.
  22760. Prefix arg LEVEL is how many levels below the current level
  22761. should be shown. Default is enough to cause the following
  22762. heading to appear."
  22763. (interactive "p")
  22764. ;; If `orgstruct-mode' is active, use the slower version.
  22765. (if orgstruct-mode (call-interactively #'outline-show-children)
  22766. (save-excursion
  22767. (org-back-to-heading t)
  22768. (let* ((current-level (funcall outline-level))
  22769. (max-level (org-get-valid-level
  22770. current-level
  22771. (if level (prefix-numeric-value level) 1)))
  22772. (end (save-excursion (org-end-of-subtree t t)))
  22773. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22774. (past-first-child nil)
  22775. ;; Make sure to skip inlinetasks.
  22776. (re (format regexp-fmt
  22777. current-level
  22778. (cond
  22779. ((not (featurep 'org-inlinetask)) "")
  22780. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22781. 3))
  22782. (t (1- org-inlinetask-min-level))))))
  22783. ;; Display parent heading.
  22784. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22785. (forward-line)
  22786. ;; Display children. First child may be deeper than expected
  22787. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22788. ;; MAX-LEVEL accordingly.
  22789. (while (re-search-forward re end t)
  22790. (unless past-first-child
  22791. (setq re (format regexp-fmt
  22792. current-level
  22793. (max (funcall outline-level) max-level)))
  22794. (setq past-first-child t))
  22795. (outline-flag-region
  22796. (line-end-position 0) (line-end-position) nil))))))
  22797. (defun org-show-subtree ()
  22798. "Show everything after this heading at deeper levels."
  22799. (interactive)
  22800. (outline-flag-region
  22801. (point)
  22802. (save-excursion
  22803. (org-end-of-subtree t t))
  22804. nil))
  22805. (defun org-show-entry ()
  22806. "Show the body directly following this heading.
  22807. Show the heading too, if it is currently invisible."
  22808. (interactive)
  22809. (save-excursion
  22810. (ignore-errors
  22811. (org-back-to-heading t)
  22812. (outline-flag-region
  22813. (max (point-min) (1- (point)))
  22814. (save-excursion
  22815. (if (re-search-forward
  22816. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22817. (match-beginning 1)
  22818. (point-max)))
  22819. nil)
  22820. (org-cycle-hide-drawers 'children))))
  22821. (defun org-make-options-regexp (kwds &optional extra)
  22822. "Make a regular expression for keyword lines.
  22823. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22824. when non-nil, is a regexp matching keywords names."
  22825. (concat "^[ \t]*#\\+\\("
  22826. (regexp-opt kwds)
  22827. (and extra (concat (and kwds "\\|") extra))
  22828. "\\):[ \t]*\\(.*\\)"))
  22829. ;;;; Integration with and fixes for other packages
  22830. ;;; Imenu support
  22831. (defvar-local org-imenu-markers nil
  22832. "All markers currently used by Imenu.")
  22833. (defun org-imenu-new-marker (&optional pos)
  22834. "Return a new marker for use by Imenu, and remember the marker."
  22835. (let ((m (make-marker)))
  22836. (move-marker m (or pos (point)))
  22837. (push m org-imenu-markers)
  22838. m))
  22839. (defun org-imenu-get-tree ()
  22840. "Produce the index for Imenu."
  22841. (dolist (x org-imenu-markers) (move-marker x nil))
  22842. (setq org-imenu-markers nil)
  22843. (let* ((case-fold-search nil)
  22844. (n org-imenu-depth)
  22845. (re (concat "^" (org-get-limited-outline-regexp)))
  22846. (subs (make-vector (1+ n) nil))
  22847. (last-level 0)
  22848. m level head0 head)
  22849. (save-excursion
  22850. (save-restriction
  22851. (widen)
  22852. (goto-char (point-max))
  22853. (while (re-search-backward re nil t)
  22854. (setq level (org-reduced-level (funcall outline-level)))
  22855. (when (and (<= level n)
  22856. (looking-at org-complex-heading-regexp)
  22857. (setq head0 (match-string-no-properties 4)))
  22858. (setq head (org-link-display-format head0)
  22859. m (org-imenu-new-marker))
  22860. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22861. (if (>= level last-level)
  22862. (push (cons head m) (aref subs level))
  22863. (push (cons head (aref subs (1+ level))) (aref subs level))
  22864. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22865. (setq last-level level)))))
  22866. (aref subs 1)))
  22867. (eval-after-load "imenu"
  22868. '(progn
  22869. (add-hook 'imenu-after-jump-hook
  22870. (lambda ()
  22871. (when (derived-mode-p 'org-mode)
  22872. (org-show-context 'org-goto))))))
  22873. (defun org-link-display-format (s)
  22874. "Replace links in string S with their description.
  22875. If there is no description, use the link target."
  22876. (save-match-data
  22877. (replace-regexp-in-string
  22878. org-bracket-link-analytic-regexp
  22879. (lambda (m)
  22880. (if (match-end 5) (match-string 5 m)
  22881. (concat (match-string 1 m) (match-string 3 m))))
  22882. s nil t)))
  22883. (defun org-toggle-link-display ()
  22884. "Toggle the literal or descriptive display of links."
  22885. (interactive)
  22886. (if org-descriptive-links
  22887. (progn (org-remove-from-invisibility-spec '(org-link))
  22888. (org-restart-font-lock)
  22889. (setq org-descriptive-links nil))
  22890. (progn (add-to-invisibility-spec '(org-link))
  22891. (org-restart-font-lock)
  22892. (setq org-descriptive-links t))))
  22893. ;; Speedbar support
  22894. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22895. "Overlay marking the agenda restriction line in speedbar.")
  22896. (overlay-put org-speedbar-restriction-lock-overlay
  22897. 'face 'org-agenda-restriction-lock)
  22898. (overlay-put org-speedbar-restriction-lock-overlay
  22899. 'help-echo "Agendas are currently limited to this item.")
  22900. (delete-overlay org-speedbar-restriction-lock-overlay)
  22901. (defun org-speedbar-set-agenda-restriction ()
  22902. "Restrict future agenda commands to the location at point in speedbar.
  22903. To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
  22904. (interactive)
  22905. (require 'org-agenda)
  22906. (let (p m tp np dir txt)
  22907. (cond
  22908. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22909. 'org-imenu t))
  22910. (setq m (get-text-property p 'org-imenu-marker))
  22911. (with-current-buffer (marker-buffer m)
  22912. (goto-char m)
  22913. (org-agenda-set-restriction-lock 'subtree)))
  22914. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22915. 'speedbar-function 'speedbar-find-file))
  22916. (setq tp (previous-single-property-change
  22917. (1+ p) 'speedbar-function)
  22918. np (next-single-property-change
  22919. tp 'speedbar-function)
  22920. dir (speedbar-line-directory)
  22921. txt (buffer-substring-no-properties (or tp (point-min))
  22922. (or np (point-max))))
  22923. (with-current-buffer (find-file-noselect
  22924. (let ((default-directory dir))
  22925. (expand-file-name txt)))
  22926. (unless (derived-mode-p 'org-mode)
  22927. (user-error "Cannot restrict to non-Org-mode file"))
  22928. (org-agenda-set-restriction-lock 'file)))
  22929. (t (user-error "Don't know how to restrict Org-mode's agenda")))
  22930. (move-overlay org-speedbar-restriction-lock-overlay
  22931. (point-at-bol) (point-at-eol))
  22932. (setq current-prefix-arg nil)
  22933. (org-agenda-maybe-redo)))
  22934. (defvar speedbar-file-key-map)
  22935. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22936. (eval-after-load "speedbar"
  22937. '(progn
  22938. (speedbar-add-supported-extension ".org")
  22939. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22940. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22941. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22942. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22943. (add-hook 'speedbar-visiting-tag-hook
  22944. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22945. ;;; Fixes and Hacks for problems with other packages
  22946. (defun org--flyspell-object-check-p (element)
  22947. "Non-nil when Flyspell can check object at point.
  22948. ELEMENT is the element at point."
  22949. (let ((object (save-excursion
  22950. (when (looking-at-p "\\>") (backward-char))
  22951. (org-element-context element))))
  22952. (cl-case (org-element-type object)
  22953. ;; Prevent checks in links due to keybinding conflict with
  22954. ;; Flyspell.
  22955. ((code entity export-snippet inline-babel-call
  22956. inline-src-block line-break latex-fragment link macro
  22957. statistics-cookie target timestamp verbatim)
  22958. nil)
  22959. (footnote-reference
  22960. ;; Only in inline footnotes, within the definition.
  22961. (and (eq (org-element-property :type object) 'inline)
  22962. (< (save-excursion
  22963. (goto-char (org-element-property :begin object))
  22964. (search-forward ":" nil t 2))
  22965. (point))))
  22966. (otherwise t))))
  22967. (defun org-mode-flyspell-verify ()
  22968. "Function used for `flyspell-generic-check-word-predicate'."
  22969. (if (org-at-heading-p)
  22970. ;; At a headline or an inlinetask, check title only. This is
  22971. ;; faster than relying on `org-element-at-point'.
  22972. (and (save-excursion (beginning-of-line)
  22973. (and (let ((case-fold-search t))
  22974. (not (looking-at "\\*+ END[ \t]*$")))
  22975. (looking-at org-complex-heading-regexp)))
  22976. (match-beginning 4)
  22977. (>= (point) (match-beginning 4))
  22978. (or (not (match-beginning 5))
  22979. (< (point) (match-beginning 5))))
  22980. (let* ((element (org-element-at-point))
  22981. (post-affiliated (org-element-property :post-affiliated element)))
  22982. (cond
  22983. ;; Ignore checks in all affiliated keywords but captions.
  22984. ((< (point) post-affiliated)
  22985. (and (save-excursion
  22986. (beginning-of-line)
  22987. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22988. (> (point) (match-end 0))
  22989. (org--flyspell-object-check-p element)))
  22990. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22991. ((let ((log (org-log-into-drawer)))
  22992. (and log
  22993. (let ((drawer (org-element-lineage element '(drawer))))
  22994. (and drawer
  22995. (eq (compare-strings
  22996. log nil nil
  22997. (org-element-property :drawer-name drawer) nil nil t)
  22998. t)))))
  22999. nil)
  23000. (t
  23001. (cl-case (org-element-type element)
  23002. ((comment quote-section) t)
  23003. (comment-block
  23004. ;; Allow checks between block markers, not on them.
  23005. (and (> (line-beginning-position) post-affiliated)
  23006. (save-excursion
  23007. (end-of-line)
  23008. (skip-chars-forward " \r\t\n")
  23009. (< (point) (org-element-property :end element)))))
  23010. ;; Arbitrary list of keywords where checks are meaningful.
  23011. ;; Make sure point is on the value part of the element.
  23012. (keyword
  23013. (and (member (org-element-property :key element)
  23014. '("DESCRIPTION" "TITLE"))
  23015. (save-excursion
  23016. (search-backward ":" (line-beginning-position) t))))
  23017. ;; Check is globally allowed in paragraphs verse blocks and
  23018. ;; table rows (after affiliated keywords) but some objects
  23019. ;; must not be affected.
  23020. ((paragraph table-row verse-block)
  23021. (let ((cbeg (org-element-property :contents-begin element))
  23022. (cend (org-element-property :contents-end element)))
  23023. (and cbeg (>= (point) cbeg) (< (point) cend)
  23024. (org--flyspell-object-check-p element))))))))))
  23025. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  23026. (defun org-remove-flyspell-overlays-in (beg end)
  23027. "Remove flyspell overlays in region."
  23028. (and (bound-and-true-p flyspell-mode)
  23029. (fboundp 'flyspell-delete-region-overlays)
  23030. (flyspell-delete-region-overlays beg end)))
  23031. (defvar flyspell-delayed-commands)
  23032. (eval-after-load "flyspell"
  23033. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23034. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23035. (eval-after-load "bookmark"
  23036. '(if (boundp 'bookmark-after-jump-hook)
  23037. ;; We can use the hook
  23038. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23039. ;; Hook not available, use advice
  23040. (defadvice bookmark-jump (after org-make-visible activate)
  23041. "Make the position visible."
  23042. (org-bookmark-jump-unhide))))
  23043. ;; Make sure saveplace shows the location if it was hidden
  23044. (eval-after-load "saveplace"
  23045. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23046. "Make the position visible."
  23047. (org-bookmark-jump-unhide)))
  23048. ;; Make sure ecb shows the location if it was hidden
  23049. (eval-after-load "ecb"
  23050. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23051. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23052. (when (derived-mode-p 'org-mode)
  23053. (org-show-context))))
  23054. (defun org-bookmark-jump-unhide ()
  23055. "Unhide the current position, to show the bookmark location."
  23056. (and (derived-mode-p 'org-mode)
  23057. (or (outline-invisible-p)
  23058. (save-excursion (goto-char (max (point-min) (1- (point))))
  23059. (outline-invisible-p)))
  23060. (org-show-context 'bookmark-jump)))
  23061. (defun org-mark-jump-unhide ()
  23062. "Make the point visible with `org-show-context' after jumping to the mark."
  23063. (when (and (derived-mode-p 'org-mode)
  23064. (outline-invisible-p))
  23065. (org-show-context 'mark-goto)))
  23066. (eval-after-load "simple"
  23067. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23068. "Make the point visible with `org-show-context'."
  23069. (org-mark-jump-unhide)))
  23070. (eval-after-load "simple"
  23071. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23072. "Make the point visible with `org-show-context'."
  23073. (org-mark-jump-unhide)))
  23074. (eval-after-load "simple"
  23075. '(defadvice pop-global-mark (after org-make-visible activate)
  23076. "Make the point visible with `org-show-context'."
  23077. (org-mark-jump-unhide)))
  23078. ;; Make session.el ignore our circular variable
  23079. (defvar session-globals-exclude)
  23080. (eval-after-load "session"
  23081. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23082. ;;;; Finish up
  23083. (provide 'org)
  23084. (run-hooks 'org-load-hook)
  23085. ;;; org.el ends here