org.el 952 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184
  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-parameters
  1522. '(("doi" :follow org--open-doi-link)
  1523. ("elisp" :follow org--open-elisp-link)
  1524. ("file" :complete org-file-complete-link)
  1525. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1526. ("help" :follow org--open-help-link)
  1527. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1528. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1529. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1530. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1531. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1532. ("shell" :follow org--open-shell-link))
  1533. "An alist of properties that defines all the links in Org mode.
  1534. The key in each association is a string of the link type.
  1535. Subsequent optional elements make up a p-list of link properties.
  1536. :follow - A function that takes the link path as an argument.
  1537. :export - A function that takes the link path, description and
  1538. export-backend as arguments.
  1539. :store - A function responsible for storing the link. See the
  1540. function `org-store-link-functions'.
  1541. :complete - A function that inserts a link with completion. The
  1542. function takes one optional prefix arg.
  1543. :face - A face for the link, or a function that returns a face.
  1544. The function takes one argument which is the link path. The
  1545. default face is `org-link'.
  1546. :mouse-face - The mouse-face. The default is `highlight'.
  1547. :display - `full' will not fold the link in descriptive
  1548. display. Default is `org-link'.
  1549. :help-echo - A string or function that takes (window object position)
  1550. as arguments and returns a string.
  1551. :keymap - A keymap that is active on the link. The default is
  1552. `org-mouse-map'.
  1553. :htmlize-link - A function for the htmlize-link. Defaults
  1554. to (list :uri \"type:path\")
  1555. :activate-func - A function to run at the end of font-lock
  1556. activation. The function must accept (link-start link-end path bracketp)
  1557. as arguments."
  1558. :group 'org-link
  1559. :type '(alist :tag "Link display parameters"
  1560. :value-type plist))
  1561. (defun org-link-get-parameter (type key)
  1562. "Get TYPE link property for KEY.
  1563. TYPE is a string and KEY is a plist keyword."
  1564. (plist-get
  1565. (cdr (assoc type org-link-parameters))
  1566. key))
  1567. (defun org-link-set-parameters (type &rest parameters)
  1568. "Set link TYPE properties to PARAMETERS.
  1569. PARAMETERS should be :key val pairs."
  1570. (let ((data (assoc type org-link-parameters)))
  1571. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1572. (push (cons type parameters) org-link-parameters)
  1573. (org-make-link-regexps)
  1574. (org-element-update-syntax))))
  1575. (defun org-link-types ()
  1576. "Return a list of known link types."
  1577. (mapcar #'car org-link-parameters))
  1578. (defcustom org-link-abbrev-alist nil
  1579. "Alist of link abbreviations.
  1580. The car of each element is a string, to be replaced at the start of a link.
  1581. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1582. links in Org-mode buffers can have an optional tag after a double colon, e.g.
  1583. [[linkkey:tag][description]]
  1584. The `linkkey' must be a word word, starting with a letter, followed
  1585. by letters, numbers, `-' or `_'.
  1586. If REPLACE is a string, the tag will simply be appended to create the link.
  1587. If the string contains \"%s\", the tag will be inserted there. If the string
  1588. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1589. at that point (see the function `url-hexify-string'). If the string contains
  1590. the specifier \"%(my-function)\", then the custom function `my-function' will
  1591. be invoked: this function takes the tag as its only argument and must return
  1592. a string.
  1593. REPLACE may also be a function that will be called with the tag as the
  1594. only argument to create the link, which should be returned as a string.
  1595. See the manual for examples."
  1596. :group 'org-link
  1597. :type '(repeat
  1598. (cons
  1599. (string :tag "Protocol")
  1600. (choice
  1601. (string :tag "Format")
  1602. (function)))))
  1603. (defcustom org-descriptive-links t
  1604. "Non-nil means Org will display descriptive links.
  1605. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1606. \"Org Website\", hiding the link itself and just displaying its
  1607. description. When set to nil, Org will display the full links
  1608. literally.
  1609. You can interactively set the value of this variable by calling
  1610. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1611. :group 'org-link
  1612. :type 'boolean)
  1613. (defcustom org-link-file-path-type 'adaptive
  1614. "How the path name in file links should be stored.
  1615. Valid values are:
  1616. relative Relative to the current directory, i.e. the directory of the file
  1617. into which the link is being inserted.
  1618. absolute Absolute path, if possible with ~ for home directory.
  1619. noabbrev Absolute path, no abbreviation of home directory.
  1620. adaptive Use relative path for files in the current directory and sub-
  1621. directories of it. For other files, use an absolute path."
  1622. :group 'org-link
  1623. :type '(choice
  1624. (const relative)
  1625. (const absolute)
  1626. (const noabbrev)
  1627. (const adaptive)))
  1628. (defvaralias 'org-activate-links 'org-highlight-links)
  1629. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1630. "Types of links that should be highlighted in Org-mode files.
  1631. This is a list of symbols, each one of them leading to the
  1632. highlighting of a certain link type.
  1633. You can still open links that are not highlighted.
  1634. In principle, it does not hurt to turn on highlighting for all
  1635. link types. There may be a small gain when turning off unused
  1636. link types. The types are:
  1637. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1638. angle Links in angular brackets that may contain whitespace like
  1639. <bbdb:Carsten Dominik>.
  1640. plain Plain links in normal text, no whitespace, like http://google.com.
  1641. radio Text that is matched by a radio target, see manual for details.
  1642. tag Tag settings in a headline (link to tag search).
  1643. date Time stamps (link to calendar).
  1644. footnote Footnote labels.
  1645. If you set this variable during an Emacs session, use `org-mode-restart'
  1646. in the Org buffer so that the change takes effect."
  1647. :group 'org-link
  1648. :group 'org-appearance
  1649. :type '(set :greedy t
  1650. (const :tag "Double bracket links" bracket)
  1651. (const :tag "Angular bracket links" angle)
  1652. (const :tag "Plain text links" plain)
  1653. (const :tag "Radio target matches" radio)
  1654. (const :tag "Tags" tag)
  1655. (const :tag "Timestamps" date)
  1656. (const :tag "Footnotes" footnote)))
  1657. (defcustom org-make-link-description-function nil
  1658. "Function to use for generating link descriptions from links.
  1659. When nil, the link location will be used. This function must take
  1660. two parameters: the first one is the link, the second one is the
  1661. description generated by `org-insert-link'. The function should
  1662. return the description to use."
  1663. :group 'org-link
  1664. :type '(choice (const nil) (function)))
  1665. (defgroup org-link-store nil
  1666. "Options concerning storing links in Org-mode."
  1667. :tag "Org Store Link"
  1668. :group 'org-link)
  1669. (defcustom org-url-hexify-p t
  1670. "When non-nil, hexify URL when creating a link."
  1671. :type 'boolean
  1672. :version "24.3"
  1673. :group 'org-link-store)
  1674. (defcustom org-email-link-description-format "Email %c: %.30s"
  1675. "Format of the description part of a link to an email or usenet message.
  1676. The following %-escapes will be replaced by corresponding information:
  1677. %F full \"From\" field
  1678. %f name, taken from \"From\" field, address if no name
  1679. %T full \"To\" field
  1680. %t first name in \"To\" field, address if no name
  1681. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1682. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1683. %s subject
  1684. %d date
  1685. %m message-id.
  1686. You may use normal field width specification between the % and the letter.
  1687. This is for example useful to limit the length of the subject.
  1688. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1689. :group 'org-link-store
  1690. :type 'string)
  1691. (defcustom org-from-is-user-regexp
  1692. (let (r1 r2)
  1693. (when (and user-mail-address (not (string= user-mail-address "")))
  1694. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1695. (when (and user-full-name (not (string= user-full-name "")))
  1696. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1697. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1698. "Regexp matched against the \"From:\" header of an email or usenet message.
  1699. It should match if the message is from the user him/herself."
  1700. :group 'org-link-store
  1701. :type 'regexp)
  1702. (defcustom org-context-in-file-links t
  1703. "Non-nil means file links from `org-store-link' contain context.
  1704. A search string will be added to the file name with :: as separator and
  1705. used to find the context when the link is activated by the command
  1706. `org-open-at-point'. When this option is t, the entire active region
  1707. will be placed in the search string of the file link. If set to a
  1708. positive integer, only the first n lines of context will be stored.
  1709. Using a prefix arg to the command \\[org-store-link] (`org-store-link')
  1710. negates this setting for the duration of the command."
  1711. :group 'org-link-store
  1712. :type '(choice boolean integer))
  1713. (defcustom org-keep-stored-link-after-insertion nil
  1714. "Non-nil means keep link in list for entire session.
  1715. The command `org-store-link' adds a link pointing to the current
  1716. location to an internal list. These links accumulate during a session.
  1717. The command `org-insert-link' can be used to insert links into any
  1718. Org-mode file (offering completion for all stored links). When this
  1719. option is nil, every link which has been inserted once using \\[org-insert-link]
  1720. will be removed from the list, to make completing the unused links
  1721. more efficient."
  1722. :group 'org-link-store
  1723. :type 'boolean)
  1724. (defgroup org-link-follow nil
  1725. "Options concerning following links in Org-mode."
  1726. :tag "Org Follow Link"
  1727. :group 'org-link)
  1728. (defcustom org-link-translation-function nil
  1729. "Function to translate links with different syntax to Org syntax.
  1730. This can be used to translate links created for example by the Planner
  1731. or emacs-wiki packages to Org syntax.
  1732. The function must accept two parameters, a TYPE containing the link
  1733. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1734. which is everything after the link protocol. It should return a cons
  1735. with possibly modified values of type and path.
  1736. Org contains a function for this, so if you set this variable to
  1737. `org-translate-link-from-planner', you should be able follow many
  1738. links created by planner."
  1739. :group 'org-link-follow
  1740. :type '(choice (const nil) (function)))
  1741. (defcustom org-follow-link-hook nil
  1742. "Hook that is run after a link has been followed."
  1743. :group 'org-link-follow
  1744. :type 'hook)
  1745. (defcustom org-tab-follows-link nil
  1746. "Non-nil means on links TAB will follow the link.
  1747. Needs to be set before org.el is loaded.
  1748. This really should not be used, it does not make sense, and the
  1749. implementation is bad."
  1750. :group 'org-link-follow
  1751. :type 'boolean)
  1752. (defcustom org-return-follows-link nil
  1753. "Non-nil means on links RET will follow the link.
  1754. In tables, the special behavior of RET has precedence."
  1755. :group 'org-link-follow
  1756. :type 'boolean)
  1757. (defcustom org-mouse-1-follows-link
  1758. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1759. "Non-nil means mouse-1 on a link will follow the link.
  1760. A longer mouse click will still set point. Needs to be set
  1761. before org.el is loaded."
  1762. :group 'org-link-follow
  1763. :version "24.4"
  1764. :package-version '(Org . "8.3")
  1765. :type '(choice
  1766. (const :tag "A double click follows the link" double)
  1767. (const :tag "Unconditionally follow the link with mouse-1" t)
  1768. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1769. (defcustom org-mark-ring-length 4
  1770. "Number of different positions to be recorded in the ring.
  1771. Changing this requires a restart of Emacs to work correctly."
  1772. :group 'org-link-follow
  1773. :type 'integer)
  1774. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1775. "Non-nil means internal links in Org files must exactly match a headline.
  1776. When nil, the link search tries to match a phrase with all words
  1777. in the search text."
  1778. :group 'org-link-follow
  1779. :version "24.1"
  1780. :type '(choice
  1781. (const :tag "Use fuzzy text search" nil)
  1782. (const :tag "Match only exact headline" t)
  1783. (const :tag "Match exact headline or query to create it"
  1784. query-to-create)))
  1785. (defcustom org-link-frame-setup
  1786. '((vm . vm-visit-folder-other-frame)
  1787. (vm-imap . vm-visit-imap-folder-other-frame)
  1788. (gnus . org-gnus-no-new-news)
  1789. (file . find-file-other-window)
  1790. (wl . wl-other-frame))
  1791. "Setup the frame configuration for following links.
  1792. When following a link with Emacs, it may often be useful to display
  1793. this link in another window or frame. This variable can be used to
  1794. set this up for the different types of links.
  1795. For VM, use any of
  1796. `vm-visit-folder'
  1797. `vm-visit-folder-other-window'
  1798. `vm-visit-folder-other-frame'
  1799. For Gnus, use any of
  1800. `gnus'
  1801. `gnus-other-frame'
  1802. `org-gnus-no-new-news'
  1803. For FILE, use any of
  1804. `find-file'
  1805. `find-file-other-window'
  1806. `find-file-other-frame'
  1807. For Wanderlust use any of
  1808. `wl'
  1809. `wl-other-frame'
  1810. For the calendar, use the variable `calendar-setup'.
  1811. For BBDB, it is currently only possible to display the matches in
  1812. another window."
  1813. :group 'org-link-follow
  1814. :type '(list
  1815. (cons (const vm)
  1816. (choice
  1817. (const vm-visit-folder)
  1818. (const vm-visit-folder-other-window)
  1819. (const vm-visit-folder-other-frame)))
  1820. (cons (const vm-imap)
  1821. (choice
  1822. (const vm-visit-imap-folder)
  1823. (const vm-visit-imap-folder-other-window)
  1824. (const vm-visit-imap-folder-other-frame)))
  1825. (cons (const gnus)
  1826. (choice
  1827. (const gnus)
  1828. (const gnus-other-frame)
  1829. (const org-gnus-no-new-news)))
  1830. (cons (const file)
  1831. (choice
  1832. (const find-file)
  1833. (const find-file-other-window)
  1834. (const find-file-other-frame)))
  1835. (cons (const wl)
  1836. (choice
  1837. (const wl)
  1838. (const wl-other-frame)))))
  1839. (defcustom org-display-internal-link-with-indirect-buffer nil
  1840. "Non-nil means use indirect buffer to display infile links.
  1841. Activating internal links (from one location in a file to another location
  1842. in the same file) normally just jumps to the location. When the link is
  1843. activated with a \\[universal-argument] prefix (or with mouse-3), the link \
  1844. is displayed in
  1845. another window. When this option is set, the other window actually displays
  1846. an indirect buffer clone of the current buffer, to avoid any visibility
  1847. changes to the current buffer."
  1848. :group 'org-link-follow
  1849. :type 'boolean)
  1850. (defcustom org-open-non-existing-files nil
  1851. "Non-nil means `org-open-file' will open non-existing files.
  1852. When nil, an error will be generated.
  1853. This variable applies only to external applications because they
  1854. might choke on non-existing files. If the link is to a file that
  1855. will be opened in Emacs, the variable is ignored."
  1856. :group 'org-link-follow
  1857. :type 'boolean)
  1858. (defcustom org-open-directory-means-index-dot-org nil
  1859. "Non-nil means a link to a directory really means to index.org.
  1860. When nil, following a directory link will run dired or open a finder/explorer
  1861. window on that directory."
  1862. :group 'org-link-follow
  1863. :type 'boolean)
  1864. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1865. "Non-nil means ask for confirmation before executing shell links.
  1866. Shell links can be dangerous: just think about a link
  1867. [[shell:rm -rf ~/*][Google Search]]
  1868. This link would show up in your Org-mode document as \"Google Search\",
  1869. but really it would remove your entire home directory.
  1870. Therefore we advise against setting this variable to nil.
  1871. Just change it to `y-or-n-p' if you want to confirm with a
  1872. single keystroke rather than having to type \"yes\"."
  1873. :group 'org-link-follow
  1874. :type '(choice
  1875. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1876. (const :tag "with y-or-n (faster)" y-or-n-p)
  1877. (const :tag "no confirmation (dangerous)" nil)))
  1878. (put 'org-confirm-shell-link-function
  1879. 'safe-local-variable
  1880. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1881. (defcustom org-confirm-shell-link-not-regexp ""
  1882. "A regexp to skip confirmation for shell links."
  1883. :group 'org-link-follow
  1884. :version "24.1"
  1885. :type 'regexp)
  1886. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1887. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1888. Elisp links can be dangerous: just think about a link
  1889. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1890. This link would show up in your Org-mode document as \"Google Search\",
  1891. but really it would remove your entire home directory.
  1892. Therefore we advise against setting this variable to nil.
  1893. Just change it to `y-or-n-p' if you want to confirm with a
  1894. single keystroke rather than having to type \"yes\"."
  1895. :group 'org-link-follow
  1896. :type '(choice
  1897. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1898. (const :tag "with y-or-n (faster)" y-or-n-p)
  1899. (const :tag "no confirmation (dangerous)" nil)))
  1900. (put 'org-confirm-shell-link-function
  1901. 'safe-local-variable
  1902. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1903. (defcustom org-confirm-elisp-link-not-regexp ""
  1904. "A regexp to skip confirmation for Elisp links."
  1905. :group 'org-link-follow
  1906. :version "24.1"
  1907. :type 'regexp)
  1908. (defconst org-file-apps-defaults-gnu
  1909. '((remote . emacs)
  1910. (system . mailcap)
  1911. (t . mailcap))
  1912. "Default file applications on a UNIX or GNU/Linux system.
  1913. See `org-file-apps'.")
  1914. (defconst org-file-apps-defaults-macosx
  1915. '((remote . emacs)
  1916. (system . "open %s")
  1917. ("ps.gz" . "gv %s")
  1918. ("eps.gz" . "gv %s")
  1919. ("dvi" . "xdvi %s")
  1920. ("fig" . "xfig %s")
  1921. (t . "open %s"))
  1922. "Default file applications on a MacOS X system.
  1923. The system \"open\" is known as a default, but we use X11 applications
  1924. for some files for which the OS does not have a good default.
  1925. See `org-file-apps'.")
  1926. (defconst org-file-apps-defaults-windowsnt
  1927. (list '(remote . emacs)
  1928. (cons 'system (lambda (file _path)
  1929. (with-no-warnings (w32-shell-execute "open" file))))
  1930. (cons t (lambda (file _path)
  1931. (with-no-warnings (w32-shell-execute "open" file)))))
  1932. "Default file applications on a Windows NT system.
  1933. The system \"open\" is used for most files.
  1934. See `org-file-apps'.")
  1935. (defcustom org-file-apps
  1936. '((auto-mode . emacs)
  1937. ("\\.mm\\'" . default)
  1938. ("\\.x?html?\\'" . default)
  1939. ("\\.pdf\\'" . default))
  1940. "External applications for opening `file:path' items in a document.
  1941. \\<org-mode-map>\
  1942. Org mode uses system defaults for different file types, but
  1943. you can use this variable to set the application for a given file
  1944. extension. The entries in this list are cons cells where the car identifies
  1945. files and the cdr the corresponding command. Possible values for the
  1946. file identifier are
  1947. \"string\" A string as a file identifier can be interpreted in different
  1948. ways, depending on its contents:
  1949. - Alphanumeric characters only:
  1950. Match links with this file extension.
  1951. Example: (\"pdf\" . \"evince %s\")
  1952. to open PDFs with evince.
  1953. - Regular expression: Match links where the
  1954. filename matches the regexp. If you want to
  1955. use groups here, use shy groups.
  1956. Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
  1957. \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
  1958. to open *.html and *.xhtml with firefox.
  1959. - Regular expression which contains (non-shy) groups:
  1960. Match links where the whole link, including \"::\", and
  1961. anything after that, matches the regexp.
  1962. In a custom command string, %1, %2, etc. are replaced with
  1963. the parts of the link that were matched by the groups.
  1964. For backwards compatibility, if a command string is given
  1965. that does not use any of the group matches, this case is
  1966. handled identically to the second one (i.e. match against
  1967. file name only).
  1968. In a custom function, you can access the group matches with
  1969. \(match-string n link).
  1970. Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
  1971. to open [[file:document.pdf::5]] with evince at page 5.
  1972. `directory' Matches a directory
  1973. `remote' Matches a remote file, accessible through tramp or efs.
  1974. Remote files most likely should be visited through Emacs
  1975. because external applications cannot handle such paths.
  1976. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1977. so all files Emacs knows how to handle. Using this with
  1978. command `emacs' will open most files in Emacs. Beware that this
  1979. will also open html files inside Emacs, unless you add
  1980. \(\"html\" . default) to the list as well.
  1981. `system' The system command to open files, like `open' on Windows
  1982. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1983. that will be selected if you call \\[org-open-at-point] with a double
  1984. \\[universal-argument] \\[universal-argument] prefix.
  1985. t Default for files not matched by any of the other options.
  1986. Possible values for the command are:
  1987. `emacs' The file will be visited by the current Emacs process.
  1988. `default' Use the default application for this file type, which is the
  1989. association for t in the list, most likely in the system-specific
  1990. part. This can be used to overrule an unwanted setting in the
  1991. system-specific variable.
  1992. `system' Use the system command for opening files, like \"open\".
  1993. This command is specified by the entry whose car is `system'.
  1994. Most likely, the system-specific version of this variable
  1995. does define this command, but you can overrule/replace it
  1996. here.
  1997. `mailcap' Use command specified in the mailcaps.
  1998. string A command to be executed by a shell; %s will be replaced
  1999. by the path to the file.
  2000. function A Lisp function, which will be called with two arguments:
  2001. the file path and the original link string, without the
  2002. \"file:\" prefix.
  2003. For more examples, see the system specific constants
  2004. `org-file-apps-defaults-macosx'
  2005. `org-file-apps-defaults-windowsnt'
  2006. `org-file-apps-defaults-gnu'."
  2007. :group 'org-link-follow
  2008. :type '(repeat
  2009. (cons (choice :value ""
  2010. (string :tag "Extension")
  2011. (const :tag "System command to open files" system)
  2012. (const :tag "Default for unrecognized files" t)
  2013. (const :tag "Remote file" remote)
  2014. (const :tag "Links to a directory" directory)
  2015. (const :tag "Any files that have Emacs modes"
  2016. auto-mode))
  2017. (choice :value ""
  2018. (const :tag "Visit with Emacs" emacs)
  2019. (const :tag "Use default" default)
  2020. (const :tag "Use the system command" system)
  2021. (string :tag "Command")
  2022. (function :tag "Function")))))
  2023. (defcustom org-doi-server-url "http://dx.doi.org/"
  2024. "The URL of the DOI server."
  2025. :type 'string
  2026. :version "24.3"
  2027. :group 'org-link-follow)
  2028. (defgroup org-refile nil
  2029. "Options concerning refiling entries in Org-mode."
  2030. :tag "Org Refile"
  2031. :group 'org)
  2032. (defcustom org-directory "~/org"
  2033. "Directory with Org files.
  2034. This is just a default location to look for Org files. There is no need
  2035. at all to put your files into this directory. It is used in the
  2036. following situations:
  2037. 1. When a capture template specifies a target file that is not an
  2038. absolute path. The path will then be interpreted relative to
  2039. `org-directory'
  2040. 2. When the value of variable `org-agenda-files' is a single file, any
  2041. relative paths in this file will be taken as relative to
  2042. `org-directory'."
  2043. :group 'org-refile
  2044. :group 'org-capture
  2045. :type 'directory)
  2046. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2047. "Default target for storing notes.
  2048. Used as a fall back file for org-capture.el, for templates that
  2049. do not specify a target file."
  2050. :group 'org-refile
  2051. :group 'org-capture
  2052. :type 'file)
  2053. (defcustom org-goto-interface 'outline
  2054. "The default interface to be used for `org-goto'.
  2055. Allowed values are:
  2056. outline The interface shows an outline of the relevant file
  2057. and the correct heading is found by moving through
  2058. the outline or by searching with incremental search.
  2059. outline-path-completion Headlines in the current buffer are offered via
  2060. completion. This is the interface also used by
  2061. the refile command."
  2062. :group 'org-refile
  2063. :type '(choice
  2064. (const :tag "Outline" outline)
  2065. (const :tag "Outline-path-completion" outline-path-completion)))
  2066. (defcustom org-goto-max-level 5
  2067. "Maximum target level when running `org-goto' with refile interface."
  2068. :group 'org-refile
  2069. :type 'integer)
  2070. (defcustom org-reverse-note-order nil
  2071. "Non-nil means store new notes at the beginning of a file or entry.
  2072. When nil, new notes will be filed to the end of a file or entry.
  2073. This can also be a list with cons cells of regular expressions that
  2074. are matched against file names, and values."
  2075. :group 'org-capture
  2076. :group 'org-refile
  2077. :type '(choice
  2078. (const :tag "Reverse always" t)
  2079. (const :tag "Reverse never" nil)
  2080. (repeat :tag "By file name regexp"
  2081. (cons regexp boolean))))
  2082. (defcustom org-log-refile nil
  2083. "Information to record when a task is refiled.
  2084. Possible values are:
  2085. nil Don't add anything
  2086. time Add a time stamp to the task
  2087. note Prompt for a note and add it with template `org-log-note-headings'
  2088. This option can also be set with on a per-file-basis with
  2089. #+STARTUP: nologrefile
  2090. #+STARTUP: logrefile
  2091. #+STARTUP: lognoterefile
  2092. You can have local logging settings for a subtree by setting the LOGGING
  2093. property to one or more of these keywords.
  2094. When bulk-refiling from the agenda, the value `note' is forbidden and
  2095. will temporarily be changed to `time'."
  2096. :group 'org-refile
  2097. :group 'org-progress
  2098. :version "24.1"
  2099. :type '(choice
  2100. (const :tag "No logging" nil)
  2101. (const :tag "Record timestamp" time)
  2102. (const :tag "Record timestamp with note." note)))
  2103. (defcustom org-refile-targets nil
  2104. "Targets for refiling entries with \\[org-refile].
  2105. This is a list of cons cells. Each cell contains:
  2106. - a specification of the files to be considered, either a list of files,
  2107. or a symbol whose function or variable value will be used to retrieve
  2108. a file name or a list of file names. If you use `org-agenda-files' for
  2109. that, all agenda files will be scanned for targets. Nil means consider
  2110. headings in the current buffer.
  2111. - A specification of how to find candidate refile targets. This may be
  2112. any of:
  2113. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2114. This tag has to be present in all target headlines, inheritance will
  2115. not be considered.
  2116. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2117. todo keyword.
  2118. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2119. headlines that are refiling targets.
  2120. - a cons cell (:level . N). Any headline of level N is considered a target.
  2121. Note that, when `org-odd-levels-only' is set, level corresponds to
  2122. order in hierarchy, not to the number of stars.
  2123. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2124. Note that, when `org-odd-levels-only' is set, level corresponds to
  2125. order in hierarchy, not to the number of stars.
  2126. Each element of this list generates a set of possible targets.
  2127. The union of these sets is presented (with completion) to
  2128. the user by `org-refile'.
  2129. You can set the variable `org-refile-target-verify-function' to a function
  2130. to verify each headline found by the simple criteria above.
  2131. When this variable is nil, all top-level headlines in the current buffer
  2132. are used, equivalent to the value `((nil . (:level . 1))'."
  2133. :group 'org-refile
  2134. :type '(repeat
  2135. (cons
  2136. (choice :value org-agenda-files
  2137. (const :tag "All agenda files" org-agenda-files)
  2138. (const :tag "Current buffer" nil)
  2139. (function) (variable) (file))
  2140. (choice :tag "Identify target headline by"
  2141. (cons :tag "Specific tag" (const :value :tag) (string))
  2142. (cons :tag "TODO keyword" (const :value :todo) (string))
  2143. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2144. (cons :tag "Level number" (const :value :level) (integer))
  2145. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2146. (defcustom org-refile-target-verify-function nil
  2147. "Function to verify if the headline at point should be a refile target.
  2148. The function will be called without arguments, with point at the
  2149. beginning of the headline. It should return t and leave point
  2150. where it is if the headline is a valid target for refiling.
  2151. If the target should not be selected, the function must return nil.
  2152. In addition to this, it may move point to a place from where the search
  2153. should be continued. For example, the function may decide that the entire
  2154. subtree of the current entry should be excluded and move point to the end
  2155. of the subtree."
  2156. :group 'org-refile
  2157. :type '(choice
  2158. (const nil)
  2159. (function)))
  2160. (defcustom org-refile-use-cache nil
  2161. "Non-nil means cache refile targets to speed up the process.
  2162. \\<org-mode-map>\
  2163. The cache for a particular file will be updated automatically when
  2164. the buffer has been killed, or when any of the marker used for flagging
  2165. refile targets no longer points at a live buffer.
  2166. If you have added new entries to a buffer that might themselves be targets,
  2167. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2168. if you find that easier, \
  2169. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2170. \\[org-refile]'."
  2171. :group 'org-refile
  2172. :version "24.1"
  2173. :type 'boolean)
  2174. (defcustom org-refile-use-outline-path nil
  2175. "Non-nil means provide refile targets as paths.
  2176. So a level 3 headline will be available as level1/level2/level3.
  2177. When the value is `file', also include the file name (without directory)
  2178. into the path. In this case, you can also stop the completion after
  2179. the file name, to get entries inserted as top level in the file.
  2180. When `full-file-path', include the full file path."
  2181. :group 'org-refile
  2182. :type '(choice
  2183. (const :tag "Not" nil)
  2184. (const :tag "Yes" t)
  2185. (const :tag "Start with file name" file)
  2186. (const :tag "Start with full file path" full-file-path)))
  2187. (defcustom org-outline-path-complete-in-steps t
  2188. "Non-nil means complete the outline path in hierarchical steps.
  2189. When Org-mode uses the refile interface to select an outline path
  2190. \(see variable `org-refile-use-outline-path'), the completion of
  2191. the path can be done in a single go, or it can be done in steps down
  2192. the headline hierarchy. Going in steps is probably the best if you
  2193. do not use a special completion package like `ido' or `icicles'.
  2194. However, when using these packages, going in one step can be very
  2195. fast, while still showing the whole path to the entry."
  2196. :group 'org-refile
  2197. :type 'boolean)
  2198. (defcustom org-refile-allow-creating-parent-nodes nil
  2199. "Non-nil means allow the creation of new nodes as refile targets.
  2200. New nodes are then created by adding \"/new node name\" to the completion
  2201. of an existing node. When the value of this variable is `confirm',
  2202. new node creation must be confirmed by the user (recommended).
  2203. When nil, the completion must match an existing entry.
  2204. Note that, if the new heading is not seen by the criteria
  2205. listed in `org-refile-targets', multiple instances of the same
  2206. heading would be created by trying again to file under the new
  2207. heading."
  2208. :group 'org-refile
  2209. :type '(choice
  2210. (const :tag "Never" nil)
  2211. (const :tag "Always" t)
  2212. (const :tag "Prompt for confirmation" confirm)))
  2213. (defcustom org-refile-active-region-within-subtree nil
  2214. "Non-nil means also refile active region within a subtree.
  2215. By default `org-refile' doesn't allow refiling regions if they
  2216. don't contain a set of subtrees, but it might be convenient to
  2217. do so sometimes: in that case, the first line of the region is
  2218. converted to a headline before refiling."
  2219. :group 'org-refile
  2220. :version "24.1"
  2221. :type 'boolean)
  2222. (defgroup org-todo nil
  2223. "Options concerning TODO items in Org-mode."
  2224. :tag "Org TODO"
  2225. :group 'org)
  2226. (defgroup org-progress nil
  2227. "Options concerning Progress logging in Org-mode."
  2228. :tag "Org Progress"
  2229. :group 'org-time)
  2230. (defvar org-todo-interpretation-widgets
  2231. '((:tag "Sequence (cycling hits every state)" sequence)
  2232. (:tag "Type (cycling directly to DONE)" type))
  2233. "The available interpretation symbols for customizing `org-todo-keywords'.
  2234. Interested libraries should add to this list.")
  2235. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2236. "List of TODO entry keyword sequences and their interpretation.
  2237. \\<org-mode-map>This is a list of sequences.
  2238. Each sequence starts with a symbol, either `sequence' or `type',
  2239. indicating if the keywords should be interpreted as a sequence of
  2240. action steps, or as different types of TODO items. The first
  2241. keywords are states requiring action - these states will select a headline
  2242. for inclusion into the global TODO list Org-mode produces. If one of
  2243. the \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2244. signify that no further action is necessary. If \"|\" is not found,
  2245. the last keyword is treated as the only DONE state of the sequence.
  2246. The command \\[org-todo] cycles an entry through these states, and one
  2247. additional state where no keyword is present. For details about this
  2248. cycling, see the manual.
  2249. TODO keywords and interpretation can also be set on a per-file basis with
  2250. the special #+SEQ_TODO and #+TYP_TODO lines.
  2251. Each keyword can optionally specify a character for fast state selection
  2252. \(in combination with the variable `org-use-fast-todo-selection')
  2253. and specifiers for state change logging, using the same syntax that
  2254. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2255. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2256. indicates to record a time stamp each time this state is selected.
  2257. Each keyword may also specify if a timestamp or a note should be
  2258. recorded when entering or leaving the state, by adding additional
  2259. characters in the parenthesis after the keyword. This looks like this:
  2260. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2261. record only the time of the state change. With X and Y being either
  2262. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2263. Y when leaving the state if and only if the *target* state does not
  2264. define X. You may omit any of the fast-selection key or X or /Y,
  2265. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2266. For backward compatibility, this variable may also be just a list
  2267. of keywords. In this case the interpretation (sequence or type) will be
  2268. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2269. :group 'org-todo
  2270. :group 'org-keywords
  2271. :type '(choice
  2272. (repeat :tag "Old syntax, just keywords"
  2273. (string :tag "Keyword"))
  2274. (repeat :tag "New syntax"
  2275. (cons
  2276. (choice
  2277. :tag "Interpretation"
  2278. ;;Quick and dirty way to see
  2279. ;;`org-todo-interpretations'. This takes the
  2280. ;;place of item arguments
  2281. :convert-widget
  2282. (lambda (widget)
  2283. (widget-put widget
  2284. :args (mapcar
  2285. (lambda (x)
  2286. (widget-convert
  2287. (cons 'const x)))
  2288. org-todo-interpretation-widgets))
  2289. widget))
  2290. (repeat
  2291. (string :tag "Keyword"))))))
  2292. (defvar-local org-todo-keywords-1 nil
  2293. "All TODO and DONE keywords active in a buffer.")
  2294. (defvar org-todo-keywords-for-agenda nil)
  2295. (defvar org-done-keywords-for-agenda nil)
  2296. (defvar org-todo-keyword-alist-for-agenda nil)
  2297. (defvar org-tag-alist-for-agenda nil
  2298. "Alist of all tags from all agenda files.")
  2299. (defvar org-tag-groups-alist-for-agenda nil
  2300. "Alist of all groups tags from all current agenda files.")
  2301. (defvar-local org-tag-groups-alist nil)
  2302. (defvar org-agenda-contributing-files nil)
  2303. (defvar-local org-current-tag-alist nil
  2304. "Alist of all tag groups in current buffer.
  2305. This variable takes into consideration `org-tag-alist',
  2306. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2307. (defvar-local org-not-done-keywords nil)
  2308. (defvar-local org-done-keywords nil)
  2309. (defvar-local org-todo-heads nil)
  2310. (defvar-local org-todo-sets nil)
  2311. (defvar-local org-todo-log-states nil)
  2312. (defvar-local org-todo-kwd-alist nil)
  2313. (defvar-local org-todo-key-alist nil)
  2314. (defvar-local org-todo-key-trigger nil)
  2315. (defcustom org-todo-interpretation 'sequence
  2316. "Controls how TODO keywords are interpreted.
  2317. This variable is in principle obsolete and is only used for
  2318. backward compatibility, if the interpretation of todo keywords is
  2319. not given already in `org-todo-keywords'. See that variable for
  2320. more information."
  2321. :group 'org-todo
  2322. :group 'org-keywords
  2323. :type '(choice (const sequence)
  2324. (const type)))
  2325. (defcustom org-use-fast-todo-selection t
  2326. "\\<org-mode-map>\
  2327. Non-nil means use the fast todo selection scheme with \\[org-todo].
  2328. This variable describes if and under what circumstances the cycling
  2329. mechanism for TODO keywords will be replaced by a single-key, direct
  2330. selection scheme.
  2331. When nil, fast selection is never used.
  2332. When the symbol `prefix', it will be used when `org-todo' is called
  2333. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2334. in an Org-mode buffer, and
  2335. `\\[universal-argument] t' in an agenda buffer.
  2336. When t, fast selection is used by default. In this case, the prefix
  2337. argument forces cycling instead.
  2338. In all cases, the special interface is only used if access keys have
  2339. actually been assigned by the user, i.e. if keywords in the configuration
  2340. are followed by a letter in parenthesis, like TODO(t)."
  2341. :group 'org-todo
  2342. :type '(choice
  2343. (const :tag "Never" nil)
  2344. (const :tag "By default" t)
  2345. (const :tag "Only with C-u C-c C-t" prefix)))
  2346. (defcustom org-provide-todo-statistics t
  2347. "Non-nil means update todo statistics after insert and toggle.
  2348. ALL-HEADLINES means update todo statistics by including headlines
  2349. with no TODO keyword as well, counting them as not done.
  2350. A list of TODO keywords means the same, but skip keywords that are
  2351. not in this list.
  2352. When set to a list of two lists, the first list contains keywords
  2353. to consider as TODO keywords, the second list contains keywords
  2354. to consider as DONE keywords.
  2355. When this is set, todo statistics is updated in the parent of the
  2356. current entry each time a todo state is changed."
  2357. :group 'org-todo
  2358. :type '(choice
  2359. (const :tag "Yes, only for TODO entries" t)
  2360. (const :tag "Yes, including all entries" all-headlines)
  2361. (repeat :tag "Yes, for TODOs in this list"
  2362. (string :tag "TODO keyword"))
  2363. (list :tag "Yes, for TODOs and DONEs in these lists"
  2364. (repeat (string :tag "TODO keyword"))
  2365. (repeat (string :tag "DONE keyword")))
  2366. (other :tag "No TODO statistics" nil)))
  2367. (defcustom org-hierarchical-todo-statistics t
  2368. "Non-nil means TODO statistics covers just direct children.
  2369. When nil, all entries in the subtree are considered.
  2370. This has only an effect if `org-provide-todo-statistics' is set.
  2371. To set this to nil for only a single subtree, use a COOKIE_DATA
  2372. property and include the word \"recursive\" into the value."
  2373. :group 'org-todo
  2374. :type 'boolean)
  2375. (defcustom org-after-todo-state-change-hook nil
  2376. "Hook which is run after the state of a TODO item was changed.
  2377. The new state (a string with a TODO keyword, or nil) is available in the
  2378. Lisp variable `org-state'."
  2379. :group 'org-todo
  2380. :type 'hook)
  2381. (defvar org-blocker-hook nil
  2382. "Hook for functions that are allowed to block a state change.
  2383. Functions in this hook should not modify the buffer.
  2384. Each function gets as its single argument a property list,
  2385. see `org-trigger-hook' for more information about this list.
  2386. If any of the functions in this hook returns nil, the state change
  2387. is blocked.")
  2388. (defvar org-trigger-hook nil
  2389. "Hook for functions that are triggered by a state change.
  2390. Each function gets as its single argument a property list with at
  2391. least the following elements:
  2392. (:type type-of-change :position pos-at-entry-start
  2393. :from old-state :to new-state)
  2394. Depending on the type, more properties may be present.
  2395. This mechanism is currently implemented for:
  2396. TODO state changes
  2397. ------------------
  2398. :type todo-state-change
  2399. :from previous state (keyword as a string), or nil, or a symbol
  2400. `todo' or `done', to indicate the general type of state.
  2401. :to new state, like in :from")
  2402. (defcustom org-enforce-todo-dependencies nil
  2403. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2404. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2405. be blocked if any prior sibling is not yet done.
  2406. Finally, if the parent is blocked because of ordered siblings of its own,
  2407. the child will also be blocked."
  2408. :set (lambda (var val)
  2409. (set var val)
  2410. (if val
  2411. (add-hook 'org-blocker-hook
  2412. 'org-block-todo-from-children-or-siblings-or-parent)
  2413. (remove-hook 'org-blocker-hook
  2414. 'org-block-todo-from-children-or-siblings-or-parent)))
  2415. :group 'org-todo
  2416. :type 'boolean)
  2417. (defcustom org-enforce-todo-checkbox-dependencies nil
  2418. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2419. When this is nil, checkboxes have no influence on switching TODO states.
  2420. When non-nil, you first need to check off all check boxes before the TODO
  2421. entry can be switched to DONE.
  2422. This variable needs to be set before org.el is loaded, and you need to
  2423. restart Emacs after a change to make the change effective. The only way
  2424. to change is while Emacs is running is through the customize interface."
  2425. :set (lambda (var val)
  2426. (set var val)
  2427. (if val
  2428. (add-hook 'org-blocker-hook
  2429. 'org-block-todo-from-checkboxes)
  2430. (remove-hook 'org-blocker-hook
  2431. 'org-block-todo-from-checkboxes)))
  2432. :group 'org-todo
  2433. :type 'boolean)
  2434. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2435. "Non-nil means inserting a TODO heading is treated as state change.
  2436. So when the command \\[org-insert-todo-heading] is used, state change
  2437. logging will apply if appropriate. When nil, the new TODO item will
  2438. be inserted directly, and no logging will take place."
  2439. :group 'org-todo
  2440. :type 'boolean)
  2441. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2442. "Non-nil means switching TODO states with S-cursor counts as state change.
  2443. This is the default behavior. However, setting this to nil allows a
  2444. convenient way to select a TODO state and bypass any logging associated
  2445. with that."
  2446. :group 'org-todo
  2447. :type 'boolean)
  2448. (defcustom org-todo-state-tags-triggers nil
  2449. "Tag changes that should be triggered by TODO state changes.
  2450. This is a list. Each entry is
  2451. (state-change (tag . flag) .......)
  2452. State-change can be a string with a state, and empty string to indicate the
  2453. state that has no TODO keyword, or it can be one of the symbols `todo'
  2454. or `done', meaning any not-done or done state, respectively."
  2455. :group 'org-todo
  2456. :group 'org-tags
  2457. :type '(repeat
  2458. (cons (choice :tag "When changing to"
  2459. (const :tag "Not-done state" todo)
  2460. (const :tag "Done state" done)
  2461. (string :tag "State"))
  2462. (repeat
  2463. (cons :tag "Tag action"
  2464. (string :tag "Tag")
  2465. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2466. (defcustom org-log-done nil
  2467. "Information to record when a task moves to the DONE state.
  2468. Possible values are:
  2469. nil Don't add anything, just change the keyword
  2470. time Add a time stamp to the task
  2471. note Prompt for a note and add it with template `org-log-note-headings'
  2472. This option can also be set with on a per-file-basis with
  2473. #+STARTUP: nologdone
  2474. #+STARTUP: logdone
  2475. #+STARTUP: lognotedone
  2476. You can have local logging settings for a subtree by setting the LOGGING
  2477. property to one or more of these keywords."
  2478. :group 'org-todo
  2479. :group 'org-progress
  2480. :type '(choice
  2481. (const :tag "No logging" nil)
  2482. (const :tag "Record CLOSED timestamp" time)
  2483. (const :tag "Record CLOSED timestamp with note." note)))
  2484. ;; Normalize old uses of org-log-done.
  2485. (cond
  2486. ((eq org-log-done t) (setq org-log-done 'time))
  2487. ((and (listp org-log-done) (memq 'done org-log-done))
  2488. (setq org-log-done 'note)))
  2489. (defcustom org-log-reschedule nil
  2490. "Information to record when the scheduling date of a tasks is modified.
  2491. Possible values are:
  2492. nil Don't add anything, just change the date
  2493. time Add a time stamp to the task
  2494. note Prompt for a note and add it with template `org-log-note-headings'
  2495. This option can also be set with on a per-file-basis with
  2496. #+STARTUP: nologreschedule
  2497. #+STARTUP: logreschedule
  2498. #+STARTUP: lognotereschedule"
  2499. :group 'org-todo
  2500. :group 'org-progress
  2501. :type '(choice
  2502. (const :tag "No logging" nil)
  2503. (const :tag "Record timestamp" time)
  2504. (const :tag "Record timestamp with note." note)))
  2505. (defcustom org-log-redeadline nil
  2506. "Information to record when the deadline date of a tasks is modified.
  2507. Possible values are:
  2508. nil Don't add anything, just change the date
  2509. time Add a time stamp to the task
  2510. note Prompt for a note and add it with template `org-log-note-headings'
  2511. This option can also be set with on a per-file-basis with
  2512. #+STARTUP: nologredeadline
  2513. #+STARTUP: logredeadline
  2514. #+STARTUP: lognoteredeadline
  2515. You can have local logging settings for a subtree by setting the LOGGING
  2516. property to one or more of these keywords."
  2517. :group 'org-todo
  2518. :group 'org-progress
  2519. :type '(choice
  2520. (const :tag "No logging" nil)
  2521. (const :tag "Record timestamp" time)
  2522. (const :tag "Record timestamp with note." note)))
  2523. (defcustom org-log-note-clock-out nil
  2524. "Non-nil means record a note when clocking out of an item.
  2525. This can also be configured on a per-file basis by adding one of
  2526. the following lines anywhere in the buffer:
  2527. #+STARTUP: lognoteclock-out
  2528. #+STARTUP: nolognoteclock-out"
  2529. :group 'org-todo
  2530. :group 'org-progress
  2531. :type 'boolean)
  2532. (defcustom org-log-done-with-time t
  2533. "Non-nil means the CLOSED time stamp will contain date and time.
  2534. When nil, only the date will be recorded."
  2535. :group 'org-progress
  2536. :type 'boolean)
  2537. (defcustom org-log-note-headings
  2538. '((done . "CLOSING NOTE %t")
  2539. (state . "State %-12s from %-12S %t")
  2540. (note . "Note taken on %t")
  2541. (reschedule . "Rescheduled from %S on %t")
  2542. (delschedule . "Not scheduled, was %S on %t")
  2543. (redeadline . "New deadline from %S on %t")
  2544. (deldeadline . "Removed deadline, was %S on %t")
  2545. (refile . "Refiled on %t")
  2546. (clock-out . ""))
  2547. "Headings for notes added to entries.
  2548. The value is an alist, with the car being a symbol indicating the
  2549. note context, and the cdr is the heading to be used. The heading
  2550. may also be the empty string. The following placeholders can be
  2551. used:
  2552. %t a time stamp.
  2553. %T an active time stamp instead the default inactive one
  2554. %d a short-format time stamp.
  2555. %D an active short-format time stamp.
  2556. %s the new TODO state or time stamp (inactive), in double quotes.
  2557. %S the old TODO state or time stamp (inactive), in double quotes.
  2558. %u the user name.
  2559. %U full user name.
  2560. In fact, it is not a good idea to change the `state' entry,
  2561. because Agenda Log mode depends on the format of these entries."
  2562. :group 'org-todo
  2563. :group 'org-progress
  2564. :type '(list :greedy t
  2565. (cons (const :tag "Heading when closing an item" done) string)
  2566. (cons (const :tag
  2567. "Heading when changing todo state (todo sequence only)"
  2568. state) string)
  2569. (cons (const :tag "Heading when just taking a note" note) string)
  2570. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2571. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2572. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2573. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2574. (cons (const :tag "Heading when refiling" refile) string)
  2575. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2576. (unless (assq 'note org-log-note-headings)
  2577. (push '(note . "%t") org-log-note-headings))
  2578. (defcustom org-log-into-drawer nil
  2579. "Non-nil means insert state change notes and time stamps into a drawer.
  2580. When nil, state changes notes will be inserted after the headline and
  2581. any scheduling and clock lines, but not inside a drawer.
  2582. The value of this variable should be the name of the drawer to use.
  2583. LOGBOOK is proposed as the default drawer for this purpose, you can
  2584. also set this to a string to define the drawer of your choice.
  2585. A value of t is also allowed, representing \"LOGBOOK\".
  2586. A value of t or nil can also be set with on a per-file-basis with
  2587. #+STARTUP: logdrawer
  2588. #+STARTUP: nologdrawer
  2589. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2590. will be ignored.
  2591. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2592. a subtree.
  2593. Do not check directly this variable in a Lisp program. Call
  2594. function `org-log-into-drawer' instead."
  2595. :group 'org-todo
  2596. :group 'org-progress
  2597. :type '(choice
  2598. (const :tag "Not into a drawer" nil)
  2599. (const :tag "LOGBOOK" t)
  2600. (string :tag "Other")))
  2601. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2602. (defun org-log-into-drawer ()
  2603. "Name of the log drawer, as a string, or nil.
  2604. This is the value of `org-log-into-drawer'. However, if the
  2605. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2606. be used instead of the default value."
  2607. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2608. (cond ((equal p "nil") nil)
  2609. ((equal p "t") "LOGBOOK")
  2610. ((stringp p) p)
  2611. (p "LOGBOOK")
  2612. ((stringp org-log-into-drawer) org-log-into-drawer)
  2613. (org-log-into-drawer "LOGBOOK"))))
  2614. (defcustom org-log-state-notes-insert-after-drawers nil
  2615. "Non-nil means insert state change notes after any drawers in entry.
  2616. Only the drawers that *immediately* follow the headline and the
  2617. deadline/scheduled line are skipped.
  2618. When nil, insert notes right after the heading and perhaps the line
  2619. with deadline/scheduling if present.
  2620. This variable will have no effect if `org-log-into-drawer' is
  2621. set."
  2622. :group 'org-todo
  2623. :group 'org-progress
  2624. :type 'boolean)
  2625. (defcustom org-log-states-order-reversed t
  2626. "Non-nil means the latest state note will be directly after heading.
  2627. When nil, the state change notes will be ordered according to time.
  2628. This option can also be set with on a per-file-basis with
  2629. #+STARTUP: logstatesreversed
  2630. #+STARTUP: nologstatesreversed"
  2631. :group 'org-todo
  2632. :group 'org-progress
  2633. :type 'boolean)
  2634. (defcustom org-todo-repeat-to-state nil
  2635. "The TODO state to which a repeater should return the repeating task.
  2636. By default this is the first task in a TODO sequence, or the previous state
  2637. in a TODO_TYP set. But you can specify another task here.
  2638. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2639. :group 'org-todo
  2640. :version "24.1"
  2641. :type '(choice (const :tag "Head of sequence" nil)
  2642. (string :tag "Specific state")))
  2643. (defcustom org-log-repeat 'time
  2644. "Non-nil means record moving through the DONE state when triggering repeat.
  2645. An auto-repeating task is immediately switched back to TODO when
  2646. marked DONE. If you are not logging state changes (by adding \"@\"
  2647. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2648. record a closing note, there will be no record of the task moving
  2649. through DONE. This variable forces taking a note anyway.
  2650. nil Don't force a record
  2651. time Record a time stamp
  2652. note Prompt for a note and add it with template `org-log-note-headings'
  2653. This option can also be set with on a per-file-basis with
  2654. #+STARTUP: nologrepeat
  2655. #+STARTUP: logrepeat
  2656. #+STARTUP: lognoterepeat
  2657. You can have local logging settings for a subtree by setting the LOGGING
  2658. property to one or more of these keywords."
  2659. :group 'org-todo
  2660. :group 'org-progress
  2661. :type '(choice
  2662. (const :tag "Don't force a record" nil)
  2663. (const :tag "Force recording the DONE state" time)
  2664. (const :tag "Force recording a note with the DONE state" note)))
  2665. (defgroup org-priorities nil
  2666. "Priorities in Org-mode."
  2667. :tag "Org Priorities"
  2668. :group 'org-todo)
  2669. (defcustom org-enable-priority-commands t
  2670. "Non-nil means priority commands are active.
  2671. When nil, these commands will be disabled, so that you never accidentally
  2672. set a priority."
  2673. :group 'org-priorities
  2674. :type 'boolean)
  2675. (defcustom org-highest-priority ?A
  2676. "The highest priority of TODO items. A character like ?A, ?B etc.
  2677. Must have a smaller ASCII number than `org-lowest-priority'."
  2678. :group 'org-priorities
  2679. :type 'character)
  2680. (defcustom org-lowest-priority ?C
  2681. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2682. Must have a larger ASCII number than `org-highest-priority'."
  2683. :group 'org-priorities
  2684. :type 'character)
  2685. (defcustom org-default-priority ?B
  2686. "The default priority of TODO items.
  2687. This is the priority an item gets if no explicit priority is given.
  2688. When starting to cycle on an empty priority the first step in the cycle
  2689. depends on `org-priority-start-cycle-with-default'. The resulting first
  2690. step priority must not exceed the range from `org-highest-priority' to
  2691. `org-lowest-priority' which means that `org-default-priority' has to be
  2692. in this range exclusive or inclusive the range boundaries. Else the
  2693. first step refuses to set the default and the second will fall back
  2694. to (depending on the command used) the highest or lowest priority."
  2695. :group 'org-priorities
  2696. :type 'character)
  2697. (defcustom org-priority-start-cycle-with-default t
  2698. "Non-nil means start with default priority when starting to cycle.
  2699. When this is nil, the first step in the cycle will be (depending on the
  2700. command used) one higher or lower than the default priority.
  2701. See also `org-default-priority'."
  2702. :group 'org-priorities
  2703. :type 'boolean)
  2704. (defcustom org-get-priority-function nil
  2705. "Function to extract the priority from a string.
  2706. The string is normally the headline. If this is nil Org computes the
  2707. priority from the priority cookie like [#A] in the headline. It returns
  2708. an integer, increasing by 1000 for each priority level.
  2709. The user can set a different function here, which should take a string
  2710. as an argument and return the numeric priority."
  2711. :group 'org-priorities
  2712. :version "24.1"
  2713. :type '(choice
  2714. (const nil)
  2715. (function)))
  2716. (defgroup org-time nil
  2717. "Options concerning time stamps and deadlines in Org-mode."
  2718. :tag "Org Time"
  2719. :group 'org)
  2720. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2721. "Number of minutes to round time stamps to.
  2722. \\<org-mode-map>\
  2723. These are two values, the first applies when first creating a time stamp.
  2724. The second applies when changing it with the commands `S-up' and `S-down'.
  2725. When changing the time stamp, this means that it will change in steps
  2726. of N minutes, as given by the second value.
  2727. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2728. numbers should be factors of 60, so for example 5, 10, 15.
  2729. When this is larger than 1, you can still force an exact time stamp by using
  2730. a double prefix argument to a time stamp command like \
  2731. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2732. and by using a prefix arg to `S-up/down' to specify the exact number
  2733. of minutes to shift."
  2734. :group 'org-time
  2735. :get (lambda (var) ; Make sure both elements are there
  2736. (if (integerp (default-value var))
  2737. (list (default-value var) 5)
  2738. (default-value var)))
  2739. :type '(list
  2740. (integer :tag "when inserting times")
  2741. (integer :tag "when modifying times")))
  2742. ;; Normalize old customizations of this variable.
  2743. (when (integerp org-time-stamp-rounding-minutes)
  2744. (setq org-time-stamp-rounding-minutes
  2745. (list org-time-stamp-rounding-minutes
  2746. org-time-stamp-rounding-minutes)))
  2747. (defcustom org-display-custom-times nil
  2748. "Non-nil means overlay custom formats over all time stamps.
  2749. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2750. To turn this on on a per-file basis, insert anywhere in the file:
  2751. #+STARTUP: customtime"
  2752. :group 'org-time
  2753. :set 'set-default
  2754. :type 'sexp)
  2755. (make-variable-buffer-local 'org-display-custom-times)
  2756. (defcustom org-time-stamp-custom-formats
  2757. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2758. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2759. These are overlaid over the default ISO format if the variable
  2760. `org-display-custom-times' is set. Time like %H:%M should be at the
  2761. end of the second format. The custom formats are also honored by export
  2762. commands, if custom time display is turned on at the time of export."
  2763. :group 'org-time
  2764. :type 'sexp)
  2765. (defun org-time-stamp-format (&optional long inactive)
  2766. "Get the right format for a time string."
  2767. (let ((f (if long (cdr org-time-stamp-formats)
  2768. (car org-time-stamp-formats))))
  2769. (if inactive
  2770. (concat "[" (substring f 1 -1) "]")
  2771. f)))
  2772. (defcustom org-time-clocksum-format
  2773. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2774. "The format string used when creating CLOCKSUM lines.
  2775. This is also used when Org mode generates a time duration.
  2776. The value can be a single format string containing two
  2777. %-sequences, which will be filled with the number of hours and
  2778. minutes in that order.
  2779. Alternatively, the value can be a plist associating any of the
  2780. keys :years, :months, :weeks, :days, :hours or :minutes with
  2781. format strings. The time duration is formatted using only the
  2782. time components that are needed and concatenating the results.
  2783. If a time unit in absent, it falls back to the next smallest
  2784. unit.
  2785. The keys :require-years, :require-months, :require-days,
  2786. :require-weeks, :require-hours, :require-minutes are also
  2787. meaningful. A non-nil value for these keys indicates that the
  2788. corresponding time component should always be included, even if
  2789. its value is 0.
  2790. For example,
  2791. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2792. :require-minutes t)
  2793. means durations longer than a day will be expressed in days,
  2794. hours and minutes, and durations less than a day will always be
  2795. expressed in hours and minutes (even for durations less than an
  2796. hour).
  2797. The value
  2798. (:days \"%dd\" :minutes \"%dm\")
  2799. means durations longer than a day will be expressed in days and
  2800. minutes, and durations less than a day will be expressed entirely
  2801. in minutes (even for durations longer than an hour)."
  2802. :group 'org-time
  2803. :group 'org-clock
  2804. :version "24.4"
  2805. :package-version '(Org . "8.0")
  2806. :type '(choice (string :tag "Format string")
  2807. (set :tag "Plist"
  2808. (group :inline t (const :tag "Years" :years)
  2809. (string :tag "Format string"))
  2810. (group :inline t
  2811. (const :tag "Always show years" :require-years)
  2812. (const t))
  2813. (group :inline t (const :tag "Months" :months)
  2814. (string :tag "Format string"))
  2815. (group :inline t
  2816. (const :tag "Always show months" :require-months)
  2817. (const t))
  2818. (group :inline t (const :tag "Weeks" :weeks)
  2819. (string :tag "Format string"))
  2820. (group :inline t
  2821. (const :tag "Always show weeks" :require-weeks)
  2822. (const t))
  2823. (group :inline t (const :tag "Days" :days)
  2824. (string :tag "Format string"))
  2825. (group :inline t
  2826. (const :tag "Always show days" :require-days)
  2827. (const t))
  2828. (group :inline t (const :tag "Hours" :hours)
  2829. (string :tag "Format string"))
  2830. (group :inline t
  2831. (const :tag "Always show hours" :require-hours)
  2832. (const t))
  2833. (group :inline t (const :tag "Minutes" :minutes)
  2834. (string :tag "Format string"))
  2835. (group :inline t
  2836. (const :tag "Always show minutes" :require-minutes)
  2837. (const t)))))
  2838. (defcustom org-time-clocksum-use-fractional nil
  2839. "When non-nil, \\[org-clock-display] uses fractional times.
  2840. See `org-time-clocksum-format' for more on time clock formats."
  2841. :group 'org-time
  2842. :group 'org-clock
  2843. :version "24.3"
  2844. :type 'boolean)
  2845. (defcustom org-time-clocksum-use-effort-durations nil
  2846. "When non-nil, \\[org-clock-display] uses effort durations.
  2847. E.g. by default, one day is considered to be a 8 hours effort,
  2848. so a task that has been clocked for 16 hours will be displayed
  2849. as during 2 days in the clock display or in the clocktable.
  2850. See `org-effort-durations' on how to set effort durations
  2851. and `org-time-clocksum-format' for more on time clock formats."
  2852. :group 'org-time
  2853. :group 'org-clock
  2854. :version "24.4"
  2855. :package-version '(Org . "8.0")
  2856. :type 'boolean)
  2857. (defcustom org-time-clocksum-fractional-format "%.2f"
  2858. "The format string used when creating CLOCKSUM lines,
  2859. or when Org mode generates a time duration, if
  2860. `org-time-clocksum-use-fractional' is enabled.
  2861. The value can be a single format string containing one
  2862. %-sequence, which will be filled with the number of hours as
  2863. a float.
  2864. Alternatively, the value can be a plist associating any of the
  2865. keys :years, :months, :weeks, :days, :hours or :minutes with
  2866. a format string. The time duration is formatted using the
  2867. largest time unit which gives a non-zero integer part. If all
  2868. specified formats have zero integer part, the smallest time unit
  2869. is used."
  2870. :group 'org-time
  2871. :type '(choice (string :tag "Format string")
  2872. (set (group :inline t (const :tag "Years" :years)
  2873. (string :tag "Format string"))
  2874. (group :inline t (const :tag "Months" :months)
  2875. (string :tag "Format string"))
  2876. (group :inline t (const :tag "Weeks" :weeks)
  2877. (string :tag "Format string"))
  2878. (group :inline t (const :tag "Days" :days)
  2879. (string :tag "Format string"))
  2880. (group :inline t (const :tag "Hours" :hours)
  2881. (string :tag "Format string"))
  2882. (group :inline t (const :tag "Minutes" :minutes)
  2883. (string :tag "Format string")))))
  2884. (defcustom org-deadline-warning-days 14
  2885. "Number of days before expiration during which a deadline becomes active.
  2886. This variable governs the display in sparse trees and in the agenda.
  2887. When 0 or negative, it means use this number (the absolute value of it)
  2888. even if a deadline has a different individual lead time specified.
  2889. Custom commands can set this variable in the options section."
  2890. :group 'org-time
  2891. :group 'org-agenda-daily/weekly
  2892. :type 'integer)
  2893. (defcustom org-scheduled-delay-days 0
  2894. "Number of days before a scheduled item becomes active.
  2895. This variable governs the display in sparse trees and in the agenda.
  2896. The default value (i.e. 0) means: don't delay scheduled item.
  2897. When negative, it means use this number (the absolute value of it)
  2898. even if a scheduled item has a different individual delay time
  2899. specified.
  2900. Custom commands can set this variable in the options section."
  2901. :group 'org-time
  2902. :group 'org-agenda-daily/weekly
  2903. :version "24.4"
  2904. :package-version '(Org . "8.0")
  2905. :type 'integer)
  2906. (defcustom org-read-date-prefer-future t
  2907. "Non-nil means assume future for incomplete date input from user.
  2908. This affects the following situations:
  2909. 1. The user gives a month but not a year.
  2910. For example, if it is April and you enter \"feb 2\", this will be read
  2911. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2912. 2. The user gives a day, but no month.
  2913. For example, if today is the 15th, and you enter \"3\", Org-mode will
  2914. read this as the third of *next* month. However, if you enter \"17\",
  2915. it will be considered as *this* month.
  2916. If you set this variable to the symbol `time', then also the following
  2917. will work:
  2918. 3. If the user gives a time.
  2919. If the time is before now, it will be interpreted as tomorrow.
  2920. Currently none of this works for ISO week specifications.
  2921. When this option is nil, the current day, month and year will always be
  2922. used as defaults.
  2923. See also `org-agenda-jump-prefer-future'."
  2924. :group 'org-time
  2925. :type '(choice
  2926. (const :tag "Never" nil)
  2927. (const :tag "Check month and day" t)
  2928. (const :tag "Check month, day, and time" time)))
  2929. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2930. "Should the agenda jump command prefer the future for incomplete dates?
  2931. The default is to do the same as configured in `org-read-date-prefer-future'.
  2932. But you can also set a deviating value here.
  2933. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2934. :group 'org-agenda
  2935. :group 'org-time
  2936. :version "24.1"
  2937. :type '(choice
  2938. (const :tag "Use org-read-date-prefer-future"
  2939. org-read-date-prefer-future)
  2940. (const :tag "Never" nil)
  2941. (const :tag "Always" t)))
  2942. (defcustom org-read-date-force-compatible-dates t
  2943. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2944. Depending on the system Emacs is running on, certain dates cannot
  2945. be represented with the type used internally to represent time.
  2946. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2947. correctly. Some systems allow for earlier dates, some for later,
  2948. some for both. One way to find out it to insert any date into an
  2949. Org buffer, putting the cursor on the year and hitting S-up and
  2950. S-down to test the range.
  2951. When this variable is set to t, the date/time prompt will not let
  2952. you specify dates outside the 1970-2037 range, so it is certain that
  2953. these dates will work in whatever version of Emacs you are
  2954. running, and also that you can move a file from one Emacs implementation
  2955. to another. WHenever Org is forcing the year for you, it will display
  2956. a message and beep.
  2957. When this variable is nil, Org will check if the date is
  2958. representable in the specific Emacs implementation you are using.
  2959. If not, it will force a year, usually the current year, and beep
  2960. to remind you. Currently this setting is not recommended because
  2961. the likelihood that you will open your Org files in an Emacs that
  2962. has limited date range is not negligible.
  2963. A workaround for this problem is to use diary sexp dates for time
  2964. stamps outside of this range."
  2965. :group 'org-time
  2966. :version "24.1"
  2967. :type 'boolean)
  2968. (defcustom org-read-date-display-live t
  2969. "Non-nil means display current interpretation of date prompt live.
  2970. This display will be in an overlay, in the minibuffer."
  2971. :group 'org-time
  2972. :type 'boolean)
  2973. (defcustom org-read-date-popup-calendar t
  2974. "Non-nil means pop up a calendar when prompting for a date.
  2975. In the calendar, the date can be selected with mouse-1. However, the
  2976. minibuffer will also be active, and you can simply enter the date as well.
  2977. When nil, only the minibuffer will be available."
  2978. :group 'org-time
  2979. :type 'boolean)
  2980. (defvaralias 'org-popup-calendar-for-date-prompt
  2981. 'org-read-date-popup-calendar)
  2982. (defcustom org-extend-today-until 0
  2983. "The hour when your day really ends. Must be an integer.
  2984. This has influence for the following applications:
  2985. - When switching the agenda to \"today\". It it is still earlier than
  2986. the time given here, the day recognized as TODAY is actually yesterday.
  2987. - When a date is read from the user and it is still before the time given
  2988. here, the current date and time will be assumed to be yesterday, 23:59.
  2989. Also, timestamps inserted in capture templates follow this rule.
  2990. IMPORTANT: This is a feature whose implementation is and likely will
  2991. remain incomplete. Really, it is only here because past midnight seems to
  2992. be the favorite working time of John Wiegley :-)"
  2993. :group 'org-time
  2994. :type 'integer)
  2995. (defcustom org-use-effective-time nil
  2996. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2997. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2998. \"effective time\" of any timestamps between midnight and 8am will be
  2999. 23:59 of the previous day."
  3000. :group 'org-time
  3001. :version "24.1"
  3002. :type 'boolean)
  3003. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3004. "When non-nil, use the last clock out time for `org-todo'.
  3005. Note that this option has precedence over the combined use of
  3006. `org-use-effective-time' and `org-extend-today-until'."
  3007. :group 'org-time
  3008. :version "24.4"
  3009. :package-version '(Org . "8.0")
  3010. :type 'boolean)
  3011. (defcustom org-edit-timestamp-down-means-later nil
  3012. "Non-nil means S-down will increase the time in a time stamp.
  3013. When nil, S-up will increase."
  3014. :group 'org-time
  3015. :type 'boolean)
  3016. (defcustom org-calendar-follow-timestamp-change t
  3017. "Non-nil means make the calendar window follow timestamp changes.
  3018. When a timestamp is modified and the calendar window is visible, it will be
  3019. moved to the new date."
  3020. :group 'org-time
  3021. :type 'boolean)
  3022. (defgroup org-tags nil
  3023. "Options concerning tags in Org-mode."
  3024. :tag "Org Tags"
  3025. :group 'org)
  3026. (defcustom org-tag-alist nil
  3027. "Default tags available in Org files.
  3028. The value of this variable is an alist. Associations either:
  3029. (TAG)
  3030. (TAG . SELECT)
  3031. (SPECIAL)
  3032. where TAG is a tag as a string, SELECT is a character, used to
  3033. select that tag through the fast tag selection interface, and
  3034. SPECIAL is one of the following keywords: `:startgroup',
  3035. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3036. `:newline'. These keywords are used to define a hierarchy of
  3037. tags. See manual for details.
  3038. When this variable is nil, Org mode bases tag input on what is
  3039. already in the buffer. The value can be overridden locally by
  3040. using a TAGS keyword, e.g.,
  3041. #+TAGS: tag1 tag2
  3042. See also `org-tag-persistent-alist' to sidestep this behavior."
  3043. :group 'org-tags
  3044. :type '(repeat
  3045. (choice
  3046. (cons (string :tag "Tag name")
  3047. (character :tag "Access char"))
  3048. (const :tag "Start radio group" (:startgroup))
  3049. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3050. (const :tag "Group tags delimiter" (:grouptags))
  3051. (const :tag "End radio group" (:endgroup))
  3052. (const :tag "End tag group, non distinct" (:endgrouptag))
  3053. (const :tag "New line" (:newline)))))
  3054. (defcustom org-tag-persistent-alist nil
  3055. "Tags always available in Org files.
  3056. The value of this variable is an alist. Associations either:
  3057. (TAG)
  3058. (TAG . SELECT)
  3059. (SPECIAL)
  3060. where TAG is a tag as a string, SELECT is a character, used to
  3061. select that tag through the fast tag selection interface, and
  3062. SPECIAL is one of the following keywords: `:startgroup',
  3063. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3064. `:newline'. These keywords are used to define a hierarchy of
  3065. tags. See manual for details.
  3066. Unlike to `org-tag-alist', tags defined in this variable do not
  3067. depend on a local TAGS keyword. Instead, to disable these tags
  3068. on a per-file basis, insert anywhere in the file:
  3069. #+STARTUP: noptag"
  3070. :group 'org-tags
  3071. :type '(repeat
  3072. (choice
  3073. (cons (string :tag "Tag name")
  3074. (character :tag "Access char"))
  3075. (const :tag "Start radio group" (:startgroup))
  3076. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3077. (const :tag "Group tags delimiter" (:grouptags))
  3078. (const :tag "End radio group" (:endgroup))
  3079. (const :tag "End tag group, non distinct" (:endgrouptag))
  3080. (const :tag "New line" (:newline)))))
  3081. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3082. "If non-nil, always offer completion for all tags of all agenda files.
  3083. Instead of customizing this variable directly, you might want to
  3084. set it locally for capture buffers, because there no list of
  3085. tags in that file can be created dynamically (there are none).
  3086. (add-hook \\='org-capture-mode-hook
  3087. (lambda ()
  3088. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3089. :group 'org-tags
  3090. :version "24.1"
  3091. :type 'boolean)
  3092. (defvar org-file-tags nil
  3093. "List of tags that can be inherited by all entries in the file.
  3094. The tags will be inherited if the variable `org-use-tag-inheritance'
  3095. says they should be.
  3096. This variable is populated from #+FILETAGS lines.")
  3097. (defcustom org-use-fast-tag-selection 'auto
  3098. "Non-nil means use fast tag selection scheme.
  3099. This is a special interface to select and deselect tags with single keys.
  3100. When nil, fast selection is never used.
  3101. When the symbol `auto', fast selection is used if and only if selection
  3102. characters for tags have been configured, either through the variable
  3103. `org-tag-alist' or through a #+TAGS line in the buffer.
  3104. When t, fast selection is always used and selection keys are assigned
  3105. automatically if necessary."
  3106. :group 'org-tags
  3107. :type '(choice
  3108. (const :tag "Always" t)
  3109. (const :tag "Never" nil)
  3110. (const :tag "When selection characters are configured" auto)))
  3111. (defcustom org-fast-tag-selection-single-key nil
  3112. "Non-nil means fast tag selection exits after first change.
  3113. When nil, you have to press RET to exit it.
  3114. During fast tag selection, you can toggle this flag with `C-c'.
  3115. This variable can also have the value `expert'. In this case, the window
  3116. displaying the tags menu is not even shown, until you press C-c again."
  3117. :group 'org-tags
  3118. :type '(choice
  3119. (const :tag "No" nil)
  3120. (const :tag "Yes" t)
  3121. (const :tag "Expert" expert)))
  3122. (defvar org-fast-tag-selection-include-todo nil
  3123. "Non-nil means fast tags selection interface will also offer TODO states.
  3124. This is an undocumented feature, you should not rely on it.")
  3125. (defcustom org-tags-column -77
  3126. "The column to which tags should be indented in a headline.
  3127. If this number is positive, it specifies the column. If it is negative,
  3128. it means that the tags should be flushright to that column. For example,
  3129. -80 works well for a normal 80 character screen.
  3130. When 0, place tags directly after headline text, with only one space in
  3131. between."
  3132. :group 'org-tags
  3133. :type 'integer)
  3134. (defcustom org-auto-align-tags t
  3135. "Non-nil keeps tags aligned when modifying headlines.
  3136. Some operations (i.e. demoting) change the length of a headline and
  3137. therefore shift the tags around. With this option turned on, after
  3138. each such operation the tags are again aligned to `org-tags-column'."
  3139. :group 'org-tags
  3140. :type 'boolean)
  3141. (defcustom org-use-tag-inheritance t
  3142. "Non-nil means tags in levels apply also for sublevels.
  3143. When nil, only the tags directly given in a specific line apply there.
  3144. This may also be a list of tags that should be inherited, or a regexp that
  3145. matches tags that should be inherited. Additional control is possible
  3146. with the variable `org-tags-exclude-from-inheritance' which gives an
  3147. explicit list of tags to be excluded from inheritance, even if the value of
  3148. `org-use-tag-inheritance' would select it for inheritance.
  3149. If this option is t, a match early-on in a tree can lead to a large
  3150. number of matches in the subtree when constructing the agenda or creating
  3151. a sparse tree. If you only want to see the first match in a tree during
  3152. a search, check out the variable `org-tags-match-list-sublevels'."
  3153. :group 'org-tags
  3154. :type '(choice
  3155. (const :tag "Not" nil)
  3156. (const :tag "Always" t)
  3157. (repeat :tag "Specific tags" (string :tag "Tag"))
  3158. (regexp :tag "Tags matched by regexp")))
  3159. (defcustom org-tags-exclude-from-inheritance nil
  3160. "List of tags that should never be inherited.
  3161. This is a way to exclude a few tags from inheritance. For way to do
  3162. the opposite, to actively allow inheritance for selected tags,
  3163. see the variable `org-use-tag-inheritance'."
  3164. :group 'org-tags
  3165. :type '(repeat (string :tag "Tag")))
  3166. (defun org-tag-inherit-p (tag)
  3167. "Check if TAG is one that should be inherited."
  3168. (cond
  3169. ((member tag org-tags-exclude-from-inheritance) nil)
  3170. ((eq org-use-tag-inheritance t) t)
  3171. ((not org-use-tag-inheritance) nil)
  3172. ((stringp org-use-tag-inheritance)
  3173. (string-match org-use-tag-inheritance tag))
  3174. ((listp org-use-tag-inheritance)
  3175. (member tag org-use-tag-inheritance))
  3176. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3177. (defcustom org-tags-match-list-sublevels t
  3178. "Non-nil means list also sublevels of headlines matching a search.
  3179. This variable applies to tags/property searches, and also to stuck
  3180. projects because this search is based on a tags match as well.
  3181. When set to the symbol `indented', sublevels are indented with
  3182. leading dots.
  3183. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3184. the sublevels of a headline matching a tag search often also match
  3185. the same search. Listing all of them can create very long lists.
  3186. Setting this variable to nil causes subtrees of a match to be skipped.
  3187. This variable is semi-obsolete and probably should always be true. It
  3188. is better to limit inheritance to certain tags using the variables
  3189. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3190. :group 'org-tags
  3191. :type '(choice
  3192. (const :tag "No, don't list them" nil)
  3193. (const :tag "Yes, do list them" t)
  3194. (const :tag "List them, indented with leading dots" indented)))
  3195. (defcustom org-tags-sort-function nil
  3196. "When set, tags are sorted using this function as a comparator."
  3197. :group 'org-tags
  3198. :type '(choice
  3199. (const :tag "No sorting" nil)
  3200. (const :tag "Alphabetical" string<)
  3201. (const :tag "Reverse alphabetical" string>)
  3202. (function :tag "Custom function" nil)))
  3203. (defvar org-tags-history nil
  3204. "History of minibuffer reads for tags.")
  3205. (defvar org-last-tags-completion-table nil
  3206. "The last used completion table for tags.")
  3207. (defvar org-after-tags-change-hook nil
  3208. "Hook that is run after the tags in a line have changed.")
  3209. (defgroup org-properties nil
  3210. "Options concerning properties in Org-mode."
  3211. :tag "Org Properties"
  3212. :group 'org)
  3213. (defcustom org-property-format "%-10s %s"
  3214. "How property key/value pairs should be formatted by `indent-line'.
  3215. When `indent-line' hits a property definition, it will format the line
  3216. according to this format, mainly to make sure that the values are
  3217. lined-up with respect to each other."
  3218. :group 'org-properties
  3219. :type 'string)
  3220. (defcustom org-properties-postprocess-alist nil
  3221. "Alist of properties and functions to adjust inserted values.
  3222. Elements of this alist must be of the form
  3223. ([string] [function])
  3224. where [string] must be a property name and [function] must be a
  3225. lambda expression: this lambda expression must take one argument,
  3226. the value to adjust, and return the new value as a string.
  3227. For example, this element will allow the property \"Remaining\"
  3228. to be updated wrt the relation between the \"Effort\" property
  3229. and the clock summary:
  3230. ((\"Remaining\" (lambda(value)
  3231. (let ((clocksum (org-clock-sum-current-item))
  3232. (effort (org-duration-string-to-minutes
  3233. (org-entry-get (point) \"Effort\"))))
  3234. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3235. :group 'org-properties
  3236. :version "24.1"
  3237. :type '(alist :key-type (string :tag "Property")
  3238. :value-type (function :tag "Function")))
  3239. (defcustom org-use-property-inheritance nil
  3240. "Non-nil means properties apply also for sublevels.
  3241. This setting is chiefly used during property searches. Turning it on can
  3242. cause significant overhead when doing a search, which is why it is not
  3243. on by default.
  3244. When nil, only the properties directly given in the current entry count.
  3245. When t, every property is inherited. The value may also be a list of
  3246. properties that should have inheritance, or a regular expression matching
  3247. properties that should be inherited.
  3248. However, note that some special properties use inheritance under special
  3249. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3250. and the properties ending in \"_ALL\" when they are used as descriptor
  3251. for valid values of a property.
  3252. Note for programmers:
  3253. When querying an entry with `org-entry-get', you can control if inheritance
  3254. should be used. By default, `org-entry-get' looks only at the local
  3255. properties. You can request inheritance by setting the inherit argument
  3256. to t (to force inheritance) or to `selective' (to respect the setting
  3257. in this variable)."
  3258. :group 'org-properties
  3259. :type '(choice
  3260. (const :tag "Not" nil)
  3261. (const :tag "Always" t)
  3262. (repeat :tag "Specific properties" (string :tag "Property"))
  3263. (regexp :tag "Properties matched by regexp")))
  3264. (defun org-property-inherit-p (property)
  3265. "Check if PROPERTY is one that should be inherited."
  3266. (cond
  3267. ((eq org-use-property-inheritance t) t)
  3268. ((not org-use-property-inheritance) nil)
  3269. ((stringp org-use-property-inheritance)
  3270. (string-match org-use-property-inheritance property))
  3271. ((listp org-use-property-inheritance)
  3272. (member property org-use-property-inheritance))
  3273. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3274. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3275. "The default column format, if no other format has been defined.
  3276. This variable can be set on the per-file basis by inserting a line
  3277. #+COLUMNS: %25ITEM ....."
  3278. :group 'org-properties
  3279. :type 'string)
  3280. (defcustom org-columns-ellipses ".."
  3281. "The ellipses to be used when a field in column view is truncated.
  3282. When this is the empty string, as many characters as possible are shown,
  3283. but then there will be no visual indication that the field has been truncated.
  3284. When this is a string of length N, the last N characters of a truncated
  3285. field are replaced by this string. If the column is narrower than the
  3286. ellipses string, only part of the ellipses string will be shown."
  3287. :group 'org-properties
  3288. :type 'string)
  3289. (defconst org-global-properties-fixed
  3290. '(("VISIBILITY_ALL" . "folded children content all")
  3291. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3292. "List of property/value pairs that can be inherited by any entry.
  3293. These are fixed values, for the preset properties. The user variable
  3294. that can be used to add to this list is `org-global-properties'.
  3295. The entries in this list are cons cells where the car is a property
  3296. name and cdr is a string with the value. If the value represents
  3297. multiple items like an \"_ALL\" property, separate the items by
  3298. spaces.")
  3299. (defcustom org-global-properties nil
  3300. "List of property/value pairs that can be inherited by any entry.
  3301. This list will be combined with the constant `org-global-properties-fixed'.
  3302. The entries in this list are cons cells where the car is a property
  3303. name and cdr is a string with the value.
  3304. You can set buffer-local values for the same purpose in the variable
  3305. `org-file-properties' this by adding lines like
  3306. #+PROPERTY: NAME VALUE"
  3307. :group 'org-properties
  3308. :type '(repeat
  3309. (cons (string :tag "Property")
  3310. (string :tag "Value"))))
  3311. (defvar-local org-file-properties nil
  3312. "List of property/value pairs that can be inherited by any entry.
  3313. Valid for the current buffer.
  3314. This variable is populated from #+PROPERTY lines.")
  3315. (defgroup org-agenda nil
  3316. "Options concerning agenda views in Org-mode."
  3317. :tag "Org Agenda"
  3318. :group 'org)
  3319. (defvar-local org-category nil
  3320. "Variable used by org files to set a category for agenda display.
  3321. Such files should use a file variable to set it, for example
  3322. # -*- mode: org; org-category: \"ELisp\"
  3323. or contain a special line
  3324. #+CATEGORY: ELisp
  3325. If the file does not specify a category, then file's base name
  3326. is used instead.")
  3327. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3328. (defcustom org-agenda-files nil
  3329. "The files to be used for agenda display.
  3330. Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
  3331. \\[org-remove-file]. You can also use customize to edit the list.
  3332. If an entry is a directory, all files in that directory that are matched by
  3333. `org-agenda-file-regexp' will be part of the file list.
  3334. If the value of the variable is not a list but a single file name, then
  3335. the list of agenda files is actually stored and maintained in that file, one
  3336. agenda file per line. In this file paths can be given relative to
  3337. `org-directory'. Tilde expansion and environment variable substitution
  3338. are also made."
  3339. :group 'org-agenda
  3340. :type '(choice
  3341. (repeat :tag "List of files and directories" file)
  3342. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3343. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3344. "Regular expression to match files for `org-agenda-files'.
  3345. If any element in the list in that variable contains a directory instead
  3346. of a normal file, all files in that directory that are matched by this
  3347. regular expression will be included."
  3348. :group 'org-agenda
  3349. :type 'regexp)
  3350. (defcustom org-agenda-text-search-extra-files nil
  3351. "List of extra files to be searched by text search commands.
  3352. These files will be searched in addition to the agenda files by the
  3353. commands `org-search-view' (`\\[org-agenda] s') \
  3354. and `org-occur-in-agenda-files'.
  3355. Note that these files will only be searched for text search commands,
  3356. not for the other agenda views like todo lists, tag searches or the weekly
  3357. agenda. This variable is intended to list notes and possibly archive files
  3358. that should also be searched by these two commands.
  3359. In fact, if the first element in the list is the symbol `agenda-archives',
  3360. then all archive files of all agenda files will be added to the search
  3361. scope."
  3362. :group 'org-agenda
  3363. :type '(set :greedy t
  3364. (const :tag "Agenda Archives" agenda-archives)
  3365. (repeat :inline t (file))))
  3366. (defvaralias 'org-agenda-multi-occur-extra-files
  3367. 'org-agenda-text-search-extra-files)
  3368. (defcustom org-agenda-skip-unavailable-files nil
  3369. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3370. A nil value means to remove them, after a query, from the list."
  3371. :group 'org-agenda
  3372. :type 'boolean)
  3373. (defcustom org-calendar-to-agenda-key [?c]
  3374. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3375. The command `org-calendar-goto-agenda' will be bound to this key. The
  3376. default is the character `c' because then `c' can be used to switch back and
  3377. forth between agenda and calendar."
  3378. :group 'org-agenda
  3379. :type 'sexp)
  3380. (defcustom org-calendar-insert-diary-entry-key [?i]
  3381. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3382. This option is irrelevant until `org-agenda-diary-file' has been configured
  3383. to point to an Org-mode file. When that is the case, the command
  3384. `org-agenda-diary-entry' will be bound to the key given here, by default
  3385. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3386. if you want to continue doing this, you need to change this to a different
  3387. key."
  3388. :group 'org-agenda
  3389. :type 'sexp)
  3390. (defcustom org-agenda-diary-file 'diary-file
  3391. "File to which to add new entries with the `i' key in agenda and calendar.
  3392. When this is the symbol `diary-file', the functionality in the Emacs
  3393. calendar will be used to add entries to the `diary-file'. But when this
  3394. points to a file, `org-agenda-diary-entry' will be used instead."
  3395. :group 'org-agenda
  3396. :type '(choice
  3397. (const :tag "The standard Emacs diary file" diary-file)
  3398. (file :tag "Special Org file diary entries")))
  3399. (eval-after-load "calendar"
  3400. '(progn
  3401. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3402. 'org-calendar-goto-agenda)
  3403. (add-hook 'calendar-mode-hook
  3404. (lambda ()
  3405. (unless (eq org-agenda-diary-file 'diary-file)
  3406. (define-key calendar-mode-map
  3407. org-calendar-insert-diary-entry-key
  3408. 'org-agenda-diary-entry))))))
  3409. (defgroup org-latex nil
  3410. "Options for embedding LaTeX code into Org-mode."
  3411. :tag "Org LaTeX"
  3412. :group 'org)
  3413. (defcustom org-format-latex-options
  3414. '(:foreground default :background default :scale 1.0
  3415. :html-foreground "Black" :html-background "Transparent"
  3416. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3417. "Options for creating images from LaTeX fragments.
  3418. This is a property list with the following properties:
  3419. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3420. `default' means use the foreground of the default face.
  3421. `auto' means use the foreground from the text face.
  3422. :background the background color, or \"Transparent\".
  3423. `default' means use the background of the default face.
  3424. `auto' means use the background from the text face.
  3425. :scale a scaling factor for the size of the images, to get more pixels
  3426. :html-foreground, :html-background, :html-scale
  3427. the same numbers for HTML export.
  3428. :matchers a list indicating which matchers should be used to
  3429. find LaTeX fragments. Valid members of this list are:
  3430. \"begin\" find environments
  3431. \"$1\" find single characters surrounded by $.$
  3432. \"$\" find math expressions surrounded by $...$
  3433. \"$$\" find math expressions surrounded by $$....$$
  3434. \"\\(\" find math expressions surrounded by \\(...\\)
  3435. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3436. :group 'org-latex
  3437. :type 'plist)
  3438. (defcustom org-format-latex-signal-error t
  3439. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3440. When nil, just push out a message."
  3441. :group 'org-latex
  3442. :version "24.1"
  3443. :type 'boolean)
  3444. (defcustom org-latex-to-mathml-jar-file nil
  3445. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3446. Use this to specify additional executable file say a jar file.
  3447. When using MathToWeb as the converter, specify the full-path to
  3448. your mathtoweb.jar file."
  3449. :group 'org-latex
  3450. :version "24.1"
  3451. :type '(choice
  3452. (const :tag "None" nil)
  3453. (file :tag "JAR file" :must-match t)))
  3454. (defcustom org-latex-to-mathml-convert-command nil
  3455. "Command to convert LaTeX fragments to MathML.
  3456. Replace format-specifiers in the command as noted below and use
  3457. `shell-command' to convert LaTeX to MathML.
  3458. %j: Executable file in fully expanded form as specified by
  3459. `org-latex-to-mathml-jar-file'.
  3460. %I: Input LaTeX file in fully expanded form.
  3461. %i: The latex fragment to be converted.
  3462. %o: Output MathML file.
  3463. This command is used by `org-create-math-formula'.
  3464. When using MathToWeb as the converter, set this option to
  3465. \"java -jar %j -unicode -force -df %o %I\".
  3466. When using LaTeXML set this option to
  3467. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3468. :group 'org-latex
  3469. :version "24.1"
  3470. :type '(choice
  3471. (const :tag "None" nil)
  3472. (string :tag "\nShell command")))
  3473. (defcustom org-preview-latex-default-process 'dvipng
  3474. "The default process to convert LaTeX fragments to image files.
  3475. All available processes and theirs documents can be found in
  3476. `org-preview-latex-process-alist', which see."
  3477. :group 'org-latex
  3478. :version "25.2"
  3479. :package-version '(Org . "9.0")
  3480. :type 'symbol)
  3481. (defcustom org-preview-latex-process-alist
  3482. '((dvipng
  3483. :programs ("latex" "dvipng" "gs")
  3484. :description "dvi > png"
  3485. :message "you need to install the programs: latex, dvipng and ghostscript."
  3486. :image-input-type "dvi"
  3487. :image-output-type "png"
  3488. :image-size-adjust (1.0 . 1.0)
  3489. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3490. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
  3491. (dvisvgm
  3492. :programs ("latex" "dvisvgm" "gs")
  3493. :description "dvi > svg"
  3494. :message "you need to install the programs: latex, dvisvgm and ghostscript."
  3495. :use-xcolor t
  3496. :image-input-type "dvi"
  3497. :image-output-type "svg"
  3498. :image-size-adjust (1.7 . 1.5)
  3499. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3500. :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
  3501. (imagemagick
  3502. :programs ("latex" "convert" "gs")
  3503. :description "pdf > png"
  3504. :message
  3505. "you need to install the programs: latex, imagemagick and ghostscript."
  3506. :use-xcolor t
  3507. :image-input-type "pdf"
  3508. :image-output-type "png"
  3509. :image-size-adjust (1.0 . 1.0)
  3510. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3511. :image-converter
  3512. ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
  3513. "Definitions of external processes for LaTeX previewing.
  3514. Org mode can use some external commands to generate TeX snippet's images for
  3515. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3516. `org-create-formula-image' how to call them.
  3517. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3518. PROPERTIES accepts the following attributes:
  3519. :programs list of strings, required programs.
  3520. :description string, describe the process.
  3521. :message string, message it when required programs cannot be found.
  3522. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3523. :image-output-type string, output file type of image converter (e.g., \"png\").
  3524. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3525. deal with background and foreground color of image.
  3526. Otherwise, dvipng style background and foregroud color
  3527. format are generated. You may then refer to them in
  3528. command options with \"%F\" and \"%B\".
  3529. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3530. image size showed in buffer and the cdr element is for
  3531. HTML file. This option is only useful for process
  3532. developers, users should use variable
  3533. `org-format-latex-options' instead.
  3534. :post-clean list of strings, files matched are to be cleaned up once
  3535. the image is generated. When nil, the files with \".dvi\",
  3536. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3537. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3538. be cleaned up.
  3539. :latex-header list of strings, the LaTeX header of the snippet file.
  3540. When nil, the fallback value is used instead, which is
  3541. controlled by `org-format-latex-header',
  3542. `org-latex-default-packages-alist' and
  3543. `org-latex-packages-alist', which see.
  3544. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3545. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3546. replaced with values defined below.
  3547. :image-converter list of image converter commands strings. Each of them is
  3548. given to the shell and supports any of the following
  3549. place-holders defined below.
  3550. Place-holders used by `:image-converter' and `:latex-compiler':
  3551. %f input file name.
  3552. %b base name of input file.
  3553. %o base directory of input file.
  3554. Place-holders only used by `:image-converter':
  3555. %F foreground of image
  3556. %B background of image
  3557. %D dpi, which is used to adjust image size by some processing commands.
  3558. %S the image size scale ratio, which is used to adjust image size by some
  3559. processing commands."
  3560. :group 'org-latex
  3561. :version "25.2"
  3562. :package-version '(Org . "9.0")
  3563. :type '(alist :tag "LaTeX to image backends"
  3564. :value-type (plist)))
  3565. (defcustom org-preview-latex-image-directory "ltximg/"
  3566. "Path to store latex preview images.
  3567. A relative path here creates many directories relative to the
  3568. processed org files paths. An absolute path puts all preview
  3569. images at the same place."
  3570. :group 'org-latex
  3571. :version "25.1"
  3572. :package-version '(Org . "9.0")
  3573. :type 'string)
  3574. (defun org-format-latex-mathml-available-p ()
  3575. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3576. (save-match-data
  3577. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3578. org-latex-to-mathml-convert-command)
  3579. (let ((executable (car (split-string
  3580. org-latex-to-mathml-convert-command))))
  3581. (when (executable-find executable)
  3582. (if (string-match
  3583. "%j" org-latex-to-mathml-convert-command)
  3584. (file-readable-p org-latex-to-mathml-jar-file)
  3585. t))))))
  3586. (defcustom org-format-latex-header "\\documentclass{article}
  3587. \\usepackage[usenames]{color}
  3588. \[PACKAGES]
  3589. \[DEFAULT-PACKAGES]
  3590. \\pagestyle{empty} % do not remove
  3591. % The settings below are copied from fullpage.sty
  3592. \\setlength{\\textwidth}{\\paperwidth}
  3593. \\addtolength{\\textwidth}{-3cm}
  3594. \\setlength{\\oddsidemargin}{1.5cm}
  3595. \\addtolength{\\oddsidemargin}{-2.54cm}
  3596. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3597. \\setlength{\\textheight}{\\paperheight}
  3598. \\addtolength{\\textheight}{-\\headheight}
  3599. \\addtolength{\\textheight}{-\\headsep}
  3600. \\addtolength{\\textheight}{-\\footskip}
  3601. \\addtolength{\\textheight}{-3cm}
  3602. \\setlength{\\topmargin}{1.5cm}
  3603. \\addtolength{\\topmargin}{-2.54cm}"
  3604. "The document header used for processing LaTeX fragments.
  3605. It is imperative that this header make sure that no page number
  3606. appears on the page. The package defined in the variables
  3607. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3608. will either replace the placeholder \"[PACKAGES]\" in this
  3609. header, or they will be appended."
  3610. :group 'org-latex
  3611. :type 'string)
  3612. (defun org-set-packages-alist (var val)
  3613. "Set the packages alist and make sure it has 3 elements per entry."
  3614. (set var (mapcar (lambda (x)
  3615. (if (and (consp x) (= (length x) 2))
  3616. (list (car x) (nth 1 x) t)
  3617. x))
  3618. val)))
  3619. (defun org-get-packages-alist (var)
  3620. "Get the packages alist and make sure it has 3 elements per entry."
  3621. (mapcar (lambda (x)
  3622. (if (and (consp x) (= (length x) 2))
  3623. (list (car x) (nth 1 x) t)
  3624. x))
  3625. (default-value var)))
  3626. (defcustom org-latex-default-packages-alist
  3627. '(("AUTO" "inputenc" t ("pdflatex"))
  3628. ("T1" "fontenc" t ("pdflatex"))
  3629. ("" "graphicx" t)
  3630. ("" "grffile" t)
  3631. ("" "longtable" nil)
  3632. ("" "wrapfig" nil)
  3633. ("" "rotating" nil)
  3634. ("normalem" "ulem" t)
  3635. ("" "amsmath" t)
  3636. ("" "textcomp" t)
  3637. ("" "amssymb" t)
  3638. ("" "capt-of" nil)
  3639. ("" "hyperref" nil))
  3640. "Alist of default packages to be inserted in the header.
  3641. Change this only if one of the packages here causes an
  3642. incompatibility with another package you are using.
  3643. The packages in this list are needed by one part or another of
  3644. Org mode to function properly:
  3645. - inputenc, fontenc: for basic font and character selection
  3646. - graphicx: for including images
  3647. - grffile: allow periods and spaces in graphics file names
  3648. - longtable: For multipage tables
  3649. - wrapfig: for figure placement
  3650. - rotating: for sideways figures and tables
  3651. - ulem: for underline and strike-through
  3652. - amsmath: for subscript and superscript and math environments
  3653. - textcomp, amssymb: for various symbols used
  3654. for interpreting the entities in `org-entities'. You can skip
  3655. some of these packages if you don't use any of their symbols.
  3656. - capt-of: for captions outside of floats
  3657. - hyperref: for cross references
  3658. Therefore you should not modify this variable unless you know
  3659. what you are doing. The one reason to change it anyway is that
  3660. you might be loading some other package that conflicts with one
  3661. of the default packages. Each element is either a cell or
  3662. a string.
  3663. A cell is of the format
  3664. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3665. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3666. when compiling LaTeX snippets into images for inclusion into
  3667. non-LaTeX output. COMPILERS is a list of compilers that should
  3668. include the package, see `org-latex-compiler'. If the document
  3669. compiler is not in the list, and the list is non-nil, the package
  3670. will not be inserted in the final document.
  3671. A string will be inserted as-is in the header of the document."
  3672. :group 'org-latex
  3673. :group 'org-export-latex
  3674. :set 'org-set-packages-alist
  3675. :get 'org-get-packages-alist
  3676. :version "25.1"
  3677. :package-version '(Org . "8.3")
  3678. :type '(repeat
  3679. (choice
  3680. (list :tag "options/package pair"
  3681. (string :tag "options")
  3682. (string :tag "package")
  3683. (boolean :tag "Snippet"))
  3684. (string :tag "A line of LaTeX"))))
  3685. (defcustom org-latex-packages-alist nil
  3686. "Alist of packages to be inserted in every LaTeX header.
  3687. These will be inserted after `org-latex-default-packages-alist'.
  3688. Each element is either a cell or a string.
  3689. A cell is of the format:
  3690. (\"options\" \"package\" SNIPPET-FLAG)
  3691. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3692. needed when turning LaTeX snippets into images for inclusion into
  3693. non-LaTeX output.
  3694. A string will be inserted as-is in the header of the document.
  3695. Make sure that you only list packages here which:
  3696. - you want in every file;
  3697. - do not conflict with the setup in `org-format-latex-header';
  3698. - do not conflict with the default packages in
  3699. `org-latex-default-packages-alist'."
  3700. :group 'org-latex
  3701. :group 'org-export-latex
  3702. :set 'org-set-packages-alist
  3703. :get 'org-get-packages-alist
  3704. :type '(repeat
  3705. (choice
  3706. (list :tag "options/package pair"
  3707. (string :tag "options")
  3708. (string :tag "package")
  3709. (boolean :tag "Snippet"))
  3710. (string :tag "A line of LaTeX"))))
  3711. (defgroup org-appearance nil
  3712. "Settings for Org-mode appearance."
  3713. :tag "Org Appearance"
  3714. :group 'org)
  3715. (defcustom org-level-color-stars-only nil
  3716. "Non-nil means fontify only the stars in each headline.
  3717. When nil, the entire headline is fontified.
  3718. Changing it requires restart of `font-lock-mode' to become effective
  3719. also in regions already fontified."
  3720. :group 'org-appearance
  3721. :type 'boolean)
  3722. (defcustom org-hide-leading-stars nil
  3723. "Non-nil means hide the first N-1 stars in a headline.
  3724. This works by using the face `org-hide' for these stars. This
  3725. face is white for a light background, and black for a dark
  3726. background. You may have to customize the face `org-hide' to
  3727. make this work.
  3728. Changing it requires restart of `font-lock-mode' to become effective
  3729. also in regions already fontified.
  3730. You may also set this on a per-file basis by adding one of the following
  3731. lines to the buffer:
  3732. #+STARTUP: hidestars
  3733. #+STARTUP: showstars"
  3734. :group 'org-appearance
  3735. :type 'boolean)
  3736. (defcustom org-hidden-keywords nil
  3737. "List of symbols corresponding to keywords to be hidden the org buffer.
  3738. For example, a value \\='(title) for this list will make the document's title
  3739. appear in the buffer without the initial #+TITLE: keyword."
  3740. :group 'org-appearance
  3741. :version "24.1"
  3742. :type '(set (const :tag "#+AUTHOR" author)
  3743. (const :tag "#+DATE" date)
  3744. (const :tag "#+EMAIL" email)
  3745. (const :tag "#+TITLE" title)))
  3746. (defcustom org-custom-properties nil
  3747. "List of properties (as strings) with a special meaning.
  3748. The default use of these custom properties is to let the user
  3749. hide them with `org-toggle-custom-properties-visibility'."
  3750. :group 'org-properties
  3751. :group 'org-appearance
  3752. :version "24.3"
  3753. :type '(repeat (string :tag "Property Name")))
  3754. (defcustom org-fontify-done-headline nil
  3755. "Non-nil means change the face of a headline if it is marked DONE.
  3756. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3757. When this is non-nil, the headline after the keyword is set to the
  3758. `org-headline-done' as an additional indication."
  3759. :group 'org-appearance
  3760. :type 'boolean)
  3761. (defcustom org-fontify-emphasized-text t
  3762. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3763. Changing this variable requires a restart of Emacs to take effect."
  3764. :group 'org-appearance
  3765. :type 'boolean)
  3766. (defcustom org-fontify-whole-heading-line nil
  3767. "Non-nil means fontify the whole line for headings.
  3768. This is useful when setting a background color for the
  3769. org-level-* faces."
  3770. :group 'org-appearance
  3771. :type 'boolean)
  3772. (defcustom org-highlight-latex-and-related nil
  3773. "Non-nil means highlight LaTeX related syntax in the buffer.
  3774. When non nil, the value should be a list containing any of the
  3775. following symbols:
  3776. `latex' Highlight LaTeX snippets and environments.
  3777. `script' Highlight subscript and superscript.
  3778. `entities' Highlight entities."
  3779. :group 'org-appearance
  3780. :version "24.4"
  3781. :package-version '(Org . "8.0")
  3782. :type '(choice
  3783. (const :tag "No highlighting" nil)
  3784. (set :greedy t :tag "Highlight"
  3785. (const :tag "LaTeX snippets and environments" latex)
  3786. (const :tag "Subscript and superscript" script)
  3787. (const :tag "Entities" entities))))
  3788. (defcustom org-hide-emphasis-markers nil
  3789. "Non-nil mean font-lock should hide the emphasis marker characters."
  3790. :group 'org-appearance
  3791. :type 'boolean)
  3792. (defcustom org-hide-macro-markers nil
  3793. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3794. :group 'org-appearance
  3795. :type 'boolean)
  3796. (defcustom org-pretty-entities nil
  3797. "Non-nil means show entities as UTF8 characters.
  3798. When nil, the \\name form remains in the buffer."
  3799. :group 'org-appearance
  3800. :version "24.1"
  3801. :type 'boolean)
  3802. (defcustom org-pretty-entities-include-sub-superscripts t
  3803. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3804. :group 'org-appearance
  3805. :version "24.1"
  3806. :type 'boolean)
  3807. (defvar org-emph-re nil
  3808. "Regular expression for matching emphasis.
  3809. After a match, the match groups contain these elements:
  3810. 0 The match of the full regular expression, including the characters
  3811. before and after the proper match
  3812. 1 The character before the proper match, or empty at beginning of line
  3813. 2 The proper match, including the leading and trailing markers
  3814. 3 The leading marker like * or /, indicating the type of highlighting
  3815. 4 The text between the emphasis markers, not including the markers
  3816. 5 The character after the match, empty at the end of a line")
  3817. (defvar org-verbatim-re nil
  3818. "Regular expression for matching verbatim text.")
  3819. (defvar org-emphasis-regexp-components) ; defined just below
  3820. (defvar org-emphasis-alist) ; defined just below
  3821. (defun org-set-emph-re (var val)
  3822. "Set variable and compute the emphasis regular expression."
  3823. (set var val)
  3824. (when (and (boundp 'org-emphasis-alist)
  3825. (boundp 'org-emphasis-regexp-components)
  3826. org-emphasis-alist org-emphasis-regexp-components)
  3827. (let* ((e org-emphasis-regexp-components)
  3828. (pre (car e))
  3829. (post (nth 1 e))
  3830. (border (nth 2 e))
  3831. (body (nth 3 e))
  3832. (nl (nth 4 e))
  3833. (body1 (concat body "*?"))
  3834. (markers (mapconcat 'car org-emphasis-alist ""))
  3835. (vmarkers (mapconcat
  3836. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3837. org-emphasis-alist "")))
  3838. ;; make sure special characters appear at the right position in the class
  3839. (if (string-match "\\^" markers)
  3840. (setq markers (concat (replace-match "" t t markers) "^")))
  3841. (if (string-match "-" markers)
  3842. (setq markers (concat (replace-match "" t t markers) "-")))
  3843. (if (string-match "\\^" vmarkers)
  3844. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3845. (if (string-match "-" vmarkers)
  3846. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3847. (if (> nl 0)
  3848. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3849. (int-to-string nl) "\\}")))
  3850. ;; Make the regexp
  3851. (setq org-emph-re
  3852. (concat "\\([" pre "]\\|^\\)"
  3853. "\\("
  3854. "\\([" markers "]\\)"
  3855. "\\("
  3856. "[^" border "]\\|"
  3857. "[^" border "]"
  3858. body1
  3859. "[^" border "]"
  3860. "\\)"
  3861. "\\3\\)"
  3862. "\\([" post "]\\|$\\)"))
  3863. (setq org-verbatim-re
  3864. (concat "\\([" pre "]\\|^\\)"
  3865. "\\("
  3866. "\\([" vmarkers "]\\)"
  3867. "\\("
  3868. "[^" border "]\\|"
  3869. "[^" border "]"
  3870. body1
  3871. "[^" border "]"
  3872. "\\)"
  3873. "\\3\\)"
  3874. "\\([" post "]\\|$\\)")))))
  3875. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3876. ;; set this option proved cumbersome. See this message/thread:
  3877. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3878. (defvar org-emphasis-regexp-components
  3879. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3880. "Components used to build the regular expression for emphasis.
  3881. This is a list with five entries. Terminology: In an emphasis string
  3882. like \" *strong word* \", we call the initial space PREMATCH, the final
  3883. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3884. and \"trong wor\" is the body. The different components in this variable
  3885. specify what is allowed/forbidden in each part:
  3886. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3887. post Chars allowed as postmatch. End of line will be allowed too.
  3888. border The chars *forbidden* as border characters.
  3889. body-regexp A regexp like \".\" to match a body character. Don't use
  3890. non-shy groups here, and don't allow newline here.
  3891. newline The maximum number of newlines allowed in an emphasis exp.
  3892. You need to reload Org or to restart Emacs after customizing this.")
  3893. (defcustom org-emphasis-alist
  3894. '(("*" bold)
  3895. ("/" italic)
  3896. ("_" underline)
  3897. ("=" org-verbatim verbatim)
  3898. ("~" org-code verbatim)
  3899. ("+" (:strike-through t)))
  3900. "Alist of characters and faces to emphasize text.
  3901. Text starting and ending with a special character will be emphasized,
  3902. for example *bold*, _underlined_ and /italic/. This variable sets the
  3903. marker characters and the face to be used by font-lock for highlighting
  3904. in Org-mode Emacs buffers.
  3905. You need to reload Org or to restart Emacs after customizing this."
  3906. :group 'org-appearance
  3907. :set 'org-set-emph-re
  3908. :version "24.4"
  3909. :package-version '(Org . "8.0")
  3910. :type '(repeat
  3911. (list
  3912. (string :tag "Marker character")
  3913. (choice
  3914. (face :tag "Font-lock-face")
  3915. (plist :tag "Face property list"))
  3916. (option (const verbatim)))))
  3917. (defvar org-protecting-blocks '("src" "example" "export")
  3918. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3919. This is needed for font-lock setup.")
  3920. ;;; Functions and variables from their packages
  3921. ;; Declared here to avoid compiler warnings
  3922. (defvar mark-active)
  3923. ;; Various packages
  3924. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3925. (declare-function calendar-forward-day "cal-move" (arg))
  3926. (declare-function calendar-goto-date "cal-move" (date))
  3927. (declare-function calendar-goto-today "cal-move" ())
  3928. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3929. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3930. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3931. (declare-function cdlatex-tab "ext:cdlatex" ())
  3932. (declare-function dired-get-filename
  3933. "dired"
  3934. (&optional localp no-error-if-not-filep))
  3935. (declare-function iswitchb-read-buffer
  3936. "iswitchb"
  3937. (prompt &optional
  3938. default require-match _predicate start matches-set))
  3939. (declare-function org-agenda-change-all-lines
  3940. "org-agenda"
  3941. (newhead hdmarker &optional fixface just-this))
  3942. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3943. "org-agenda"
  3944. (&optional end))
  3945. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3946. (declare-function org-agenda-format-item
  3947. "org-agenda"
  3948. (extra txt &optional level category tags dotime
  3949. remove-re habitp))
  3950. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3951. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3952. (declare-function org-agenda-save-markers-for-cut-and-paste
  3953. "org-agenda"
  3954. (beg end))
  3955. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3956. (declare-function org-agenda-skip "org-agenda" ())
  3957. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3958. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3959. (declare-function org-indent-mode "org-indent" (&optional arg))
  3960. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3961. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3962. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3963. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3964. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3965. (declare-function parse-time-string "parse-time" (string))
  3966. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3967. (declare-function table--at-cell-p
  3968. "table"
  3969. (position &optional object at-column))
  3970. (defvar align-mode-rules-list)
  3971. (defvar calc-embedded-close-formula)
  3972. (defvar calc-embedded-open-formula)
  3973. (defvar calc-embedded-open-mode)
  3974. (defvar font-lock-unfontify-region-function)
  3975. (defvar iswitchb-temp-buflist)
  3976. (defvar org-agenda-tags-todo-honor-ignore-options)
  3977. (defvar remember-data-file)
  3978. (defvar texmathp-why)
  3979. ;;;###autoload
  3980. (defun turn-on-orgtbl ()
  3981. "Unconditionally turn on `orgtbl-mode'."
  3982. (require 'org-table)
  3983. (orgtbl-mode 1))
  3984. (defun org-at-table-p (&optional table-type)
  3985. "Non-nil if the cursor is inside an Org table.
  3986. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3987. If `org-enable-table-editor' is nil, return nil unconditionally."
  3988. (and
  3989. org-enable-table-editor
  3990. (save-excursion
  3991. (beginning-of-line)
  3992. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3993. (or (not (derived-mode-p 'org-mode))
  3994. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3995. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3996. (defun org-at-table.el-p ()
  3997. "Non-nil when point is at a table.el table."
  3998. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3999. (let ((element (org-element-at-point)))
  4000. (and (eq (org-element-type element) 'table)
  4001. (eq (org-element-property :type element) 'table.el)))))
  4002. (defun org-table-recognize-table.el ()
  4003. "If there is a table.el table nearby, recognize it and move into it."
  4004. (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
  4005. (beginning-of-line)
  4006. (unless (or (looking-at org-table-dataline-regexp)
  4007. (not (looking-at org-table1-hline-regexp)))
  4008. (forward-line)
  4009. (when (looking-at org-table-any-border-regexp)
  4010. (forward-line -2)))
  4011. (if (re-search-forward "|" (org-table-end t) t)
  4012. (progn
  4013. (require 'table)
  4014. (if (table--at-cell-p (point)) t
  4015. (message "recognizing table.el table...")
  4016. (table-recognize-table)
  4017. (message "recognizing table.el table...done")))
  4018. (error "This should not happen"))))
  4019. ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
  4020. (make-obsolete 'org-table-recognize-table.el
  4021. "please notify the org mailing list if you use this function."
  4022. "Org 9.0")
  4023. (defun org-at-table-hline-p ()
  4024. "Non-nil when point is inside a hline in a table.
  4025. Assume point is already in a table. If `org-enable-table-editor'
  4026. is nil, return nil unconditionally."
  4027. (and org-enable-table-editor
  4028. (save-excursion
  4029. (beginning-of-line)
  4030. (looking-at org-table-hline-regexp))))
  4031. (defun org-table-map-tables (function &optional quietly)
  4032. "Apply FUNCTION to the start of all tables in the buffer."
  4033. (save-excursion
  4034. (save-restriction
  4035. (widen)
  4036. (goto-char (point-min))
  4037. (while (re-search-forward org-table-any-line-regexp nil t)
  4038. (unless quietly
  4039. (message "Mapping tables: %d%%"
  4040. (floor (* 100.0 (point)) (buffer-size))))
  4041. (beginning-of-line 1)
  4042. (when (and (looking-at org-table-line-regexp)
  4043. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4044. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4045. (save-excursion (funcall function))
  4046. (or (looking-at org-table-line-regexp)
  4047. (forward-char 1)))
  4048. (re-search-forward org-table-any-border-regexp nil 1))))
  4049. (unless quietly (message "Mapping tables: done")))
  4050. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4051. (declare-function org-clock-update-mode-line "org-clock" ())
  4052. (declare-function org-resolve-clocks "org-clock"
  4053. (&optional also-non-dangling-p prompt last-valid))
  4054. (defun org-at-TBLFM-p (&optional pos)
  4055. "Non-nil when point (or POS) is in #+TBLFM line."
  4056. (save-excursion
  4057. (goto-char (or pos (point)))
  4058. (beginning-of-line)
  4059. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4060. (eq (org-element-type (org-element-at-point)) 'table))))
  4061. (defvar org-clock-start-time)
  4062. (defvar org-clock-marker (make-marker)
  4063. "Marker recording the last clock-in.")
  4064. (defvar org-clock-hd-marker (make-marker)
  4065. "Marker recording the last clock-in, but the headline position.")
  4066. (defvar org-clock-heading ""
  4067. "The heading of the current clock entry.")
  4068. (defun org-clock-is-active ()
  4069. "Return the buffer where the clock is currently running.
  4070. Return nil if no clock is running."
  4071. (marker-buffer org-clock-marker))
  4072. (defun org-check-running-clock ()
  4073. "Check if the current buffer contains the running clock.
  4074. If yes, offer to stop it and to save the buffer with the changes."
  4075. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4076. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4077. (buffer-name))))
  4078. (org-clock-out)
  4079. (when (y-or-n-p "Save changed buffer?")
  4080. (save-buffer))))
  4081. (defun org-clocktable-try-shift (dir n)
  4082. "Check if this line starts a clock table, if yes, shift the time block."
  4083. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4084. (org-clocktable-shift dir n)))
  4085. ;;;###autoload
  4086. (defun org-clock-persistence-insinuate ()
  4087. "Set up hooks for clock persistence."
  4088. (require 'org-clock)
  4089. (add-hook 'org-mode-hook 'org-clock-load)
  4090. (add-hook 'kill-emacs-hook 'org-clock-save))
  4091. (defgroup org-archive nil
  4092. "Options concerning archiving in Org-mode."
  4093. :tag "Org Archive"
  4094. :group 'org-structure)
  4095. (defcustom org-archive-location "%s_archive::"
  4096. "The location where subtrees should be archived.
  4097. The value of this variable is a string, consisting of two parts,
  4098. separated by a double-colon. The first part is a filename and
  4099. the second part is a headline.
  4100. When the filename is omitted, archiving happens in the same file.
  4101. %s in the filename will be replaced by the current file
  4102. name (without the directory part). Archiving to a different file
  4103. is useful to keep archived entries from contributing to the
  4104. Org-mode Agenda.
  4105. The archived entries will be filed as subtrees of the specified
  4106. headline. When the headline is omitted, the subtrees are simply
  4107. filed away at the end of the file, as top-level entries. Also in
  4108. the heading you can use %s to represent the file name, this can be
  4109. useful when using the same archive for a number of different files.
  4110. Here are a few examples:
  4111. \"%s_archive::\"
  4112. If the current file is Projects.org, archive in file
  4113. Projects.org_archive, as top-level trees. This is the default.
  4114. \"::* Archived Tasks\"
  4115. Archive in the current file, under the top-level headline
  4116. \"* Archived Tasks\".
  4117. \"~/org/archive.org::\"
  4118. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4119. \"~/org/archive.org::* From %s\"
  4120. Archive in file ~/org/archive.org (absolute path), under headlines
  4121. \"From FILENAME\" where file name is the current file name.
  4122. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4123. The \"datetree/\" string is special, signifying to archive
  4124. items to the datetree. Items are placed in either the CLOSED
  4125. date of the item, or the current date if there is no CLOSED date.
  4126. The heading will be a subentry to the current date. There doesn't
  4127. need to be a heading, but there always needs to be a slash after
  4128. datetree. For example, to store archived items directly in the
  4129. datetree, use \"~/org/datetree.org::datetree/\".
  4130. \"basement::** Finished Tasks\"
  4131. Archive in file ./basement (relative path), as level 3 trees
  4132. below the level 2 heading \"** Finished Tasks\".
  4133. You may set this option on a per-file basis by adding to the buffer a
  4134. line like
  4135. #+ARCHIVE: basement::** Finished Tasks
  4136. You may also define it locally for a subtree by setting an ARCHIVE property
  4137. in the entry. If such a property is found in an entry, or anywhere up
  4138. the hierarchy, it will be used."
  4139. :group 'org-archive
  4140. :type 'string)
  4141. (defcustom org-agenda-skip-archived-trees t
  4142. "Non-nil means the agenda will skip any items located in archived trees.
  4143. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4144. variable is no longer recommended, you should leave it at the value t.
  4145. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4146. :group 'org-archive
  4147. :group 'org-agenda-skip
  4148. :type 'boolean)
  4149. (defcustom org-columns-skip-archived-trees t
  4150. "Non-nil means ignore archived trees when creating column view."
  4151. :group 'org-archive
  4152. :group 'org-properties
  4153. :type 'boolean)
  4154. (defcustom org-cycle-open-archived-trees nil
  4155. "Non-nil means `org-cycle' will open archived trees.
  4156. An archived tree is a tree marked with the tag ARCHIVE.
  4157. When nil, archived trees will stay folded. You can still open them with
  4158. normal outline commands like `show-all', but not with the cycling commands."
  4159. :group 'org-archive
  4160. :group 'org-cycle
  4161. :type 'boolean)
  4162. (defcustom org-sparse-tree-open-archived-trees nil
  4163. "Non-nil means sparse tree construction shows matches in archived trees.
  4164. When nil, matches in these trees are highlighted, but the trees are kept in
  4165. collapsed state."
  4166. :group 'org-archive
  4167. :group 'org-sparse-trees
  4168. :type 'boolean)
  4169. (defcustom org-sparse-tree-default-date-type nil
  4170. "The default date type when building a sparse tree.
  4171. When this is nil, a date is a scheduled or a deadline timestamp.
  4172. Otherwise, these types are allowed:
  4173. all: all timestamps
  4174. active: only active timestamps (<...>)
  4175. inactive: only inactive timestamps ([...])
  4176. scheduled: only scheduled timestamps
  4177. deadline: only deadline timestamps"
  4178. :type '(choice (const :tag "Scheduled or deadline" nil)
  4179. (const :tag "All timestamps" all)
  4180. (const :tag "Only active timestamps" active)
  4181. (const :tag "Only inactive timestamps" inactive)
  4182. (const :tag "Only scheduled timestamps" scheduled)
  4183. (const :tag "Only deadline timestamps" deadline)
  4184. (const :tag "Only closed timestamps" closed))
  4185. :version "25.1"
  4186. :package-version '(Org . "8.3")
  4187. :group 'org-sparse-trees)
  4188. (defun org-cycle-hide-archived-subtrees (state)
  4189. "Re-hide all archived subtrees after a visibility state change."
  4190. (when (and (not org-cycle-open-archived-trees)
  4191. (not (memq state '(overview folded))))
  4192. (save-excursion
  4193. (let* ((globalp (memq state '(contents all)))
  4194. (beg (if globalp (point-min) (point)))
  4195. (end (if globalp (point-max) (org-end-of-subtree t))))
  4196. (org-hide-archived-subtrees beg end)
  4197. (goto-char beg)
  4198. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4199. (message "%s" (substitute-command-keys
  4200. "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
  4201. (defun org-force-cycle-archived ()
  4202. "Cycle subtree even if it is archived."
  4203. (interactive)
  4204. (setq this-command 'org-cycle)
  4205. (let ((org-cycle-open-archived-trees t))
  4206. (call-interactively 'org-cycle)))
  4207. (defun org-hide-archived-subtrees (beg end)
  4208. "Re-hide all archived subtrees after a visibility state change."
  4209. (org-with-wide-buffer
  4210. (let ((case-fold-search nil)
  4211. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4212. (goto-char beg)
  4213. ;; Include headline point is currently on.
  4214. (beginning-of-line)
  4215. (while (and (< (point) end) (re-search-forward re end t))
  4216. (when (member org-archive-tag (org-get-tags))
  4217. (org-flag-subtree t)
  4218. (org-end-of-subtree t))))))
  4219. (declare-function outline-end-of-heading "outline" ())
  4220. (declare-function outline-flag-region "outline" (from to flag))
  4221. (defun org-flag-subtree (flag)
  4222. (save-excursion
  4223. (org-back-to-heading t)
  4224. (outline-end-of-heading)
  4225. (outline-flag-region (point)
  4226. (progn (org-end-of-subtree t) (point))
  4227. flag)))
  4228. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4229. ;; Declare Column View Code
  4230. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4231. (declare-function org-columns-compute "org-colview" (property))
  4232. ;; Declare ID code
  4233. (declare-function org-id-store-link "org-id")
  4234. (declare-function org-id-locations-load "org-id")
  4235. (declare-function org-id-locations-save "org-id")
  4236. (defvar org-id-track-globally)
  4237. ;;; Variables for pre-computed regular expressions, all buffer local
  4238. (defvar-local org-todo-regexp nil
  4239. "Matches any of the TODO state keywords.")
  4240. (defvar-local org-not-done-regexp nil
  4241. "Matches any of the TODO state keywords except the last one.")
  4242. (defvar-local org-not-done-heading-regexp nil
  4243. "Matches a TODO headline that is not done.")
  4244. (defvar-local org-todo-line-regexp nil
  4245. "Matches a headline and puts TODO state into group 2 if present.")
  4246. (defvar-local org-complex-heading-regexp nil
  4247. "Matches a headline and puts everything into groups:
  4248. group 1: the stars
  4249. group 2: The todo keyword, maybe
  4250. group 3: Priority cookie
  4251. group 4: True headline
  4252. group 5: Tags")
  4253. (defvar-local org-complex-heading-regexp-format nil
  4254. "Printf format to make regexp to match an exact headline.
  4255. This regexp will match the headline of any node which has the
  4256. exact headline text that is put into the format, but may have any
  4257. TODO state, priority and tags.")
  4258. (defvar-local org-todo-line-tags-regexp nil
  4259. "Matches a headline and puts TODO state into group 2 if present.
  4260. Also put tags into group 4 if tags are present.")
  4261. (defconst org-plain-time-of-day-regexp
  4262. (concat
  4263. "\\(\\<[012]?[0-9]"
  4264. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4265. "\\(--?"
  4266. "\\(\\<[012]?[0-9]"
  4267. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4268. "\\)?")
  4269. "Regular expression to match a plain time or time range.
  4270. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4271. groups carry important information:
  4272. 0 the full match
  4273. 1 the first time, range or not
  4274. 8 the second time, if it is a range.")
  4275. (defconst org-plain-time-extension-regexp
  4276. (concat
  4277. "\\(\\<[012]?[0-9]"
  4278. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4279. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4280. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4281. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4282. groups carry important information:
  4283. 0 the full match
  4284. 7 hours of duration
  4285. 9 minutes of duration")
  4286. (defconst org-stamp-time-of-day-regexp
  4287. (concat
  4288. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4289. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4290. "\\(--?"
  4291. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4292. "Regular expression to match a timestamp time or time range.
  4293. After a match, the following groups carry important information:
  4294. 0 the full match
  4295. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4296. 2 the first time, range or not
  4297. 4 the second time, if it is a range.")
  4298. (defconst org-startup-options
  4299. '(("fold" org-startup-folded t)
  4300. ("overview" org-startup-folded t)
  4301. ("nofold" org-startup-folded nil)
  4302. ("showall" org-startup-folded nil)
  4303. ("showeverything" org-startup-folded showeverything)
  4304. ("content" org-startup-folded content)
  4305. ("indent" org-startup-indented t)
  4306. ("noindent" org-startup-indented nil)
  4307. ("hidestars" org-hide-leading-stars t)
  4308. ("showstars" org-hide-leading-stars nil)
  4309. ("odd" org-odd-levels-only t)
  4310. ("oddeven" org-odd-levels-only nil)
  4311. ("align" org-startup-align-all-tables t)
  4312. ("noalign" org-startup-align-all-tables nil)
  4313. ("inlineimages" org-startup-with-inline-images t)
  4314. ("noinlineimages" org-startup-with-inline-images nil)
  4315. ("latexpreview" org-startup-with-latex-preview t)
  4316. ("nolatexpreview" org-startup-with-latex-preview nil)
  4317. ("customtime" org-display-custom-times t)
  4318. ("logdone" org-log-done time)
  4319. ("lognotedone" org-log-done note)
  4320. ("nologdone" org-log-done nil)
  4321. ("lognoteclock-out" org-log-note-clock-out t)
  4322. ("nolognoteclock-out" org-log-note-clock-out nil)
  4323. ("logrepeat" org-log-repeat state)
  4324. ("lognoterepeat" org-log-repeat note)
  4325. ("logdrawer" org-log-into-drawer t)
  4326. ("nologdrawer" org-log-into-drawer nil)
  4327. ("logstatesreversed" org-log-states-order-reversed t)
  4328. ("nologstatesreversed" org-log-states-order-reversed nil)
  4329. ("nologrepeat" org-log-repeat nil)
  4330. ("logreschedule" org-log-reschedule time)
  4331. ("lognotereschedule" org-log-reschedule note)
  4332. ("nologreschedule" org-log-reschedule nil)
  4333. ("logredeadline" org-log-redeadline time)
  4334. ("lognoteredeadline" org-log-redeadline note)
  4335. ("nologredeadline" org-log-redeadline nil)
  4336. ("logrefile" org-log-refile time)
  4337. ("lognoterefile" org-log-refile note)
  4338. ("nologrefile" org-log-refile nil)
  4339. ("fninline" org-footnote-define-inline t)
  4340. ("nofninline" org-footnote-define-inline nil)
  4341. ("fnlocal" org-footnote-section nil)
  4342. ("fnauto" org-footnote-auto-label t)
  4343. ("fnprompt" org-footnote-auto-label nil)
  4344. ("fnconfirm" org-footnote-auto-label confirm)
  4345. ("fnplain" org-footnote-auto-label plain)
  4346. ("fnadjust" org-footnote-auto-adjust t)
  4347. ("nofnadjust" org-footnote-auto-adjust nil)
  4348. ("constcgs" constants-unit-system cgs)
  4349. ("constSI" constants-unit-system SI)
  4350. ("noptag" org-tag-persistent-alist nil)
  4351. ("hideblocks" org-hide-block-startup t)
  4352. ("nohideblocks" org-hide-block-startup nil)
  4353. ("beamer" org-startup-with-beamer-mode t)
  4354. ("entitiespretty" org-pretty-entities t)
  4355. ("entitiesplain" org-pretty-entities nil))
  4356. "Variable associated with STARTUP options for org-mode.
  4357. Each element is a list of three items: the startup options (as written
  4358. in the #+STARTUP line), the corresponding variable, and the value to set
  4359. this variable to if the option is found. An optional forth element PUSH
  4360. means to push this value onto the list in the variable.")
  4361. (defcustom org-group-tags t
  4362. "When non-nil (the default), use group tags.
  4363. This can be turned on/off through `org-toggle-tags-groups'."
  4364. :group 'org-tags
  4365. :group 'org-startup
  4366. :type 'boolean)
  4367. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4368. (defun org-toggle-tags-groups ()
  4369. "Toggle support for group tags.
  4370. Support for group tags is controlled by the option
  4371. `org-group-tags', which is non-nil by default."
  4372. (interactive)
  4373. (setq org-group-tags (not org-group-tags))
  4374. (cond ((and (derived-mode-p 'org-agenda-mode)
  4375. org-group-tags)
  4376. (org-agenda-redo))
  4377. ((derived-mode-p 'org-mode)
  4378. (let ((org-inhibit-startup t)) (org-mode))))
  4379. (message "Groups tags support has been turned %s"
  4380. (if org-group-tags "on" "off")))
  4381. (defun org-set-regexps-and-options (&optional tags-only)
  4382. "Precompute regular expressions used in the current buffer.
  4383. When optional argument TAGS-ONLY is non-nil, only compute tags
  4384. related expressions."
  4385. (when (derived-mode-p 'org-mode)
  4386. (let ((alist (org--setup-collect-keywords
  4387. (org-make-options-regexp
  4388. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4389. (and (not tags-only)
  4390. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4391. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4392. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4393. ;; Startup options. Get this early since it does change
  4394. ;; behavior for other options (e.g., tags).
  4395. (let ((startup (cdr (assq 'startup alist))))
  4396. (dolist (option startup)
  4397. (let ((entry (assoc-string option org-startup-options t)))
  4398. (when entry
  4399. (let ((var (nth 1 entry))
  4400. (val (nth 2 entry)))
  4401. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4402. (unless (listp (symbol-value var))
  4403. (set (make-local-variable var) nil))
  4404. (add-to-list var val)))))))
  4405. (setq-local org-file-tags
  4406. (mapcar #'org-add-prop-inherited
  4407. (cdr (assq 'filetags alist))))
  4408. (setq org-current-tag-alist
  4409. (append org-tag-persistent-alist
  4410. (let ((tags (cdr (assq 'tags alist))))
  4411. (if tags (org-tag-string-to-alist tags)
  4412. org-tag-alist))))
  4413. (setq org-tag-groups-alist
  4414. (org-tag-alist-to-groups org-current-tag-alist))
  4415. (unless tags-only
  4416. ;; File properties.
  4417. (setq-local org-file-properties (cdr (assq 'property alist)))
  4418. ;; Archive location.
  4419. (let ((archive (cdr (assq 'archive alist))))
  4420. (when archive (setq-local org-archive-location archive)))
  4421. ;; Category.
  4422. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4423. (when cat
  4424. (setq-local org-category (intern cat))
  4425. (setq-local org-file-properties
  4426. (org--update-property-plist
  4427. "CATEGORY" cat org-file-properties))))
  4428. ;; Columns.
  4429. (let ((column (cdr (assq 'columns alist))))
  4430. (when column (setq-local org-columns-default-format column)))
  4431. ;; Constants.
  4432. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4433. ;; Link abbreviations.
  4434. (let ((links (cdr (assq 'link alist))))
  4435. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4436. ;; Priorities.
  4437. (let ((priorities (cdr (assq 'priorities alist))))
  4438. (when priorities
  4439. (setq-local org-highest-priority (nth 0 priorities))
  4440. (setq-local org-lowest-priority (nth 1 priorities))
  4441. (setq-local org-default-priority (nth 2 priorities))))
  4442. ;; Scripts.
  4443. (let ((scripts (assq 'scripts alist)))
  4444. (when scripts
  4445. (setq-local org-use-sub-superscripts (cdr scripts))))
  4446. ;; TODO keywords.
  4447. (setq-local org-todo-kwd-alist nil)
  4448. (setq-local org-todo-key-alist nil)
  4449. (setq-local org-todo-key-trigger nil)
  4450. (setq-local org-todo-keywords-1 nil)
  4451. (setq-local org-done-keywords nil)
  4452. (setq-local org-todo-heads nil)
  4453. (setq-local org-todo-sets nil)
  4454. (setq-local org-todo-log-states nil)
  4455. (let ((todo-sequences
  4456. (or (nreverse (cdr (assq 'todo alist)))
  4457. (let ((d (default-value 'org-todo-keywords)))
  4458. (if (not (stringp (car d))) d
  4459. ;; XXX: Backward compatibility code.
  4460. (list (cons org-todo-interpretation d)))))))
  4461. (dolist (sequence todo-sequences)
  4462. (let* ((sequence (or (run-hook-with-args-until-success
  4463. 'org-todo-setup-filter-hook sequence)
  4464. sequence))
  4465. (sequence-type (car sequence))
  4466. (keywords (cdr sequence))
  4467. (sep (member "|" keywords))
  4468. names alist)
  4469. (dolist (k (remove "|" keywords))
  4470. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4471. k)
  4472. (error "Invalid TODO keyword %s" k))
  4473. (let ((name (match-string 1 k))
  4474. (key (match-string 2 k))
  4475. (log (org-extract-log-state-settings k)))
  4476. (push name names)
  4477. (push (cons name (and key (string-to-char key))) alist)
  4478. (when log (push log org-todo-log-states))))
  4479. (let* ((names (nreverse names))
  4480. (done (if sep (org-remove-keyword-keys (cdr sep))
  4481. (last names)))
  4482. (head (car names))
  4483. (tail (list sequence-type head (car done) (org-last done))))
  4484. (add-to-list 'org-todo-heads head 'append)
  4485. (push names org-todo-sets)
  4486. (setq org-done-keywords (append org-done-keywords done nil))
  4487. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4488. (setq org-todo-key-alist
  4489. (append org-todo-key-alist
  4490. (and alist
  4491. (append '((:startgroup))
  4492. (nreverse alist)
  4493. '((:endgroup))))))
  4494. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4495. (setq org-todo-sets (nreverse org-todo-sets)
  4496. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4497. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4498. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4499. ;; Compute the regular expressions and other local variables.
  4500. ;; Using `org-outline-regexp-bol' would complicate them much,
  4501. ;; because of the fixed white space at the end of that string.
  4502. (unless org-done-keywords
  4503. (setq org-done-keywords
  4504. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4505. (setq org-not-done-keywords
  4506. (org-delete-all org-done-keywords
  4507. (copy-sequence org-todo-keywords-1))
  4508. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4509. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4510. org-not-done-heading-regexp
  4511. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4512. org-todo-line-regexp
  4513. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4514. org-complex-heading-regexp
  4515. (concat "^\\(\\*+\\)"
  4516. "\\(?: +" org-todo-regexp "\\)?"
  4517. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4518. "\\(?: +\\(.*?\\)\\)??"
  4519. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4520. "[ \t]*$")
  4521. org-complex-heading-regexp-format
  4522. (concat "^\\(\\*+\\)"
  4523. "\\(?: +" org-todo-regexp "\\)?"
  4524. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4525. "\\(?: +"
  4526. ;; Stats cookies can be stuck to body.
  4527. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4528. "\\(%s\\)"
  4529. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4530. "\\)"
  4531. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4532. "[ \t]*$")
  4533. org-todo-line-tags-regexp
  4534. (concat "^\\(\\*+\\)"
  4535. "\\(?: +" org-todo-regexp "\\)?"
  4536. "\\(?: +\\(.*?\\)\\)??"
  4537. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4538. "[ \t]*$"))
  4539. (org-compute-latex-and-related-regexp)))))
  4540. (defun org--setup-collect-keywords (regexp &optional files alist)
  4541. "Return setup keywords values as an alist.
  4542. REGEXP matches a subset of setup keywords. FILES is a list of
  4543. file names already visited. It is used to avoid circular setup
  4544. files. ALIST, when non-nil, is the alist computed so far.
  4545. Return value contains the following keys: `archive', `category',
  4546. `columns', `constants', `filetags', `link', `priorities',
  4547. `property', `scripts', `startup', `tags' and `todo'."
  4548. (org-with-wide-buffer
  4549. (goto-char (point-min))
  4550. (let ((case-fold-search t))
  4551. (while (re-search-forward regexp nil t)
  4552. (let ((element (org-element-at-point)))
  4553. (when (eq (org-element-type element) 'keyword)
  4554. (let ((key (org-element-property :key element))
  4555. (value (org-element-property :value element)))
  4556. (cond
  4557. ((equal key "ARCHIVE")
  4558. (when (org-string-nw-p value)
  4559. (push (cons 'archive value) alist)))
  4560. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4561. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4562. ((equal key "CONSTANTS")
  4563. (let* ((constants (assq 'constants alist))
  4564. (store (cdr constants)))
  4565. (dolist (pair (org-split-string value))
  4566. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4567. pair)
  4568. (let* ((name (match-string 1 pair))
  4569. (value (match-string 2 pair))
  4570. (old (assoc name store)))
  4571. (if old (setcdr old value)
  4572. (push (cons name value) store)))))
  4573. (if constants (setcdr constants store)
  4574. (push (cons 'constants store) alist))))
  4575. ((equal key "FILETAGS")
  4576. (when (org-string-nw-p value)
  4577. (let ((old (assq 'filetags alist))
  4578. (new (apply #'nconc
  4579. (mapcar (lambda (x) (org-split-string x ":"))
  4580. (org-split-string value)))))
  4581. (if old (setcdr old (append new (cdr old)))
  4582. (push (cons 'filetags new) alist)))))
  4583. ((equal key "LINK")
  4584. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4585. (let ((links (assq 'link alist))
  4586. (pair (cons (match-string-no-properties 1 value)
  4587. (match-string-no-properties 2 value))))
  4588. (if links (push pair (cdr links))
  4589. (push (list 'link pair) alist)))))
  4590. ((equal key "OPTIONS")
  4591. (when (and (org-string-nw-p value)
  4592. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4593. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4594. ((equal key "PRIORITIES")
  4595. (push (cons 'priorities
  4596. (let ((prio (org-split-string value)))
  4597. (if (< (length prio) 3) '(?A ?C ?B)
  4598. (mapcar #'string-to-char prio))))
  4599. alist))
  4600. ((equal key "PROPERTY")
  4601. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4602. (let* ((property (assq 'property alist))
  4603. (value (org--update-property-plist
  4604. (match-string-no-properties 1 value)
  4605. (match-string-no-properties 2 value)
  4606. (cdr property))))
  4607. (if property (setcdr property value)
  4608. (push (cons 'property value) alist)))))
  4609. ((equal key "STARTUP")
  4610. (let ((startup (assq 'startup alist)))
  4611. (if startup
  4612. (setcdr startup
  4613. (append (cdr startup) (org-split-string value)))
  4614. (push (cons 'startup (org-split-string value)) alist))))
  4615. ((equal key "TAGS")
  4616. (let ((tag-cell (assq 'tags alist)))
  4617. (if tag-cell
  4618. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4619. (push (cons 'tags value) alist))))
  4620. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4621. (let ((todo (assq 'todo alist))
  4622. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4623. (org-split-string value))))
  4624. (if todo (push value (cdr todo))
  4625. (push (list 'todo value) alist))))
  4626. ((equal key "SETUPFILE")
  4627. (unless buffer-read-only ; Do not check in Gnus messages.
  4628. (let ((f (and (org-string-nw-p value)
  4629. (expand-file-name
  4630. (org-remove-double-quotes value)))))
  4631. (when (and f (file-readable-p f) (not (member f files)))
  4632. (with-temp-buffer
  4633. (setq default-directory (file-name-directory f))
  4634. (insert-file-contents f)
  4635. (setq alist
  4636. ;; Fake Org mode to benefit from cache
  4637. ;; without recurring needlessly.
  4638. (let ((major-mode 'org-mode))
  4639. (org--setup-collect-keywords
  4640. regexp (cons f files) alist)))))))))))))))
  4641. alist)
  4642. (defun org-tag-string-to-alist (s)
  4643. "Return tag alist associated to string S.
  4644. S is a value for TAGS keyword or produced with
  4645. `org-tag-alist-to-string'. Return value is an alist suitable for
  4646. `org-tag-alist' or `org-tag-persistent-alist'."
  4647. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4648. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4649. "\\|{.+?}\\)" ; regular expression
  4650. "\\(?:(\\(.\\))\\)?\\'"))
  4651. alist group-flag)
  4652. (dolist (tokens lines (cdr (nreverse alist)))
  4653. (push '(:newline) alist)
  4654. (while tokens
  4655. (let ((token (pop tokens)))
  4656. (pcase token
  4657. ("{"
  4658. (push '(:startgroup) alist)
  4659. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4660. ("}"
  4661. (push '(:endgroup) alist)
  4662. (setq group-flag nil))
  4663. ("["
  4664. (push '(:startgrouptag) alist)
  4665. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4666. ("]"
  4667. (push '(:endgrouptag) alist)
  4668. (setq group-flag nil))
  4669. (":"
  4670. (push '(:grouptags) alist))
  4671. ((guard (string-match tag-re token))
  4672. (let ((tag (match-string 1 token))
  4673. (key (and (match-beginning 2)
  4674. (string-to-char (match-string 2 token)))))
  4675. ;; Push all tags in groups, no matter if they already
  4676. ;; appear somewhere else in the list.
  4677. (when (or group-flag (not (assoc tag alist)))
  4678. (push (cons tag key) alist))))))))))
  4679. (defun org-tag-alist-to-string (alist &optional skip-key)
  4680. "Return tag string associated to ALIST.
  4681. ALIST is an alist, as defined in `org-tag-alist' or
  4682. `org-tag-persistent-alist', or produced with
  4683. `org-tag-string-to-alist'.
  4684. Return value is a string suitable as a value for \"TAGS\"
  4685. keyword.
  4686. When optional argument SKIP-KEY is non-nil, skip selection keys
  4687. next to tags."
  4688. (mapconcat (lambda (token)
  4689. (pcase token
  4690. (`(:startgroup) "{")
  4691. (`(:endgroup) "}")
  4692. (`(:startgrouptag) "[")
  4693. (`(:endgrouptag) "]")
  4694. (`(:grouptags) ":")
  4695. (`(:newline) "\\n")
  4696. ((and
  4697. (guard (not skip-key))
  4698. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4699. (format "%s(%c)" tag key))
  4700. (`(,(and tag (pred stringp)) . ,_) tag)
  4701. (_ (user-error "Invalid tag token: %S" token))))
  4702. alist
  4703. " "))
  4704. (defun org-tag-alist-to-groups (alist)
  4705. "Return group alist from tag ALIST.
  4706. ALIST is an alist, as defined in `org-tag-alist' or
  4707. `org-tag-persistent-alist', or produced with
  4708. `org-tag-string-to-alist'. Return value is an alist following
  4709. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4710. a string, summarizing TAGS, as a list of strings."
  4711. (let (groups group-status current-group)
  4712. (dolist (token alist (nreverse groups))
  4713. (pcase token
  4714. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4715. (`(,(or :endgroup :endgrouptag))
  4716. (when (eq group-status 'append)
  4717. (push (nreverse current-group) groups))
  4718. (setq group-status nil))
  4719. (`(:grouptags) (setq group-status 'append))
  4720. ((and `(,tag . ,_) (guard group-status))
  4721. (if (eq group-status 'append) (push tag current-group)
  4722. (setq current-group (list tag))))
  4723. (_ nil)))))
  4724. (defun org-file-contents (file &optional noerror)
  4725. "Return the contents of FILE, as a string."
  4726. (if (and file (file-readable-p file))
  4727. (with-temp-buffer
  4728. (insert-file-contents file)
  4729. (buffer-string))
  4730. (funcall (if noerror 'message 'error)
  4731. "Cannot read file \"%s\"%s"
  4732. file
  4733. (let ((from (buffer-file-name (buffer-base-buffer))))
  4734. (if from (concat " (referenced in file \"" from "\")") "")))))
  4735. (defun org-extract-log-state-settings (x)
  4736. "Extract the log state setting from a TODO keyword string.
  4737. This will extract info from a string like \"WAIT(w@/!)\"."
  4738. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4739. (let ((kw (match-string 1 x))
  4740. (log1 (and (match-end 3) (match-string 3 x)))
  4741. (log2 (and (match-end 4) (match-string 4 x))))
  4742. (and (or log1 log2)
  4743. (list kw
  4744. (and log1 (if (equal log1 "!") 'time 'note))
  4745. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4746. (defun org-remove-keyword-keys (list)
  4747. "Remove a pair of parenthesis at the end of each string in LIST."
  4748. (mapcar (lambda (x)
  4749. (if (string-match "(.*)$" x)
  4750. (substring x 0 (match-beginning 0))
  4751. x))
  4752. list))
  4753. (defun org-assign-fast-keys (alist)
  4754. "Assign fast keys to a keyword-key alist.
  4755. Respect keys that are already there."
  4756. (let (new e (alt ?0))
  4757. (while (setq e (pop alist))
  4758. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4759. (cdr e)) ;; Key already assigned.
  4760. (push e new)
  4761. (let ((clist (string-to-list (downcase (car e))))
  4762. (used (append new alist)))
  4763. (when (= (car clist) ?@)
  4764. (pop clist))
  4765. (while (and clist (rassoc (car clist) used))
  4766. (pop clist))
  4767. (unless clist
  4768. (while (rassoc alt used)
  4769. (cl-incf alt)))
  4770. (push (cons (car e) (or (car clist) alt)) new))))
  4771. (nreverse new)))
  4772. ;;; Some variables used in various places
  4773. (defvar org-window-configuration nil
  4774. "Used in various places to store a window configuration.")
  4775. (defvar org-selected-window nil
  4776. "Used in various places to store a window configuration.")
  4777. (defvar org-finish-function nil
  4778. "Function to be called when `C-c C-c' is used.
  4779. This is for getting out of special buffers like capture.")
  4780. (defvar org-last-state)
  4781. ;; Defined somewhere in this file, but used before definition.
  4782. (defvar org-entities) ;; defined in org-entities.el
  4783. (defvar org-struct-menu)
  4784. (defvar org-org-menu)
  4785. (defvar org-tbl-menu)
  4786. ;;;; Define the Org-mode
  4787. ;; We use a before-change function to check if a table might need
  4788. ;; an update.
  4789. (defvar org-table-may-need-update t
  4790. "Indicates that a table might need an update.
  4791. This variable is set by `org-before-change-function'.
  4792. `org-table-align' sets it back to nil.")
  4793. (defun org-before-change-function (_beg _end)
  4794. "Every change indicates that a table might need an update."
  4795. (setq org-table-may-need-update t))
  4796. (defvar org-mode-map)
  4797. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4798. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4799. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4800. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4801. (defvar org-table-buffer-is-an nil)
  4802. (defvar bidi-paragraph-direction)
  4803. (defvar buffer-face-mode-face)
  4804. (require 'outline)
  4805. ;; Other stuff we need.
  4806. (require 'time-date)
  4807. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4808. (require 'easymenu)
  4809. (autoload 'easy-menu-add "easymenu")
  4810. (require 'overlay)
  4811. ;; (require 'org-macs) moved higher up in the file before it is first used
  4812. (require 'org-entities)
  4813. ;; (require 'org-compat) moved higher up in the file before it is first used
  4814. (require 'org-faces)
  4815. (require 'org-list)
  4816. (require 'org-pcomplete)
  4817. (require 'org-src)
  4818. (require 'org-footnote)
  4819. (require 'org-macro)
  4820. ;; babel
  4821. (require 'ob)
  4822. ;;;###autoload
  4823. (define-derived-mode org-mode outline-mode "Org"
  4824. "Outline-based notes management and organizer, alias
  4825. \"Carsten's outline-mode for keeping track of everything.\"
  4826. Org-mode develops organizational tasks around a NOTES file which
  4827. contains information about projects as plain text. Org-mode is
  4828. implemented on top of outline-mode, which is ideal to keep the content
  4829. of large files well structured. It supports ToDo items, deadlines and
  4830. time stamps, which magically appear in the diary listing of the Emacs
  4831. calendar. Tables are easily created with a built-in table editor.
  4832. Plain text URL-like links connect to websites, emails (VM), Usenet
  4833. messages (Gnus), BBDB entries, and any files related to the project.
  4834. For printing and sharing of notes, an Org-mode file (or a part of it)
  4835. can be exported as a structured ASCII or HTML file.
  4836. The following commands are available:
  4837. \\{org-mode-map}"
  4838. ;; Get rid of Outline menus, they are not needed
  4839. ;; Need to do this here because define-derived-mode sets up
  4840. ;; the keymap so late. Still, it is a waste to call this each time
  4841. ;; we switch another buffer into Org mode.
  4842. (define-key org-mode-map [menu-bar headings] 'undefined)
  4843. (define-key org-mode-map [menu-bar hide] 'undefined)
  4844. (define-key org-mode-map [menu-bar show] 'undefined)
  4845. (org-load-modules-maybe)
  4846. (org-install-agenda-files-menu)
  4847. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4848. (add-to-invisibility-spec '(org-cwidth))
  4849. (add-to-invisibility-spec '(org-hide-block . t))
  4850. (setq-local outline-regexp org-outline-regexp)
  4851. (setq-local outline-level 'org-outline-level)
  4852. (setq bidi-paragraph-direction 'left-to-right)
  4853. (when (and org-ellipsis
  4854. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4855. (fboundp 'make-glyph-code))
  4856. (unless org-display-table
  4857. (setq org-display-table (make-display-table)))
  4858. (set-display-table-slot
  4859. org-display-table 4
  4860. (vconcat (mapcar
  4861. (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
  4862. org-ellipsis)))
  4863. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4864. (setq buffer-display-table org-display-table))
  4865. (org-set-regexps-and-options)
  4866. (org-set-font-lock-defaults)
  4867. (when (and org-tag-faces (not org-tags-special-faces-re))
  4868. ;; tag faces set outside customize.... force initialization.
  4869. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4870. ;; Calc embedded
  4871. (setq-local calc-embedded-open-mode "# ")
  4872. ;; Modify a few syntax entries
  4873. (modify-syntax-entry ?@ "w")
  4874. (modify-syntax-entry ?\" "\"")
  4875. (modify-syntax-entry ?\\ "_")
  4876. (modify-syntax-entry ?~ "_")
  4877. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4878. ;; Activate before-change-function
  4879. (setq-local org-table-may-need-update t)
  4880. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4881. ;; Check for running clock before killing a buffer
  4882. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4883. ;; Initialize macros templates.
  4884. (org-macro-initialize-templates)
  4885. ;; Initialize radio targets.
  4886. (org-update-radio-target-regexp)
  4887. ;; Indentation.
  4888. (setq-local indent-line-function 'org-indent-line)
  4889. (setq-local indent-region-function 'org-indent-region)
  4890. ;; Filling and auto-filling.
  4891. (org-setup-filling)
  4892. ;; Comments.
  4893. (org-setup-comments-handling)
  4894. ;; Initialize cache.
  4895. (org-element-cache-reset)
  4896. ;; Beginning/end of defun
  4897. (setq-local beginning-of-defun-function 'org-backward-element)
  4898. (setq-local end-of-defun-function
  4899. (lambda ()
  4900. (if (not (org-at-heading-p))
  4901. (org-forward-element)
  4902. (org-forward-element)
  4903. (forward-char -1))))
  4904. ;; Next error for sparse trees
  4905. (setq-local next-error-function 'org-occur-next-match)
  4906. ;; Make sure dependence stuff works reliably, even for users who set it
  4907. ;; too late :-(
  4908. (if org-enforce-todo-dependencies
  4909. (add-hook 'org-blocker-hook
  4910. 'org-block-todo-from-children-or-siblings-or-parent)
  4911. (remove-hook 'org-blocker-hook
  4912. 'org-block-todo-from-children-or-siblings-or-parent))
  4913. (if org-enforce-todo-checkbox-dependencies
  4914. (add-hook 'org-blocker-hook
  4915. 'org-block-todo-from-checkboxes)
  4916. (remove-hook 'org-blocker-hook
  4917. 'org-block-todo-from-checkboxes))
  4918. ;; Align options lines
  4919. (setq-local
  4920. align-mode-rules-list
  4921. '((org-in-buffer-settings
  4922. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4923. (modes . '(org-mode)))))
  4924. ;; Imenu
  4925. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4926. ;; Make isearch reveal context
  4927. (setq-local outline-isearch-open-invisible-function
  4928. (lambda (&rest _) (org-show-context 'isearch)))
  4929. ;; Setup the pcomplete hooks
  4930. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4931. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4932. (setq-local pcomplete-default-completion-function 'ignore)
  4933. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4934. (setq-local pcomplete-termination-string "")
  4935. (setq-local buffer-face-mode-face 'org-default)
  4936. ;; If empty file that did not turn on Org mode automatically, make
  4937. ;; it to.
  4938. (when (and org-insert-mode-line-in-empty-file
  4939. (called-interactively-p 'any)
  4940. (= (point-min) (point-max)))
  4941. (insert "# -*- mode: org -*-\n\n"))
  4942. (unless org-inhibit-startup
  4943. (org-unmodified
  4944. (when org-startup-with-beamer-mode (org-beamer-mode))
  4945. (when org-startup-align-all-tables
  4946. (org-table-map-tables #'org-table-align t))
  4947. (when org-startup-with-inline-images (org-display-inline-images))
  4948. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4949. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4950. (when org-startup-truncated (setq truncate-lines t))
  4951. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4952. (org-refresh-effort-properties)))
  4953. ;; Try to set `org-hide' face correctly.
  4954. (let ((foreground (org-find-invisible-foreground)))
  4955. (when foreground
  4956. (set-face-foreground 'org-hide foreground))))
  4957. ;; Update `customize-package-emacs-version-alist'
  4958. (add-to-list 'customize-package-emacs-version-alist
  4959. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4960. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4961. ("8.2.6" . "24.4") ("8.3" . "25.1")))
  4962. (defvar org-mode-transpose-word-syntax-table
  4963. (let ((st (make-syntax-table text-mode-syntax-table)))
  4964. (dolist (c org-emphasis-alist st)
  4965. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4966. (when (fboundp 'abbrev-table-put)
  4967. (abbrev-table-put org-mode-abbrev-table
  4968. :parents (list text-mode-abbrev-table)))
  4969. (defun org-find-invisible-foreground ()
  4970. (let ((candidates (remove
  4971. "unspecified-bg"
  4972. (nconc
  4973. (list (face-background 'default)
  4974. (face-background 'org-default))
  4975. (mapcar
  4976. (lambda (alist)
  4977. (when (boundp alist)
  4978. (cdr (assoc 'background-color (symbol-value alist)))))
  4979. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4980. (list (face-foreground 'org-hide))))))
  4981. (car (remove nil candidates))))
  4982. (defun org-current-time (&optional rounding-minutes past)
  4983. "Current time, possibly rounded to ROUNDING-MINUTES.
  4984. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4985. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4986. the rounding returns a past time."
  4987. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4988. (car org-time-stamp-rounding-minutes)))
  4989. (time (decode-time)) res)
  4990. (if (< r 1)
  4991. (current-time)
  4992. (setq res
  4993. (apply 'encode-time
  4994. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4995. (nthcdr 2 time))))
  4996. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4997. (seconds-to-time (- (float-time res) (* r 60)))
  4998. res))))
  4999. (defun org-today ()
  5000. "Return today date, considering `org-extend-today-until'."
  5001. (time-to-days
  5002. (time-subtract (current-time)
  5003. (list 0 (* 3600 org-extend-today-until) 0))))
  5004. ;;;; Font-Lock stuff, including the activators
  5005. (defvar org-mouse-map (make-sparse-keymap))
  5006. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  5007. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  5008. (when org-mouse-1-follows-link
  5009. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5010. (when org-tab-follows-link
  5011. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5012. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5013. (require 'font-lock)
  5014. (defconst org-non-link-chars "]\t\n\r<>")
  5015. (defvar org-link-types-re nil
  5016. "Matches a link that has a url-like prefix like \"http:\"")
  5017. (defvar org-link-re-with-space nil
  5018. "Matches a link with spaces, optional angular brackets around it.")
  5019. (defvar org-link-re-with-space2 nil
  5020. "Matches a link with spaces, optional angular brackets around it.")
  5021. (defvar org-link-re-with-space3 nil
  5022. "Matches a link with spaces, only for internal part in bracket links.")
  5023. (defvar org-angle-link-re nil
  5024. "Matches link with angular brackets, spaces are allowed.")
  5025. (defvar org-plain-link-re nil
  5026. "Matches plain link, without spaces.")
  5027. (defvar org-bracket-link-regexp nil
  5028. "Matches a link in double brackets.")
  5029. (defvar org-bracket-link-analytic-regexp nil
  5030. "Regular expression used to analyze links.
  5031. Here is what the match groups contain after a match:
  5032. 1: http:
  5033. 2: http
  5034. 3: path
  5035. 4: [desc]
  5036. 5: desc")
  5037. (defvar org-bracket-link-analytic-regexp++ nil
  5038. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5039. (defvar org-any-link-re nil
  5040. "Regular expression matching any link.")
  5041. (defconst org-match-sexp-depth 3
  5042. "Number of stacked braces for sub/superscript matching.")
  5043. (defun org-create-multibrace-regexp (left right n)
  5044. "Create a regular expression which will match a balanced sexp.
  5045. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5046. as single character strings.
  5047. The regexp returned will match the entire expression including the
  5048. delimiters. It will also define a single group which contains the
  5049. match except for the outermost delimiters. The maximum depth of
  5050. stacked delimiters is N. Escaping delimiters is not possible."
  5051. (let* ((nothing (concat "[^" left right "]*?"))
  5052. (or "\\|")
  5053. (re nothing)
  5054. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5055. (while (> n 1)
  5056. (setq n (1- n)
  5057. re (concat re or next)
  5058. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5059. (concat left "\\(" re "\\)" right)))
  5060. (defconst org-match-substring-regexp
  5061. (concat
  5062. "\\(\\S-\\)\\([_^]\\)\\("
  5063. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5064. "\\|"
  5065. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5066. "\\|"
  5067. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5068. "The regular expression matching a sub- or superscript.")
  5069. (defconst org-match-substring-with-braces-regexp
  5070. (concat
  5071. "\\(\\S-\\)\\([_^]\\)"
  5072. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5073. "The regular expression matching a sub- or superscript, forcing braces.")
  5074. (defun org-make-link-regexps ()
  5075. "Update the link regular expressions.
  5076. This should be called after the variable `org-link-parameters' has changed."
  5077. (let ((types-re (regexp-opt (org-link-types) t)))
  5078. (setq org-link-types-re
  5079. (concat "\\`" types-re ":")
  5080. org-link-re-with-space
  5081. (concat "<?" types-re ":"
  5082. "\\([^" org-non-link-chars " ]"
  5083. "[^" org-non-link-chars "]*"
  5084. "[^" org-non-link-chars " ]\\)>?")
  5085. org-link-re-with-space2
  5086. (concat "<?" types-re ":"
  5087. "\\([^" org-non-link-chars " ]"
  5088. "[^\t\n\r]*"
  5089. "[^" org-non-link-chars " ]\\)>?")
  5090. org-link-re-with-space3
  5091. (concat "<?" types-re ":"
  5092. "\\([^" org-non-link-chars " ]"
  5093. "[^\t\n\r]*\\)")
  5094. org-angle-link-re
  5095. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5096. types-re)
  5097. org-plain-link-re
  5098. (concat
  5099. "\\<" types-re ":"
  5100. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5101. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5102. org-bracket-link-regexp
  5103. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5104. org-bracket-link-analytic-regexp
  5105. (concat
  5106. "\\[\\["
  5107. "\\(" types-re ":\\)?"
  5108. "\\([^]]+\\)"
  5109. "\\]"
  5110. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5111. "\\]")
  5112. org-bracket-link-analytic-regexp++
  5113. (concat
  5114. "\\[\\["
  5115. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5116. "\\([^]]+\\)"
  5117. "\\]"
  5118. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5119. "\\]")
  5120. org-any-link-re
  5121. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5122. org-angle-link-re "\\)\\|\\("
  5123. org-plain-link-re "\\)"))))
  5124. (org-make-link-regexps)
  5125. (defvar org-emph-face nil)
  5126. (defun org-do-emphasis-faces (limit)
  5127. "Run through the buffer and emphasize strings."
  5128. (let (rtn a)
  5129. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5130. (let* ((border (char-after (match-beginning 3)))
  5131. (bre (regexp-quote (char-to-string border))))
  5132. (when (and (not (= border (char-after (match-beginning 4))))
  5133. (not (string-match-p (concat bre ".*" bre)
  5134. (replace-regexp-in-string
  5135. "\n" " "
  5136. (substring (match-string 2) 1 -1)))))
  5137. (setq rtn t)
  5138. (setq a (assoc (match-string 3) org-emphasis-alist))
  5139. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5140. 'face
  5141. (nth 1 a))
  5142. (and (nth 2 a)
  5143. (org-remove-flyspell-overlays-in
  5144. (match-beginning 0) (match-end 0)))
  5145. (add-text-properties (match-beginning 2) (match-end 2)
  5146. '(font-lock-multiline t org-emphasis t))
  5147. (when org-hide-emphasis-markers
  5148. (add-text-properties (match-end 4) (match-beginning 5)
  5149. '(invisible org-link))
  5150. (add-text-properties (match-beginning 3) (match-end 3)
  5151. '(invisible org-link)))))
  5152. (goto-char (1+ (match-beginning 0))))
  5153. rtn))
  5154. (defun org-emphasize (&optional char)
  5155. "Insert or change an emphasis, i.e. a font like bold or italic.
  5156. If there is an active region, change that region to a new emphasis.
  5157. If there is no region, just insert the marker characters and position
  5158. the cursor between them.
  5159. CHAR should be the marker character. If it is a space, it means to
  5160. remove the emphasis of the selected region.
  5161. If CHAR is not given (for example in an interactive call) it will be
  5162. prompted for."
  5163. (interactive)
  5164. (let ((erc org-emphasis-regexp-components)
  5165. (string "") beg end move s)
  5166. (if (org-region-active-p)
  5167. (setq beg (region-beginning)
  5168. end (region-end)
  5169. string (buffer-substring beg end))
  5170. (setq move t))
  5171. (unless char
  5172. (message "Emphasis marker or tag: [%s]"
  5173. (mapconcat #'car org-emphasis-alist ""))
  5174. (setq char (read-char-exclusive)))
  5175. (if (equal char ?\s)
  5176. (setq s ""
  5177. move nil)
  5178. (unless (assoc (char-to-string char) org-emphasis-alist)
  5179. (user-error "No such emphasis marker: \"%c\"" char))
  5180. (setq s (char-to-string char)))
  5181. (while (and (> (length string) 1)
  5182. (equal (substring string 0 1) (substring string -1))
  5183. (assoc (substring string 0 1) org-emphasis-alist))
  5184. (setq string (substring string 1 -1)))
  5185. (setq string (concat s string s))
  5186. (when beg (delete-region beg end))
  5187. (unless (or (bolp)
  5188. (string-match (concat "[" (nth 0 erc) "\n]")
  5189. (char-to-string (char-before (point)))))
  5190. (insert " "))
  5191. (unless (or (eobp)
  5192. (string-match (concat "[" (nth 1 erc) "\n]")
  5193. (char-to-string (char-after (point)))))
  5194. (insert " ") (backward-char 1))
  5195. (insert string)
  5196. (and move (backward-char 1))))
  5197. (defconst org-nonsticky-props
  5198. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5199. (defsubst org-rear-nonsticky-at (pos)
  5200. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5201. (defun org-activate-plain-links (limit)
  5202. "Add link properties for plain links."
  5203. (when (and (re-search-forward org-plain-link-re limit t)
  5204. (not (org-in-src-block-p)))
  5205. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5206. 'face))
  5207. (link (match-string-no-properties 0))
  5208. (type (match-string-no-properties 1))
  5209. (path (match-string-no-properties 2))
  5210. (link-start (match-beginning 0))
  5211. (link-end (match-end 0))
  5212. (link-face (org-link-get-parameter type :face))
  5213. (help-echo (org-link-get-parameter type :help-echo))
  5214. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5215. (activate-func (org-link-get-parameter type :activate-func)))
  5216. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5217. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5218. (add-text-properties (match-beginning 0) (match-end 0)
  5219. (list
  5220. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5221. 'highlight)
  5222. 'face (cond
  5223. ;; A function that returns a face
  5224. ((functionp link-face)
  5225. (funcall link-face path))
  5226. ;; a face
  5227. ((facep link-face)
  5228. link-face)
  5229. ;; An anonymous face
  5230. ((consp link-face)
  5231. link-face)
  5232. ;; default
  5233. (t
  5234. 'org-link))
  5235. 'help-echo (cond
  5236. ((stringp help-echo)
  5237. help-echo)
  5238. ((functionp help-echo)
  5239. help-echo)
  5240. (t
  5241. (concat "LINK: "
  5242. (save-match-data
  5243. (org-link-unescape link)))))
  5244. 'htmlize-link (cond
  5245. ((functionp htmlize-link)
  5246. (funcall htmlize-link path))
  5247. (t
  5248. `(:uri ,link)))
  5249. 'keymap (or (org-link-get-parameter type :keymap)
  5250. org-mouse-map)
  5251. 'org-link-start (match-beginning 0)))
  5252. (org-rear-nonsticky-at (match-end 0))
  5253. (when activate-func
  5254. (funcall activate-func link-start link-end path nil))
  5255. t))))
  5256. (defun org-activate-code (limit)
  5257. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5258. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5259. (remove-text-properties (match-beginning 0) (match-end 0)
  5260. '(display t invisible t intangible t))
  5261. t))
  5262. (defcustom org-src-fontify-natively t
  5263. "When non-nil, fontify code in code blocks.
  5264. See also the `org-block' face."
  5265. :type 'boolean
  5266. :version "24.4"
  5267. :package-version '(Org . "8.3")
  5268. :group 'org-appearance
  5269. :group 'org-babel)
  5270. (defcustom org-allow-promoting-top-level-subtree nil
  5271. "When non-nil, allow promoting a top level subtree.
  5272. The leading star of the top level headline will be replaced
  5273. by a #."
  5274. :type 'boolean
  5275. :version "24.1"
  5276. :group 'org-appearance)
  5277. (defun org-fontify-meta-lines-and-blocks (limit)
  5278. (condition-case nil
  5279. (org-fontify-meta-lines-and-blocks-1 limit)
  5280. (error (message "org-mode fontification error in %S at %d"
  5281. (current-buffer)
  5282. (line-number-at-pos)))))
  5283. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5284. "Fontify #+ lines and blocks."
  5285. (let ((case-fold-search t))
  5286. (when (re-search-forward
  5287. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5288. limit t)
  5289. (let ((beg (match-beginning 0))
  5290. (block-start (match-end 0))
  5291. (block-end nil)
  5292. (lang (match-string 7))
  5293. (beg1 (line-beginning-position 2))
  5294. (dc1 (downcase (match-string 2)))
  5295. (dc3 (downcase (match-string 3)))
  5296. end end1 quoting block-type)
  5297. (cond
  5298. ((and (match-end 4) (equal dc3 "+begin"))
  5299. ;; Truly a block
  5300. (setq block-type (downcase (match-string 5))
  5301. quoting (member block-type org-protecting-blocks))
  5302. (when (re-search-forward
  5303. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5304. nil t) ;; on purpose, we look further than LIMIT
  5305. (setq end (min (point-max) (match-end 0))
  5306. end1 (min (point-max) (1- (match-beginning 0))))
  5307. (setq block-end (match-beginning 0))
  5308. (when quoting
  5309. (org-remove-flyspell-overlays-in beg1 end1)
  5310. (remove-text-properties beg end
  5311. '(display t invisible t intangible t)))
  5312. (add-text-properties
  5313. beg end '(font-lock-fontified t font-lock-multiline t))
  5314. (add-text-properties beg beg1 '(face org-meta-line))
  5315. (org-remove-flyspell-overlays-in beg beg1)
  5316. (add-text-properties ; For end_src
  5317. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5318. (org-remove-flyspell-overlays-in end1 end)
  5319. (cond
  5320. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5321. (org-src-font-lock-fontify-block lang block-start block-end)
  5322. (add-text-properties beg1 block-end '(src-block t)))
  5323. (quoting
  5324. (add-text-properties beg1 (min (point-max) (1+ end1))
  5325. (list 'face
  5326. (list :inherit
  5327. (let ((face-name
  5328. (intern (format "org-block-%s" lang))))
  5329. (append (and (facep face-name) (list face-name))
  5330. '(org-block))))))) ; end of source block
  5331. ((not org-fontify-quote-and-verse-blocks))
  5332. ((string= block-type "quote")
  5333. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5334. ((string= block-type "verse")
  5335. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5336. (add-text-properties beg beg1 '(face org-block-begin-line))
  5337. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5338. '(face org-block-end-line))
  5339. t))
  5340. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5341. (org-remove-flyspell-overlays-in
  5342. (match-beginning 0)
  5343. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5344. (add-text-properties
  5345. beg (match-end 3)
  5346. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5347. '(font-lock-fontified t invisible t)
  5348. '(font-lock-fontified t face org-document-info-keyword)))
  5349. (add-text-properties
  5350. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5351. (if (string-equal dc1 "+title:")
  5352. '(font-lock-fontified t face org-document-title)
  5353. '(font-lock-fontified t face org-document-info))))
  5354. ((equal dc1 "+caption:")
  5355. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5356. (remove-text-properties (match-beginning 0) (match-end 0)
  5357. '(display t invisible t intangible t))
  5358. (add-text-properties (match-beginning 1) (match-end 3)
  5359. '(font-lock-fontified t face org-meta-line))
  5360. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5361. '(font-lock-fontified t face org-block))
  5362. t)
  5363. ((member dc3 '(" " ""))
  5364. (org-remove-flyspell-overlays-in beg (match-end 0))
  5365. (add-text-properties
  5366. beg (match-end 0)
  5367. '(font-lock-fontified t face font-lock-comment-face)))
  5368. (t ;; just any other in-buffer setting, but not indented
  5369. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5370. (remove-text-properties (match-beginning 0) (match-end 0)
  5371. '(display t invisible t intangible t))
  5372. (add-text-properties beg (match-end 0)
  5373. '(font-lock-fontified t face org-meta-line))
  5374. t))))))
  5375. (defun org-fontify-drawers (limit)
  5376. "Fontify drawers."
  5377. (when (re-search-forward org-drawer-regexp limit t)
  5378. (add-text-properties
  5379. (match-beginning 0) (match-end 0)
  5380. '(font-lock-fontified t face org-special-keyword))
  5381. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5382. t))
  5383. (defun org-fontify-macros (limit)
  5384. "Fontify macros."
  5385. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5386. (add-text-properties
  5387. (match-beginning 0) (match-end 0)
  5388. '(font-lock-fontified t face org-macro))
  5389. (when org-hide-macro-markers
  5390. (add-text-properties (match-end 2) (match-beginning 2)
  5391. '(invisible t))
  5392. (add-text-properties (match-beginning 1) (match-end 1)
  5393. '(invisible t)))
  5394. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5395. t))
  5396. (defun org-activate-angle-links (limit)
  5397. "Add text properties for angle links."
  5398. (when (and (re-search-forward org-angle-link-re limit t)
  5399. (not (org-in-src-block-p)))
  5400. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5401. (add-text-properties (match-beginning 0) (match-end 0)
  5402. (list 'mouse-face 'highlight
  5403. 'keymap org-mouse-map
  5404. 'font-lock-multiline t))
  5405. (org-rear-nonsticky-at (match-end 0))
  5406. t))
  5407. (defun org-activate-footnote-links (limit)
  5408. "Add text properties for footnotes."
  5409. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5410. (when fn
  5411. (let* ((beg (nth 1 fn))
  5412. (end (nth 2 fn))
  5413. (label (car fn))
  5414. (referencep (/= (line-beginning-position) beg)))
  5415. (when (and referencep (nth 3 fn))
  5416. (save-excursion
  5417. (goto-char beg)
  5418. (search-forward (or label "fn:"))
  5419. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5420. (add-text-properties beg end
  5421. (list 'mouse-face 'highlight
  5422. 'keymap org-mouse-map
  5423. 'help-echo
  5424. (if referencep "Footnote reference"
  5425. "Footnote definition")
  5426. 'font-lock-fontified t
  5427. 'font-lock-multiline t
  5428. 'face 'org-footnote))))))
  5429. (defun org-activate-bracket-links (limit)
  5430. "Add text properties for bracketed links."
  5431. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5432. (not (org-in-src-block-p)))
  5433. (let* ((hl (match-string-no-properties 1))
  5434. (type (save-match-data
  5435. (and (string-match org-plain-link-re hl)
  5436. (match-string-no-properties 1 hl))))
  5437. (path (save-match-data
  5438. (and (string-match org-plain-link-re hl)
  5439. (match-string-no-properties 2 hl))))
  5440. (link-start (match-beginning 0))
  5441. (link-end (match-end 0))
  5442. (bracketp t)
  5443. (help-echo (org-link-get-parameter type :help-echo))
  5444. (help (cond
  5445. ((stringp help-echo)
  5446. help-echo)
  5447. ((functionp help-echo)
  5448. help-echo)
  5449. (t
  5450. (concat "LINK: "
  5451. (save-match-data
  5452. (org-link-unescape hl))))))
  5453. (link-face (org-link-get-parameter type :face))
  5454. (face (cond
  5455. ;; A function that returns a face
  5456. ((functionp link-face)
  5457. (funcall link-face path))
  5458. ;; a face
  5459. ((facep link-face)
  5460. link-face)
  5461. ;; An anonymous face
  5462. ((consp link-face)
  5463. link-face)
  5464. ;; default
  5465. (t
  5466. 'org-link)))
  5467. (keymap (or (org-link-get-parameter type :keymap)
  5468. org-mouse-map))
  5469. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5470. 'highlight))
  5471. (htmlize (org-link-get-parameter type :htmlize-link))
  5472. (htmlize-link (cond
  5473. ((functionp htmlize)
  5474. (funcall htmlize))
  5475. (t
  5476. `(:uri ,(format "%s:%s" type path)))))
  5477. (activate-func (org-link-get-parameter type :activate-func))
  5478. ;; invisible part
  5479. (ip (list 'invisible (or
  5480. (org-link-get-parameter type :display)
  5481. 'org-link)
  5482. 'face face
  5483. 'keymap keymap
  5484. 'mouse-face mouse-face
  5485. 'font-lock-multiline t
  5486. 'help-echo help
  5487. 'htmlize-link htmlize-link))
  5488. ;; visible part
  5489. (vp (list 'keymap keymap
  5490. 'face face
  5491. 'mouse-face mouse-face
  5492. 'font-lock-multiline t
  5493. 'help-echo help
  5494. 'htmlize-link htmlize-link)))
  5495. ;; We need to remove the invisible property here. Table narrowing
  5496. ;; may have made some of this invisible.
  5497. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5498. (remove-text-properties (match-beginning 0) (match-end 0)
  5499. '(invisible nil))
  5500. (if (match-end 3)
  5501. (progn
  5502. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5503. (org-rear-nonsticky-at (match-beginning 3))
  5504. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5505. (org-rear-nonsticky-at (match-end 3))
  5506. (add-text-properties (match-end 3) (match-end 0) ip)
  5507. (org-rear-nonsticky-at (match-end 0)))
  5508. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5509. (org-rear-nonsticky-at (match-beginning 1))
  5510. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5511. (org-rear-nonsticky-at (match-end 1))
  5512. (add-text-properties (match-end 1) (match-end 0) ip)
  5513. (org-rear-nonsticky-at (match-end 0)))
  5514. (when activate-func
  5515. (funcall activate-func link-start link-end path bracketp))
  5516. t)))
  5517. (defun org-activate-dates (limit)
  5518. "Add text properties for dates."
  5519. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5520. (not (equal (char-before (match-beginning 0)) 91)))
  5521. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5522. (add-text-properties (match-beginning 0) (match-end 0)
  5523. (list 'mouse-face 'highlight
  5524. 'keymap org-mouse-map))
  5525. (org-rear-nonsticky-at (match-end 0))
  5526. (when org-display-custom-times
  5527. (if (match-end 3)
  5528. (org-display-custom-time (match-beginning 3) (match-end 3))
  5529. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5530. t))
  5531. (defvar-local org-target-link-regexp nil
  5532. "Regular expression matching radio targets in plain text.")
  5533. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5534. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5535. border border border))
  5536. "Regular expression matching a link target.")
  5537. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5538. "Regular expression matching a radio target.")
  5539. (defconst org-any-target-regexp
  5540. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5541. "Regular expression matching any target.")
  5542. (defun org-activate-target-links (limit)
  5543. "Add text properties for target matches."
  5544. (when org-target-link-regexp
  5545. (let ((case-fold-search t))
  5546. (when (re-search-forward org-target-link-regexp limit t)
  5547. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5548. (add-text-properties (match-beginning 1) (match-end 1)
  5549. (list 'mouse-face 'highlight
  5550. 'keymap org-mouse-map
  5551. 'help-echo "Radio target link"
  5552. 'org-linked-text t))
  5553. (org-rear-nonsticky-at (match-end 1))
  5554. t))))
  5555. (defun org-update-radio-target-regexp ()
  5556. "Find all radio targets in this file and update the regular expression.
  5557. Also refresh fontification if needed."
  5558. (interactive)
  5559. (let ((old-regexp org-target-link-regexp)
  5560. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5561. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5562. (targets
  5563. (org-with-wide-buffer
  5564. (goto-char (point-min))
  5565. (let (rtn)
  5566. (while (re-search-forward org-radio-target-regexp nil t)
  5567. ;; Make sure point is really within the object.
  5568. (backward-char)
  5569. (let ((obj (org-element-context)))
  5570. (when (eq (org-element-type obj) 'radio-target)
  5571. (cl-pushnew (org-element-property :value obj) rtn
  5572. :test #'equal))))
  5573. rtn))))
  5574. (setq org-target-link-regexp
  5575. (and targets
  5576. (concat before-re
  5577. (mapconcat
  5578. (lambda (x)
  5579. (replace-regexp-in-string
  5580. " +" "\\s-+" (regexp-quote x) t t))
  5581. targets
  5582. "\\|")
  5583. after-re)))
  5584. (unless (equal old-regexp org-target-link-regexp)
  5585. ;; Clean-up cache.
  5586. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5587. ((not org-target-link-regexp) old-regexp)
  5588. (t
  5589. (concat before-re
  5590. (mapconcat
  5591. (lambda (re)
  5592. (substring re (length before-re)
  5593. (- (length after-re))))
  5594. (list old-regexp org-target-link-regexp)
  5595. "\\|")
  5596. after-re)))))
  5597. (org-with-wide-buffer
  5598. (goto-char (point-min))
  5599. (while (re-search-forward regexp nil t)
  5600. (org-element-cache-refresh (match-beginning 1)))))
  5601. ;; Re fontify buffer.
  5602. (when (memq 'radio org-highlight-links)
  5603. (org-restart-font-lock)))))
  5604. (defun org-hide-wide-columns (limit)
  5605. (let (s e)
  5606. (setq s (text-property-any (point) (or limit (point-max))
  5607. 'org-cwidth t))
  5608. (when s
  5609. (setq e (next-single-property-change s 'org-cwidth))
  5610. (add-text-properties s e '(invisible org-cwidth))
  5611. (goto-char e)
  5612. t)))
  5613. (defvar org-latex-and-related-regexp nil
  5614. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5615. (defun org-compute-latex-and-related-regexp ()
  5616. "Compute regular expression for LaTeX, entities and sub/superscript.
  5617. Result depends on variable `org-highlight-latex-and-related'."
  5618. (setq-local
  5619. org-latex-and-related-regexp
  5620. (let* ((re-sub
  5621. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5622. ((eq org-use-sub-superscripts '{})
  5623. (list org-match-substring-with-braces-regexp))
  5624. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5625. (re-latex
  5626. (when (memq 'latex org-highlight-latex-and-related)
  5627. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5628. (delq nil
  5629. (mapcar (lambda (x)
  5630. (and (member (car x) matchers) (nth 1 x)))
  5631. org-latex-regexps)))))
  5632. (re-entities
  5633. (when (memq 'entities org-highlight-latex-and-related)
  5634. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5635. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5636. (defun org-do-latex-and-related (limit)
  5637. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5638. LIMIT bounds the search for syntax to highlight. Stop at first
  5639. highlighted object, if any. Return t if some highlighting was
  5640. done, nil otherwise."
  5641. (when (org-string-nw-p org-latex-and-related-regexp)
  5642. (catch 'found
  5643. (while (re-search-forward org-latex-and-related-regexp limit t)
  5644. (unless
  5645. (cl-some
  5646. (lambda (f)
  5647. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5648. (save-excursion
  5649. (goto-char (1+ (match-beginning 0)))
  5650. (face-at-point nil t)))
  5651. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5652. '(?_ ?^))
  5653. 1
  5654. 0)))
  5655. (font-lock-prepend-text-property
  5656. (+ offset (match-beginning 0)) (match-end 0)
  5657. 'face 'org-latex-and-related)
  5658. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5659. '(font-lock-multiline t)))
  5660. (throw 'found t)))
  5661. nil)))
  5662. (defun org-restart-font-lock ()
  5663. "Restart `font-lock-mode', to force refontification."
  5664. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5665. (font-lock-mode -1)
  5666. (font-lock-mode 1)))
  5667. (defun org-activate-tags (limit)
  5668. (when (re-search-forward
  5669. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5670. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5671. (add-text-properties (match-beginning 1) (match-end 1)
  5672. (list 'mouse-face 'highlight
  5673. 'keymap org-mouse-map))
  5674. (org-rear-nonsticky-at (match-end 1))
  5675. t))
  5676. (defun org-outline-level ()
  5677. "Compute the outline level of the heading at point.
  5678. If this is called at a normal headline, the level is the number
  5679. of stars. Use `org-reduced-level' to remove the effect of
  5680. `org-odd-levels'. Unlike to `org-current-level', this function
  5681. takes into consideration inlinetasks."
  5682. (org-with-wide-buffer
  5683. (end-of-line)
  5684. (if (re-search-backward org-outline-regexp-bol nil t)
  5685. (1- (- (match-end 0) (match-beginning 0)))
  5686. 0)))
  5687. (defvar org-font-lock-keywords nil)
  5688. (defsubst org-re-property (property &optional literal allow-null value)
  5689. "Return a regexp matching a PROPERTY line.
  5690. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5691. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5692. non-nil, match properties even without a value.
  5693. Match group 3 is set to the value when it exists. If there is no
  5694. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5695. With optional argument VALUE, match only property lines with
  5696. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5697. unless LITERAL is non-nil."
  5698. (concat
  5699. "^\\(?4:[ \t]*\\)"
  5700. (format "\\(?1::\\(?2:%s\\):\\)"
  5701. (if literal property (regexp-quote property)))
  5702. (cond (value
  5703. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5704. (if literal value (regexp-quote value))))
  5705. (allow-null
  5706. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5707. (t
  5708. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5709. (defconst org-property-re
  5710. (org-re-property "\\S-+" 'literal t)
  5711. "Regular expression matching a property line.
  5712. There are four matching groups:
  5713. 1: :PROPKEY: including the leading and trailing colon,
  5714. 2: PROPKEY without the leading and trailing colon,
  5715. 3: PROPVAL without leading or trailing spaces,
  5716. 4: the indentation of the current line,
  5717. 5: trailing whitespace.")
  5718. (defvar org-font-lock-hook nil
  5719. "Functions to be called for special font lock stuff.")
  5720. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5721. (defvar org-font-lock-set-keywords-hook nil
  5722. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5723. This is called after `org-font-lock-extra-keywords' is defined, but before
  5724. it is installed to be used by font lock. This can be useful if something
  5725. needs to be inserted at a specific position in the font-lock sequence.")
  5726. (defun org-font-lock-hook (limit)
  5727. "Run `org-font-lock-hook' within LIMIT."
  5728. (run-hook-with-args 'org-font-lock-hook limit))
  5729. (defun org-set-font-lock-defaults ()
  5730. "Set font lock defaults for the current buffer."
  5731. (let* ((em org-fontify-emphasized-text)
  5732. (lk org-highlight-links)
  5733. (org-font-lock-extra-keywords
  5734. (list
  5735. ;; Call the hook
  5736. '(org-font-lock-hook)
  5737. ;; Headlines
  5738. `(,(if org-fontify-whole-heading-line
  5739. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5740. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5741. (1 (org-get-level-face 1))
  5742. (2 (org-get-level-face 2))
  5743. (3 (org-get-level-face 3)))
  5744. ;; Table lines
  5745. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5746. (1 'org-table t))
  5747. ;; Table internals
  5748. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5749. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5750. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5751. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5752. ;; Drawers
  5753. '(org-fontify-drawers)
  5754. ;; Properties
  5755. (list org-property-re
  5756. '(1 'org-special-keyword t)
  5757. '(3 'org-property-value t))
  5758. ;; Links
  5759. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5760. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5761. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5762. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5763. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5764. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5765. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5766. ;; Targets.
  5767. (list org-any-target-regexp '(0 'org-target t))
  5768. ;; Diary sexps.
  5769. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5770. ;; Macro
  5771. '(org-fontify-macros)
  5772. '(org-hide-wide-columns (0 nil append))
  5773. ;; TODO keyword
  5774. (list (format org-heading-keyword-regexp-format
  5775. org-todo-regexp)
  5776. '(2 (org-get-todo-face 2) t))
  5777. ;; DONE
  5778. (if org-fontify-done-headline
  5779. (list (format org-heading-keyword-regexp-format
  5780. (concat
  5781. "\\(?:"
  5782. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5783. "\\)"))
  5784. '(2 'org-headline-done t))
  5785. nil)
  5786. ;; Priorities
  5787. '(org-font-lock-add-priority-faces)
  5788. ;; Tags
  5789. '(org-font-lock-add-tag-faces)
  5790. ;; Tags groups
  5791. (when (and org-group-tags org-tag-groups-alist)
  5792. (list (concat org-outline-regexp-bol ".+\\(:"
  5793. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5794. ":\\).*$")
  5795. '(1 'org-tag-group prepend)))
  5796. ;; Special keywords
  5797. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5798. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5799. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5800. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5801. ;; Emphasis
  5802. (when em '(org-do-emphasis-faces))
  5803. ;; Checkboxes
  5804. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5805. 1 'org-checkbox prepend)
  5806. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5807. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5808. (0 (org-get-checkbox-statistics-face) t)))
  5809. ;; Description list items
  5810. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5811. 1 'org-list-dt prepend)
  5812. ;; ARCHIVEd headings
  5813. (list (concat
  5814. org-outline-regexp-bol
  5815. "\\(.*:" org-archive-tag ":.*\\)")
  5816. '(1 'org-archived prepend))
  5817. ;; Specials
  5818. '(org-do-latex-and-related)
  5819. '(org-fontify-entities)
  5820. '(org-raise-scripts)
  5821. ;; Code
  5822. '(org-activate-code (1 'org-code t))
  5823. ;; COMMENT
  5824. (list (format
  5825. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5826. org-todo-regexp
  5827. org-comment-string)
  5828. '(9 'org-special-keyword t))
  5829. ;; Blocks and meta lines
  5830. '(org-fontify-meta-lines-and-blocks))))
  5831. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5832. (run-hooks 'org-font-lock-set-keywords-hook)
  5833. ;; Now set the full font-lock-keywords
  5834. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5835. (setq-local font-lock-defaults
  5836. '(org-font-lock-keywords t nil nil backward-paragraph))
  5837. (kill-local-variable 'font-lock-keywords)
  5838. nil))
  5839. (defun org-toggle-pretty-entities ()
  5840. "Toggle the composition display of entities as UTF8 characters."
  5841. (interactive)
  5842. (setq-local org-pretty-entities (not org-pretty-entities))
  5843. (org-restart-font-lock)
  5844. (if org-pretty-entities
  5845. (message "Entities are now displayed as UTF8 characters")
  5846. (save-restriction
  5847. (widen)
  5848. (decompose-region (point-min) (point-max))
  5849. (message "Entities are now displayed as plain text"))))
  5850. (defvar-local org-custom-properties-overlays nil
  5851. "List of overlays used for custom properties.")
  5852. (defun org-toggle-custom-properties-visibility ()
  5853. "Display or hide properties in `org-custom-properties'."
  5854. (interactive)
  5855. (if org-custom-properties-overlays
  5856. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5857. (setq org-custom-properties-overlays nil))
  5858. (when org-custom-properties
  5859. (org-with-wide-buffer
  5860. (goto-char (point-min))
  5861. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5862. (while (re-search-forward regexp nil t)
  5863. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5864. (when (and end (< (point) end))
  5865. ;; Hide first custom property in current drawer.
  5866. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5867. (overlay-put o 'invisible t)
  5868. (overlay-put o 'org-custom-property t)
  5869. (push o org-custom-properties-overlays))
  5870. ;; Hide additional custom properties in the same drawer.
  5871. (while (re-search-forward regexp end t)
  5872. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5873. (overlay-put o 'invisible t)
  5874. (overlay-put o 'org-custom-property t)
  5875. (push o org-custom-properties-overlays)))))
  5876. ;; Each entry is limited to a single property drawer.
  5877. (outline-next-heading)))))))
  5878. (defun org-fontify-entities (limit)
  5879. "Find an entity to fontify."
  5880. (let (ee)
  5881. (when org-pretty-entities
  5882. (catch 'match
  5883. ;; "\_ "-family is left out on purpose. Only the first one,
  5884. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5885. ;; confusing when adding a second white space character.
  5886. (while (re-search-forward
  5887. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5888. limit t)
  5889. (when (and (not (org-at-comment-p))
  5890. (setq ee (org-entity-get (match-string 1)))
  5891. (= (length (nth 6 ee)) 1))
  5892. (let* ((end (if (equal (match-string 2) "{}")
  5893. (match-end 2)
  5894. (match-end 1))))
  5895. (add-text-properties
  5896. (match-beginning 0) end
  5897. (list 'font-lock-fontified t))
  5898. (compose-region (match-beginning 0) end
  5899. (nth 6 ee) nil)
  5900. (backward-char 1)
  5901. (throw 'match t))))
  5902. nil))))
  5903. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5904. "Fontify string S like in Org-mode."
  5905. (with-temp-buffer
  5906. (insert s)
  5907. (let ((org-odd-levels-only odd-levels))
  5908. (org-mode)
  5909. (org-font-lock-ensure)
  5910. (buffer-string))))
  5911. (defvar org-m nil)
  5912. (defvar org-l nil)
  5913. (defvar org-f nil)
  5914. (defun org-get-level-face (n)
  5915. "Get the right face for match N in font-lock matching of headlines."
  5916. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5917. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5918. (if org-cycle-level-faces
  5919. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5920. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5921. (cond
  5922. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5923. ((eq n 2) org-f)
  5924. (t (unless org-level-color-stars-only org-f))))
  5925. (defun org-face-from-face-or-color (context inherit face-or-color)
  5926. "Create a face list that inherits INHERIT, but sets the foreground color.
  5927. When FACE-OR-COLOR is not a string, just return it."
  5928. (if (stringp face-or-color)
  5929. (list :inherit inherit
  5930. (cdr (assoc context org-faces-easy-properties))
  5931. face-or-color)
  5932. face-or-color))
  5933. (defun org-get-todo-face (kwd)
  5934. "Get the right face for a TODO keyword KWD.
  5935. If KWD is a number, get the corresponding match group."
  5936. (when (numberp kwd) (setq kwd (match-string kwd)))
  5937. (or (org-face-from-face-or-color
  5938. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5939. (and (member kwd org-done-keywords) 'org-done)
  5940. 'org-todo))
  5941. (defun org-get-priority-face (priority)
  5942. "Get the right face for PRIORITY.
  5943. PRIORITY is a character."
  5944. (or (org-face-from-face-or-color
  5945. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5946. 'org-priority))
  5947. (defun org-get-tag-face (tag)
  5948. "Get the right face for TAG.
  5949. If TAG is a number, get the corresponding match group."
  5950. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5951. (or (org-face-from-face-or-color
  5952. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5953. 'org-tag)))
  5954. (defun org-font-lock-add-priority-faces (limit)
  5955. "Add the special priority faces."
  5956. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5957. (add-text-properties
  5958. (match-beginning 1) (match-end 1)
  5959. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5960. 'font-lock-fontified t))))
  5961. (defun org-font-lock-add-tag-faces (limit)
  5962. "Add the special tag faces."
  5963. (when (and org-tag-faces org-tags-special-faces-re)
  5964. (while (re-search-forward org-tags-special-faces-re limit t)
  5965. (add-text-properties (match-beginning 1) (match-end 1)
  5966. (list 'face (org-get-tag-face 1)
  5967. 'font-lock-fontified t))
  5968. (backward-char 1))))
  5969. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5970. "Remove fontification and activation overlays from links."
  5971. (font-lock-default-unfontify-region beg end)
  5972. (let* ((buffer-undo-list t)
  5973. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5974. (inhibit-modification-hooks t)
  5975. deactivate-mark buffer-file-name buffer-file-truename)
  5976. (decompose-region beg end)
  5977. (remove-text-properties beg end
  5978. '(mouse-face t keymap t org-linked-text t
  5979. invisible t intangible t
  5980. org-emphasis t))
  5981. (org-remove-font-lock-display-properties beg end)))
  5982. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5983. ((raise 0.3) (height 0.7))
  5984. ((raise -0.5))
  5985. ((raise 0.5)))
  5986. "Display properties for showing superscripts and subscripts.")
  5987. (defun org-remove-font-lock-display-properties (beg end)
  5988. "Remove specific display properties that have been added by font lock.
  5989. The will remove the raise properties that are used to show superscripts
  5990. and subscripts."
  5991. (let (next prop)
  5992. (while (< beg end)
  5993. (setq next (next-single-property-change beg 'display nil end)
  5994. prop (get-text-property beg 'display))
  5995. (when (member prop org-script-display)
  5996. (put-text-property beg next 'display nil))
  5997. (setq beg next))))
  5998. (defun org-raise-scripts (limit)
  5999. "Add raise properties to sub/superscripts."
  6000. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  6001. (re-search-forward
  6002. (if (eq org-use-sub-superscripts t)
  6003. org-match-substring-regexp
  6004. org-match-substring-with-braces-regexp)
  6005. limit t))
  6006. (let* ((pos (point)) table-p comment-p
  6007. (mpos (match-beginning 3))
  6008. (emph-p (get-text-property mpos 'org-emphasis))
  6009. (link-p (get-text-property mpos 'mouse-face))
  6010. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  6011. (goto-char (point-at-bol))
  6012. (setq table-p (looking-at-p org-table-dataline-regexp)
  6013. comment-p (looking-at-p "^[ \t]*#[ +]"))
  6014. (goto-char pos)
  6015. ;; Handle a_b^c
  6016. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  6017. (unless (or comment-p emph-p link-p keyw-p)
  6018. (put-text-property (match-beginning 3) (match-end 0)
  6019. 'display
  6020. (if (equal (char-after (match-beginning 2)) ?^)
  6021. (nth (if table-p 3 1) org-script-display)
  6022. (nth (if table-p 2 0) org-script-display)))
  6023. (add-text-properties (match-beginning 2) (match-end 2)
  6024. (list 'invisible t
  6025. 'org-dwidth t 'org-dwidth-n 1))
  6026. (if (and (eq (char-after (match-beginning 3)) ?{)
  6027. (eq (char-before (match-end 3)) ?}))
  6028. (progn
  6029. (add-text-properties
  6030. (match-beginning 3) (1+ (match-beginning 3))
  6031. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6032. (add-text-properties
  6033. (1- (match-end 3)) (match-end 3)
  6034. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6035. t)))
  6036. ;;;; Visibility cycling, including org-goto and indirect buffer
  6037. ;;; Cycling
  6038. (defvar-local org-cycle-global-status nil)
  6039. (put 'org-cycle-global-status 'org-state t)
  6040. (defvar-local org-cycle-subtree-status nil)
  6041. (put 'org-cycle-subtree-status 'org-state t)
  6042. (defvar org-inlinetask-min-level)
  6043. (defun org-unlogged-message (&rest args)
  6044. "Display a message, but avoid logging it in the *Messages* buffer."
  6045. (let ((message-log-max nil))
  6046. (apply 'message args)))
  6047. ;;;###autoload
  6048. (defun org-cycle (&optional arg)
  6049. "TAB-action and visibility cycling for Org-mode.
  6050. This is the command invoked in Org-mode by the TAB key. Its main purpose
  6051. is outline visibility cycling, but it also invokes other actions
  6052. in special contexts.
  6053. - When this function is called with a prefix argument, rotate the entire
  6054. buffer through 3 states (global cycling)
  6055. 1. OVERVIEW: Show only top-level headlines.
  6056. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6057. 3. SHOW ALL: Show everything.
  6058. With a double \\[universal-argument] prefix argument, \
  6059. switch to the startup visibility,
  6060. determined by the variable `org-startup-folded', and by any VISIBILITY
  6061. properties in the buffer.
  6062. With a triple \\[universal-argument] prefix argument, \
  6063. show the entire buffer, including any drawers.
  6064. - When inside a table, re-align the table and move to the next field.
  6065. - When point is at the beginning of a headline, rotate the subtree started
  6066. by this line through 3 different states (local cycling)
  6067. 1. FOLDED: Only the main headline is shown.
  6068. 2. CHILDREN: The main headline and the direct children are shown.
  6069. From this state, you can move to one of the children
  6070. and zoom in further.
  6071. 3. SUBTREE: Show the entire subtree, including body text.
  6072. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6073. - When point is at the beginning of an empty headline and the variable
  6074. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6075. of the headline by demoting and promoting it to likely levels. This
  6076. speeds up creation document structure by pressing TAB once or several
  6077. times right after creating a new headline.
  6078. - When there is a numeric prefix, go up to a heading with level ARG, do
  6079. a `show-subtree' and return to the previous cursor position. If ARG
  6080. is negative, go up that many levels.
  6081. - When point is not at the beginning of a headline, execute the global
  6082. binding for TAB, which is re-indenting the line. See the option
  6083. `org-cycle-emulate-tab' for details.
  6084. - Special case: if point is at the beginning of the buffer and there is
  6085. no headline in line 1, this function will act as if called with prefix arg
  6086. (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
  6087. But only if also the variable `org-cycle-global-at-bob' is t."
  6088. (interactive "P")
  6089. (org-load-modules-maybe)
  6090. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6091. (and org-cycle-level-after-item/entry-creation
  6092. (or (org-cycle-level)
  6093. (org-cycle-item-indentation))))
  6094. (let* ((limit-level
  6095. (or org-cycle-max-level
  6096. (and (boundp 'org-inlinetask-min-level)
  6097. org-inlinetask-min-level
  6098. (1- org-inlinetask-min-level))))
  6099. (nstars (and limit-level
  6100. (if org-odd-levels-only
  6101. (and limit-level (1- (* limit-level 2)))
  6102. limit-level)))
  6103. (org-outline-regexp
  6104. (if (not (derived-mode-p 'org-mode))
  6105. outline-regexp
  6106. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6107. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6108. (not (looking-at org-outline-regexp))))
  6109. (org-cycle-hook
  6110. (if bob-special
  6111. (delq 'org-optimize-window-after-visibility-change
  6112. (copy-sequence org-cycle-hook))
  6113. org-cycle-hook))
  6114. (pos (point)))
  6115. (when (or bob-special (equal arg '(4)))
  6116. ;; special case: use global cycling
  6117. (setq arg t))
  6118. (cond
  6119. ((equal arg '(16))
  6120. (setq last-command 'dummy)
  6121. (org-set-startup-visibility)
  6122. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6123. ((equal arg '(64))
  6124. (outline-show-all)
  6125. (org-unlogged-message "Entire buffer visible, including drawers"))
  6126. ;; Try cdlatex TAB completion
  6127. ((org-try-cdlatex-tab))
  6128. ;; Table: enter it or move to the next field.
  6129. ((org-at-table-p 'any)
  6130. (if (org-at-table.el-p)
  6131. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6132. Use \\[org-edit-special] to edit table.el tables"))
  6133. (if arg (org-table-edit-field t)
  6134. (org-table-justify-field-maybe)
  6135. (call-interactively 'org-table-next-field))))
  6136. ((run-hook-with-args-until-success
  6137. 'org-tab-after-check-for-table-hook))
  6138. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6139. ((eq arg t) (org-cycle-internal-global))
  6140. ;; Drawers: delegate to `org-flag-drawer'.
  6141. ((save-excursion
  6142. (beginning-of-line 1)
  6143. (looking-at org-drawer-regexp))
  6144. (org-flag-drawer ; toggle block visibility
  6145. (not (get-char-property (match-end 0) 'invisible))))
  6146. ;; Show-subtree, ARG levels up from here.
  6147. ((integerp arg)
  6148. (save-excursion
  6149. (org-back-to-heading)
  6150. (outline-up-heading (if (< arg 0) (- arg)
  6151. (- (funcall outline-level) arg)))
  6152. (org-show-subtree)))
  6153. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6154. ((and (featurep 'org-inlinetask)
  6155. (org-inlinetask-at-task-p)
  6156. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6157. (org-inlinetask-toggle-visibility))
  6158. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6159. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6160. (save-excursion (move-beginning-of-line 1)
  6161. (looking-at org-outline-regexp)))
  6162. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6163. (org-cycle-internal-local))
  6164. ;; From there: TAB emulation and template completion.
  6165. (buffer-read-only (org-back-to-heading))
  6166. ((run-hook-with-args-until-success
  6167. 'org-tab-after-check-for-cycling-hook))
  6168. ((org-try-structure-completion))
  6169. ((run-hook-with-args-until-success
  6170. 'org-tab-before-tab-emulation-hook))
  6171. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6172. (or (not (bolp))
  6173. (not (looking-at org-outline-regexp))))
  6174. (call-interactively (global-key-binding "\t")))
  6175. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6176. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6177. (or (and (eq org-cycle-emulate-tab 'white)
  6178. (= (match-end 0) (point-at-eol)))
  6179. (and (eq org-cycle-emulate-tab 'whitestart)
  6180. (>= (match-end 0) pos))))
  6181. t
  6182. (eq org-cycle-emulate-tab t))
  6183. (call-interactively (global-key-binding "\t")))
  6184. (t (save-excursion
  6185. (org-back-to-heading)
  6186. (org-cycle)))))))
  6187. (defun org-cycle-internal-global ()
  6188. "Do the global cycling action."
  6189. ;; Hack to avoid display of messages for .org attachments in Gnus
  6190. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6191. (cond
  6192. ((and (eq last-command this-command)
  6193. (eq org-cycle-global-status 'overview))
  6194. ;; We just created the overview - now do table of contents
  6195. ;; This can be slow in very large buffers, so indicate action
  6196. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6197. (unless ga (org-unlogged-message "CONTENTS..."))
  6198. (org-content)
  6199. (unless ga (org-unlogged-message "CONTENTS...done"))
  6200. (setq org-cycle-global-status 'contents)
  6201. (run-hook-with-args 'org-cycle-hook 'contents))
  6202. ((and (eq last-command this-command)
  6203. (eq org-cycle-global-status 'contents))
  6204. ;; We just showed the table of contents - now show everything
  6205. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6206. (outline-show-all)
  6207. (unless ga (org-unlogged-message "SHOW ALL"))
  6208. (setq org-cycle-global-status 'all)
  6209. (run-hook-with-args 'org-cycle-hook 'all))
  6210. (t
  6211. ;; Default action: go to overview
  6212. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6213. (org-overview)
  6214. (unless ga (org-unlogged-message "OVERVIEW"))
  6215. (setq org-cycle-global-status 'overview)
  6216. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6217. (defvar org-called-with-limited-levels nil
  6218. "Non-nil when `org-with-limited-levels' is currently active.")
  6219. (defun org-cycle-internal-local ()
  6220. "Do the local cycling action."
  6221. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6222. ;; First, determine end of headline (EOH), end of subtree or item
  6223. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6224. (save-excursion
  6225. (if (org-at-item-p)
  6226. (progn
  6227. (beginning-of-line)
  6228. (setq struct (org-list-struct))
  6229. (setq eoh (point-at-eol))
  6230. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6231. (setq has-children (org-list-has-child-p (point) struct)))
  6232. (org-back-to-heading)
  6233. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6234. (setq eos (save-excursion (org-end-of-subtree t t)
  6235. (when (bolp) (backward-char)) (point)))
  6236. (setq has-children
  6237. (or (save-excursion
  6238. (let ((level (funcall outline-level)))
  6239. (outline-next-heading)
  6240. (and (org-at-heading-p t)
  6241. (> (funcall outline-level) level))))
  6242. (save-excursion
  6243. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6244. ;; Determine end invisible part of buffer (EOL)
  6245. (beginning-of-line 2)
  6246. (while (and (not (eobp)) ;This is like `next-line'.
  6247. (get-char-property (1- (point)) 'invisible))
  6248. (goto-char (next-single-char-property-change (point) 'invisible))
  6249. (and (eolp) (beginning-of-line 2)))
  6250. (setq eol (point)))
  6251. ;; Find out what to do next and set `this-command'
  6252. (cond
  6253. ((= eos eoh)
  6254. ;; Nothing is hidden behind this heading
  6255. (unless (org-before-first-heading-p)
  6256. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6257. (org-unlogged-message "EMPTY ENTRY")
  6258. (setq org-cycle-subtree-status nil)
  6259. (save-excursion
  6260. (goto-char eos)
  6261. (outline-next-heading)
  6262. (when (outline-invisible-p) (org-flag-heading nil))))
  6263. ((and (or (>= eol eos)
  6264. (not (string-match "\\S-" (buffer-substring eol eos))))
  6265. (or has-children
  6266. (not (setq children-skipped
  6267. org-cycle-skip-children-state-if-no-children))))
  6268. ;; Entire subtree is hidden in one line: children view
  6269. (unless (org-before-first-heading-p)
  6270. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6271. (if (org-at-item-p)
  6272. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6273. (org-show-entry)
  6274. (org-with-limited-levels (org-show-children))
  6275. ;; FIXME: This slows down the func way too much.
  6276. ;; How keep drawers hidden in subtree anyway?
  6277. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6278. ;; (org-cycle-hide-drawers 'subtree))
  6279. ;; Fold every list in subtree to top-level items.
  6280. (when (eq org-cycle-include-plain-lists 'integrate)
  6281. (save-excursion
  6282. (org-back-to-heading)
  6283. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6284. (beginning-of-line 1)
  6285. (let* ((struct (org-list-struct))
  6286. (prevs (org-list-prevs-alist struct))
  6287. (end (org-list-get-bottom-point struct)))
  6288. (dolist (e (org-list-get-all-items (point) struct prevs))
  6289. (org-list-set-item-visibility e struct 'folded))
  6290. (goto-char (if (< end eos) end eos)))))))
  6291. (org-unlogged-message "CHILDREN")
  6292. (save-excursion
  6293. (goto-char eos)
  6294. (outline-next-heading)
  6295. (when (outline-invisible-p) (org-flag-heading nil)))
  6296. (setq org-cycle-subtree-status 'children)
  6297. (unless (org-before-first-heading-p)
  6298. (run-hook-with-args 'org-cycle-hook 'children)))
  6299. ((or children-skipped
  6300. (and (eq last-command this-command)
  6301. (eq org-cycle-subtree-status 'children)))
  6302. ;; We just showed the children, or no children are there,
  6303. ;; now show everything.
  6304. (unless (org-before-first-heading-p)
  6305. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6306. (outline-flag-region eoh eos nil)
  6307. (org-unlogged-message
  6308. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6309. (setq org-cycle-subtree-status 'subtree)
  6310. (unless (org-before-first-heading-p)
  6311. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6312. (t
  6313. ;; Default action: hide the subtree.
  6314. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6315. (outline-flag-region eoh eos t)
  6316. (org-unlogged-message "FOLDED")
  6317. (setq org-cycle-subtree-status 'folded)
  6318. (unless (org-before-first-heading-p)
  6319. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6320. ;;;###autoload
  6321. (defun org-global-cycle (&optional arg)
  6322. "Cycle the global visibility. For details see `org-cycle'.
  6323. With \\[universal-argument] prefix arg, switch to startup visibility.
  6324. With a numeric prefix, show all headlines up to that level."
  6325. (interactive "P")
  6326. (let ((org-cycle-include-plain-lists
  6327. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6328. (cond
  6329. ((integerp arg)
  6330. (outline-show-all)
  6331. (outline-hide-sublevels arg)
  6332. (setq org-cycle-global-status 'contents))
  6333. ((equal arg '(4))
  6334. (org-set-startup-visibility)
  6335. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6336. (t
  6337. (org-cycle '(4))))))
  6338. (defun org-set-startup-visibility ()
  6339. "Set the visibility required by startup options and properties."
  6340. (cond
  6341. ((eq org-startup-folded t)
  6342. (org-overview))
  6343. ((eq org-startup-folded 'content)
  6344. (org-content))
  6345. ((or (eq org-startup-folded 'showeverything)
  6346. (eq org-startup-folded nil))
  6347. (outline-show-all)))
  6348. (unless (eq org-startup-folded 'showeverything)
  6349. (when org-hide-block-startup (org-hide-block-all))
  6350. (org-set-visibility-according-to-property 'no-cleanup)
  6351. (org-cycle-hide-archived-subtrees 'all)
  6352. (org-cycle-hide-drawers 'all)
  6353. (org-cycle-show-empty-lines t)))
  6354. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6355. "Switch subtree visibilities according to :VISIBILITY: property."
  6356. (interactive)
  6357. (org-with-wide-buffer
  6358. (goto-char (point-min))
  6359. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6360. (if (not (org-at-property-p)) (outline-next-heading)
  6361. (let ((state (match-string 3)))
  6362. (save-excursion
  6363. (org-back-to-heading t)
  6364. (outline-hide-subtree)
  6365. (org-reveal)
  6366. (cond
  6367. ((equal state "folded")
  6368. (outline-hide-subtree))
  6369. ((equal state "children")
  6370. (org-show-hidden-entry)
  6371. (org-show-children))
  6372. ((equal state "content")
  6373. (save-excursion
  6374. (save-restriction
  6375. (org-narrow-to-subtree)
  6376. (org-content))))
  6377. ((member state '("all" "showall"))
  6378. (outline-show-subtree)))))))
  6379. (unless no-cleanup
  6380. (org-cycle-hide-archived-subtrees 'all)
  6381. (org-cycle-hide-drawers 'all)
  6382. (org-cycle-show-empty-lines 'all))))
  6383. ;; This function uses outline-regexp instead of the more fundamental
  6384. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6385. ;; buffers, where outline-regexp is needed.
  6386. (defun org-overview ()
  6387. "Switch to overview mode, showing only top-level headlines.
  6388. This shows all headlines with a level equal or greater than the level
  6389. of the first headline in the buffer. This is important, because if the
  6390. first headline is not level one, then (hide-sublevels 1) gives confusing
  6391. results."
  6392. (interactive)
  6393. (save-excursion
  6394. (let ((level
  6395. (save-excursion
  6396. (goto-char (point-min))
  6397. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6398. (goto-char (match-beginning 0))
  6399. (funcall outline-level)))))
  6400. (and level (outline-hide-sublevels level)))))
  6401. (defun org-content (&optional arg)
  6402. "Show all headlines in the buffer, like a table of contents.
  6403. With numerical argument N, show content up to level N."
  6404. (interactive "P")
  6405. (org-overview)
  6406. (save-excursion
  6407. ;; Visit all headings and show their offspring
  6408. (and (integerp arg) (org-overview))
  6409. (goto-char (point-max))
  6410. (catch 'exit
  6411. (while (and (progn (condition-case nil
  6412. (outline-previous-visible-heading 1)
  6413. (error (goto-char (point-min))))
  6414. t)
  6415. (looking-at org-outline-regexp))
  6416. (if (integerp arg)
  6417. (org-show-children (1- arg))
  6418. (outline-show-branches))
  6419. (when (bobp) (throw 'exit nil))))))
  6420. (defun org-optimize-window-after-visibility-change (state)
  6421. "Adjust the window after a change in outline visibility.
  6422. This function is the default value of the hook `org-cycle-hook'."
  6423. (when (get-buffer-window (current-buffer))
  6424. (cond
  6425. ((eq state 'content) nil)
  6426. ((eq state 'all) nil)
  6427. ((eq state 'folded) nil)
  6428. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6429. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6430. (defun org-remove-empty-overlays-at (pos)
  6431. "Remove outline overlays that do not contain non-white stuff."
  6432. (dolist (o (overlays-at pos))
  6433. (and (eq 'outline (overlay-get o 'invisible))
  6434. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6435. (overlay-end o))))
  6436. (delete-overlay o))))
  6437. (defun org-clean-visibility-after-subtree-move ()
  6438. "Fix visibility issues after moving a subtree."
  6439. ;; First, find a reasonable region to look at:
  6440. ;; Start two siblings above, end three below
  6441. (let* ((beg (save-excursion
  6442. (and (org-get-last-sibling)
  6443. (org-get-last-sibling))
  6444. (point)))
  6445. (end (save-excursion
  6446. (and (org-get-next-sibling)
  6447. (org-get-next-sibling)
  6448. (org-get-next-sibling))
  6449. (if (org-at-heading-p)
  6450. (point-at-eol)
  6451. (point))))
  6452. (level (looking-at "\\*+"))
  6453. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6454. (save-excursion
  6455. (save-restriction
  6456. (narrow-to-region beg end)
  6457. (when re
  6458. ;; Properly fold already folded siblings
  6459. (goto-char (point-min))
  6460. (while (re-search-forward re nil t)
  6461. (when (and (not (outline-invisible-p))
  6462. (save-excursion
  6463. (goto-char (point-at-eol)) (outline-invisible-p)))
  6464. (outline-hide-entry))))
  6465. (org-cycle-show-empty-lines 'overview)
  6466. (org-cycle-hide-drawers 'overview)))))
  6467. (defun org-cycle-show-empty-lines (state)
  6468. "Show empty lines above all visible headlines.
  6469. The region to be covered depends on STATE when called through
  6470. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6471. entire buffer covered. Note that an empty line is only shown if there
  6472. are at least `org-cycle-separator-lines' empty lines before the headline."
  6473. (when (/= org-cycle-separator-lines 0)
  6474. (save-excursion
  6475. (let* ((n (abs org-cycle-separator-lines))
  6476. (re (cond
  6477. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6478. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6479. (t (let ((ns (number-to-string (- n 2))))
  6480. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6481. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6482. beg end)
  6483. (cond
  6484. ((memq state '(overview contents t))
  6485. (setq beg (point-min) end (point-max)))
  6486. ((memq state '(children folded))
  6487. (setq beg (point)
  6488. end (progn (org-end-of-subtree t t)
  6489. (line-beginning-position 2)))))
  6490. (when beg
  6491. (goto-char beg)
  6492. (while (re-search-forward re end t)
  6493. (unless (get-char-property (match-end 1) 'invisible)
  6494. (let ((e (match-end 1))
  6495. (b (if (>= org-cycle-separator-lines 0)
  6496. (match-beginning 1)
  6497. (save-excursion
  6498. (goto-char (match-beginning 0))
  6499. (skip-chars-backward " \t\n")
  6500. (line-end-position)))))
  6501. (outline-flag-region b e nil))))))))
  6502. ;; Never hide empty lines at the end of the file.
  6503. (save-excursion
  6504. (goto-char (point-max))
  6505. (outline-previous-heading)
  6506. (outline-end-of-heading)
  6507. (when (and (looking-at "[ \t\n]+")
  6508. (= (match-end 0) (point-max)))
  6509. (outline-flag-region (point) (match-end 0) nil))))
  6510. (defun org-show-empty-lines-in-parent ()
  6511. "Move to the parent and re-show empty lines before visible headlines."
  6512. (save-excursion
  6513. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6514. (org-cycle-show-empty-lines context))))
  6515. (defun org-files-list ()
  6516. "Return `org-agenda-files' list, plus all open org-mode files.
  6517. This is useful for operations that need to scan all of a user's
  6518. open and agenda-wise Org files."
  6519. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6520. (dolist (buf (buffer-list))
  6521. (with-current-buffer buf
  6522. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6523. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6524. files))
  6525. (defsubst org-entry-beginning-position ()
  6526. "Return the beginning position of the current entry."
  6527. (save-excursion (org-back-to-heading t) (point)))
  6528. (defsubst org-entry-end-position ()
  6529. "Return the end position of the current entry."
  6530. (save-excursion (outline-next-heading) (point)))
  6531. (defun org-cycle-hide-drawers (state &optional exceptions)
  6532. "Re-hide all drawers after a visibility state change.
  6533. When non-nil, optional argument EXCEPTIONS is a list of strings
  6534. specifying which drawers should not be hidden."
  6535. (when (and (derived-mode-p 'org-mode)
  6536. (not (memq state '(overview folded contents))))
  6537. (save-excursion
  6538. (let* ((globalp (memq state '(contents all)))
  6539. (beg (if globalp (point-min) (point)))
  6540. (end (if globalp (point-max)
  6541. (if (eq state 'children)
  6542. (save-excursion (outline-next-heading) (point))
  6543. (org-end-of-subtree t)))))
  6544. (goto-char beg)
  6545. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6546. (unless (member-ignore-case (match-string 1) exceptions)
  6547. (let ((drawer (org-element-at-point)))
  6548. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6549. (org-flag-drawer t drawer)
  6550. ;; Make sure to skip drawer entirely or we might flag
  6551. ;; it another time when matching its ending line with
  6552. ;; `org-drawer-regexp'.
  6553. (goto-char (org-element-property :end drawer))))))))))
  6554. (defun org-flag-drawer (flag &optional element)
  6555. "When FLAG is non-nil, hide the drawer we are at.
  6556. Otherwise make it visible. When optional argument ELEMENT is
  6557. a parsed drawer, as returned by `org-element-at-point', hide or
  6558. show that drawer instead."
  6559. (let ((drawer (or element
  6560. (and (save-excursion
  6561. (beginning-of-line)
  6562. (looking-at-p org-drawer-regexp))
  6563. (org-element-at-point)))))
  6564. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6565. (let ((post (org-element-property :post-affiliated drawer)))
  6566. (save-excursion
  6567. (outline-flag-region
  6568. (progn (goto-char post) (line-end-position))
  6569. (progn (goto-char (org-element-property :end drawer))
  6570. (skip-chars-backward " \r\t\n")
  6571. (line-end-position))
  6572. flag))
  6573. ;; When the drawer is hidden away, make sure point lies in
  6574. ;; a visible part of the buffer.
  6575. (when (and flag (> (line-beginning-position) post))
  6576. (goto-char post))))))
  6577. (defun org-subtree-end-visible-p ()
  6578. "Is the end of the current subtree visible?"
  6579. (pos-visible-in-window-p
  6580. (save-excursion (org-end-of-subtree t) (point))))
  6581. (defun org-first-headline-recenter ()
  6582. "Move cursor to the first headline and recenter the headline."
  6583. (let ((window (get-buffer-window)))
  6584. (when window
  6585. (goto-char (point-min))
  6586. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6587. (set-window-start window (line-beginning-position))))))
  6588. ;;; Saving and restoring visibility
  6589. (defun org-outline-overlay-data (&optional use-markers)
  6590. "Return a list of the locations of all outline overlays.
  6591. These are overlays with the `invisible' property value `outline'.
  6592. The return value is a list of cons cells, with start and stop
  6593. positions for each overlay.
  6594. If USE-MARKERS is set, return the positions as markers."
  6595. (let (beg end)
  6596. (save-excursion
  6597. (save-restriction
  6598. (widen)
  6599. (delq nil
  6600. (mapcar (lambda (o)
  6601. (when (eq (overlay-get o 'invisible) 'outline)
  6602. (setq beg (overlay-start o)
  6603. end (overlay-end o))
  6604. (and beg end (> end beg)
  6605. (if use-markers
  6606. (cons (copy-marker beg)
  6607. (copy-marker end t))
  6608. (cons beg end)))))
  6609. (overlays-in (point-min) (point-max))))))))
  6610. (defun org-set-outline-overlay-data (data)
  6611. "Create visibility overlays for all positions in DATA.
  6612. DATA should have been made by `org-outline-overlay-data'."
  6613. (org-with-wide-buffer
  6614. (outline-show-all)
  6615. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6616. ;;; Folding of blocks
  6617. (defvar-local org-hide-block-overlays nil
  6618. "Overlays hiding blocks.")
  6619. (defun org-block-map (function &optional start end)
  6620. "Call FUNCTION at the head of all source blocks in the current buffer.
  6621. Optional arguments START and END can be used to limit the range."
  6622. (let ((start (or start (point-min)))
  6623. (end (or end (point-max))))
  6624. (save-excursion
  6625. (goto-char start)
  6626. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6627. (save-excursion
  6628. (save-match-data
  6629. (goto-char (match-beginning 0))
  6630. (funcall function)))))))
  6631. (defun org-hide-block-toggle-all ()
  6632. "Toggle the visibility of all blocks in the current buffer."
  6633. (org-block-map 'org-hide-block-toggle))
  6634. (defun org-hide-block-all ()
  6635. "Fold all blocks in the current buffer."
  6636. (interactive)
  6637. (org-show-block-all)
  6638. (org-block-map 'org-hide-block-toggle-maybe))
  6639. (defun org-show-block-all ()
  6640. "Unfold all blocks in the current buffer."
  6641. (interactive)
  6642. (mapc #'delete-overlay org-hide-block-overlays)
  6643. (setq org-hide-block-overlays nil))
  6644. (defun org-hide-block-toggle-maybe ()
  6645. "Toggle visibility of block at point.
  6646. Unlike to `org-hide-block-toggle', this function does not throw
  6647. an error. Return a non-nil value when toggling is successful."
  6648. (interactive)
  6649. (ignore-errors (org-hide-block-toggle)))
  6650. (defun org-hide-block-toggle (&optional force)
  6651. "Toggle the visibility of the current block.
  6652. When optional argument FORCE is `off', make block visible. If it
  6653. is non-nil, hide it unconditionally. Throw an error when not at
  6654. a block. Return a non-nil value when toggling is successful."
  6655. (interactive)
  6656. (let ((element (org-element-at-point)))
  6657. (unless (memq (org-element-type element)
  6658. '(center-block comment-block dynamic-block example-block
  6659. export-block quote-block special-block
  6660. src-block verse-block))
  6661. (user-error "Not at a block"))
  6662. (let* ((start (save-excursion
  6663. (goto-char (org-element-property :post-affiliated element))
  6664. (line-end-position)))
  6665. (end (save-excursion
  6666. (goto-char (org-element-property :end element))
  6667. (skip-chars-backward " \r\t\n")
  6668. (line-end-position)))
  6669. (overlays (overlays-at start)))
  6670. (cond
  6671. ;; Do nothing when not before or at the block opening line or
  6672. ;; at the block closing line.
  6673. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6674. ((and (not (eq force 'off))
  6675. (not (memq t (mapcar
  6676. (lambda (o)
  6677. (eq (overlay-get o 'invisible) 'org-hide-block))
  6678. overlays))))
  6679. (let ((ov (make-overlay start end)))
  6680. (overlay-put ov 'invisible 'org-hide-block)
  6681. ;; Make the block accessible to `isearch'.
  6682. (overlay-put
  6683. ov 'isearch-open-invisible
  6684. (lambda (ov)
  6685. (when (memq ov org-hide-block-overlays)
  6686. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6687. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6688. (delete-overlay ov))))
  6689. (push ov org-hide-block-overlays)
  6690. ;; When the block is hidden away, make sure point is left in
  6691. ;; a visible part of the buffer.
  6692. (when (> (line-beginning-position) start)
  6693. (goto-char start)
  6694. (beginning-of-line))
  6695. ;; Signal successful toggling.
  6696. t))
  6697. ((or (not force) (eq force 'off))
  6698. (dolist (ov overlays t)
  6699. (when (memq ov org-hide-block-overlays)
  6700. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6701. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6702. (delete-overlay ov))))))))
  6703. ;; org-tab-after-check-for-cycling-hook
  6704. (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
  6705. ;; Remove overlays when changing major mode
  6706. (add-hook 'org-mode-hook
  6707. (lambda () (add-hook 'change-major-mode-hook
  6708. 'org-show-block-all 'append 'local)))
  6709. ;;; Org-goto
  6710. (defvar org-goto-window-configuration nil)
  6711. (defvar org-goto-marker nil)
  6712. (defvar org-goto-map)
  6713. (defun org-goto-map ()
  6714. "Set the keymap `org-goto'."
  6715. (setq org-goto-map
  6716. (let ((map (make-sparse-keymap)))
  6717. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6718. mouse-drag-region universal-argument org-occur)))
  6719. (dolist (cmd cmds)
  6720. (substitute-key-definition cmd cmd map global-map)))
  6721. (suppress-keymap map)
  6722. (org-defkey map "\C-m" 'org-goto-ret)
  6723. (org-defkey map [(return)] 'org-goto-ret)
  6724. (org-defkey map [(left)] 'org-goto-left)
  6725. (org-defkey map [(right)] 'org-goto-right)
  6726. (org-defkey map [(control ?g)] 'org-goto-quit)
  6727. (org-defkey map "\C-i" 'org-cycle)
  6728. (org-defkey map [(tab)] 'org-cycle)
  6729. (org-defkey map [(down)] 'outline-next-visible-heading)
  6730. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6731. (if org-goto-auto-isearch
  6732. (if (fboundp 'define-key-after)
  6733. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6734. nil)
  6735. (org-defkey map "q" 'org-goto-quit)
  6736. (org-defkey map "n" 'outline-next-visible-heading)
  6737. (org-defkey map "p" 'outline-previous-visible-heading)
  6738. (org-defkey map "f" 'outline-forward-same-level)
  6739. (org-defkey map "b" 'outline-backward-same-level)
  6740. (org-defkey map "u" 'outline-up-heading))
  6741. (org-defkey map "/" 'org-occur)
  6742. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6743. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6744. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6745. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6746. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6747. map)))
  6748. (defconst org-goto-help
  6749. "Browse buffer copy, to find location or copy text.%s
  6750. RET=jump to location C-g=quit and return to previous location
  6751. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6752. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6753. (defun org-goto (&optional alternative-interface)
  6754. "Look up a different location in the current file, keeping current visibility.
  6755. When you want look-up or go to a different location in a
  6756. document, the fastest way is often to fold the entire buffer and
  6757. then dive into the tree. This method has the disadvantage, that
  6758. the previous location will be folded, which may not be what you
  6759. want.
  6760. This command works around this by showing a copy of the current
  6761. buffer in an indirect buffer, in overview mode. You can dive
  6762. into the tree in that copy, use org-occur and incremental search
  6763. to find a location. When pressing RET or `Q', the command
  6764. returns to the original buffer in which the visibility is still
  6765. unchanged. After RET it will also jump to the location selected
  6766. in the indirect buffer and expose the headline hierarchy above.
  6767. With a prefix argument, use the alternative interface: e.g., if
  6768. `org-goto-interface' is `outline' use `outline-path-completion'."
  6769. (interactive "P")
  6770. (org-goto-map)
  6771. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6772. (org-refile-use-outline-path t)
  6773. (org-refile-target-verify-function nil)
  6774. (interface
  6775. (if (not alternative-interface)
  6776. org-goto-interface
  6777. (if (eq org-goto-interface 'outline)
  6778. 'outline-path-completion
  6779. 'outline)))
  6780. (org-goto-start-pos (point))
  6781. (selected-point
  6782. (if (eq interface 'outline)
  6783. (car (org-get-location (current-buffer) org-goto-help))
  6784. (let ((pa (org-refile-get-location "Goto")))
  6785. (org-refile-check-position pa)
  6786. (nth 3 pa)))))
  6787. (if selected-point
  6788. (progn
  6789. (org-mark-ring-push org-goto-start-pos)
  6790. (goto-char selected-point)
  6791. (when (or (outline-invisible-p) (org-invisible-p2))
  6792. (org-show-context 'org-goto)))
  6793. (message "Quit"))))
  6794. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6795. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6796. (defvar org-goto-local-auto-isearch-map) ; defined below
  6797. (defun org-get-location (_buf help)
  6798. "Let the user select a location in current buffer.
  6799. This function uses a recursive edit. It returns the selected position
  6800. or nil."
  6801. (org-no-popups
  6802. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6803. (isearch-hide-immediately nil)
  6804. (isearch-search-fun-function
  6805. (lambda () 'org-goto-local-search-headings))
  6806. (org-goto-selected-point org-goto-exit-command))
  6807. (save-excursion
  6808. (save-window-excursion
  6809. (delete-other-windows)
  6810. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6811. (pop-to-buffer-same-window
  6812. (condition-case nil
  6813. (make-indirect-buffer (current-buffer) "*org-goto*")
  6814. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6815. (with-output-to-temp-buffer "*Org Help*"
  6816. (princ (format help (if org-goto-auto-isearch
  6817. " Just type for auto-isearch."
  6818. " n/p/f/b/u to navigate, q to quit."))))
  6819. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6820. (setq buffer-read-only nil)
  6821. (let ((org-startup-truncated t)
  6822. (org-startup-folded nil)
  6823. (org-startup-align-all-tables nil))
  6824. (org-mode)
  6825. (org-overview))
  6826. (setq buffer-read-only t)
  6827. (if (and (boundp 'org-goto-start-pos)
  6828. (integer-or-marker-p org-goto-start-pos))
  6829. (progn (goto-char org-goto-start-pos)
  6830. (when (outline-invisible-p)
  6831. (org-show-set-visibility 'lineage)))
  6832. (goto-char (point-min)))
  6833. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6834. (message "Select location and press RET")
  6835. (use-local-map org-goto-map)
  6836. (recursive-edit)))
  6837. (kill-buffer "*org-goto*")
  6838. (cons org-goto-selected-point org-goto-exit-command))))
  6839. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6840. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6841. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6842. (if (fboundp 'isearch-other-control-char)
  6843. (progn
  6844. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6845. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6846. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6847. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6848. (define-key org-goto-local-auto-isearch-map [return] nil))
  6849. (defun org-goto-local-search-headings (string bound noerror)
  6850. "Search and make sure that any matches are in headlines."
  6851. (catch 'return
  6852. (while (if isearch-forward
  6853. (search-forward string bound noerror)
  6854. (search-backward string bound noerror))
  6855. (when (save-match-data
  6856. (and (save-excursion
  6857. (beginning-of-line)
  6858. (looking-at org-complex-heading-regexp))
  6859. (or (not (match-beginning 5))
  6860. (< (point) (match-beginning 5)))))
  6861. (throw 'return (point))))))
  6862. (defun org-goto-local-auto-isearch ()
  6863. "Start isearch."
  6864. (interactive)
  6865. (goto-char (point-min))
  6866. (let ((keys (this-command-keys)))
  6867. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6868. (isearch-mode t)
  6869. (isearch-process-search-char (string-to-char keys)))))
  6870. (defun org-goto-ret (&optional _arg)
  6871. "Finish `org-goto' by going to the new location."
  6872. (interactive "P")
  6873. (setq org-goto-selected-point (point))
  6874. (setq org-goto-exit-command 'return)
  6875. (throw 'exit nil))
  6876. (defun org-goto-left ()
  6877. "Finish `org-goto' by going to the new location."
  6878. (interactive)
  6879. (if (org-at-heading-p)
  6880. (progn
  6881. (beginning-of-line 1)
  6882. (setq org-goto-selected-point (point)
  6883. org-goto-exit-command 'left)
  6884. (throw 'exit nil))
  6885. (user-error "Not on a heading")))
  6886. (defun org-goto-right ()
  6887. "Finish `org-goto' by going to the new location."
  6888. (interactive)
  6889. (if (org-at-heading-p)
  6890. (progn
  6891. (setq org-goto-selected-point (point)
  6892. org-goto-exit-command 'right)
  6893. (throw 'exit nil))
  6894. (user-error "Not on a heading")))
  6895. (defun org-goto-quit ()
  6896. "Finish `org-goto' without cursor motion."
  6897. (interactive)
  6898. (setq org-goto-selected-point nil)
  6899. (setq org-goto-exit-command 'quit)
  6900. (throw 'exit nil))
  6901. ;;; Indirect buffer display of subtrees
  6902. (defvar org-indirect-dedicated-frame nil
  6903. "This is the frame being used for indirect tree display.")
  6904. (defvar org-last-indirect-buffer nil)
  6905. (defun org-tree-to-indirect-buffer (&optional arg)
  6906. "Create indirect buffer and narrow it to current subtree.
  6907. With a numerical prefix ARG, go up to this level and then take that tree.
  6908. If ARG is negative, go up that many levels.
  6909. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6910. indirect buffer previously made with this command, to avoid proliferation of
  6911. indirect buffers. However, when you call the command with a \
  6912. \\[universal-argument] prefix, or
  6913. when `org-indirect-buffer-display' is `new-frame', the last buffer
  6914. is kept so that you can work with several indirect buffers at the same time.
  6915. If `org-indirect-buffer-display' is `dedicated-frame', the \
  6916. \\[universal-argument] prefix also
  6917. requests that a new frame be made for the new buffer, so that the dedicated
  6918. frame is not changed."
  6919. (interactive "P")
  6920. (let ((cbuf (current-buffer))
  6921. (cwin (selected-window))
  6922. (pos (point))
  6923. beg end level heading ibuf)
  6924. (save-excursion
  6925. (org-back-to-heading t)
  6926. (when (numberp arg)
  6927. (setq level (org-outline-level))
  6928. (when (< arg 0) (setq arg (+ level arg)))
  6929. (while (> (setq level (org-outline-level)) arg)
  6930. (org-up-heading-safe)))
  6931. (setq beg (point)
  6932. heading (org-get-heading 'no-tags))
  6933. (org-end-of-subtree t t)
  6934. (when (org-at-heading-p) (backward-char 1))
  6935. (setq end (point)))
  6936. (when (and (buffer-live-p org-last-indirect-buffer)
  6937. (not (eq org-indirect-buffer-display 'new-frame))
  6938. (not arg))
  6939. (kill-buffer org-last-indirect-buffer))
  6940. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6941. org-last-indirect-buffer ibuf)
  6942. (cond
  6943. ((or (eq org-indirect-buffer-display 'new-frame)
  6944. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6945. (select-frame (make-frame))
  6946. (delete-other-windows)
  6947. (pop-to-buffer-same-window ibuf)
  6948. (org-set-frame-title heading))
  6949. ((eq org-indirect-buffer-display 'dedicated-frame)
  6950. (raise-frame
  6951. (select-frame (or (and org-indirect-dedicated-frame
  6952. (frame-live-p org-indirect-dedicated-frame)
  6953. org-indirect-dedicated-frame)
  6954. (setq org-indirect-dedicated-frame (make-frame)))))
  6955. (delete-other-windows)
  6956. (pop-to-buffer-same-window ibuf)
  6957. (org-set-frame-title (concat "Indirect: " heading)))
  6958. ((eq org-indirect-buffer-display 'current-window)
  6959. (pop-to-buffer-same-window ibuf))
  6960. ((eq org-indirect-buffer-display 'other-window)
  6961. (pop-to-buffer ibuf))
  6962. (t (error "Invalid value")))
  6963. (narrow-to-region beg end)
  6964. (outline-show-all)
  6965. (goto-char pos)
  6966. (run-hook-with-args 'org-cycle-hook 'all)
  6967. (and (window-live-p cwin) (select-window cwin))))
  6968. (defun org-get-indirect-buffer (&optional buffer heading)
  6969. (setq buffer (or buffer (current-buffer)))
  6970. (let ((n 1) (base (buffer-name buffer)) bname)
  6971. (while (buffer-live-p
  6972. (get-buffer
  6973. (setq bname
  6974. (concat base "-"
  6975. (if heading (concat heading "-" (number-to-string n))
  6976. (number-to-string n))))))
  6977. (setq n (1+ n)))
  6978. (condition-case nil
  6979. (make-indirect-buffer buffer bname 'clone)
  6980. (error (make-indirect-buffer buffer bname)))))
  6981. (defun org-set-frame-title (title)
  6982. "Set the title of the current frame to the string TITLE."
  6983. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6984. ;;;; Structure editing
  6985. ;;; Inserting headlines
  6986. (defun org--line-empty-p (n)
  6987. "Is the Nth next line empty?
  6988. Counts the current line as N = 1 and the previous line as N = 0;
  6989. see `beginning-of-line'."
  6990. (save-excursion
  6991. (and (not (bobp))
  6992. (or (beginning-of-line n) t)
  6993. (save-match-data
  6994. (looking-at "[ \t]*$")))))
  6995. (defun org-previous-line-empty-p ()
  6996. "Is the previous line a blank line?
  6997. When NEXT is non-nil, check the next line instead."
  6998. (org--line-empty-p 0))
  6999. (defun org-next-line-empty-p ()
  7000. "Is the previous line a blank line?
  7001. When NEXT is non-nil, check the next line instead."
  7002. (org--line-empty-p 2))
  7003. (defun org-insert-heading (&optional arg invisible-ok top)
  7004. "Insert a new heading or an item with the same depth at point.
  7005. If point is at the beginning of a heading or a list item, insert
  7006. a new heading or a new item above the current one. If point is
  7007. at the beginning of a normal line, turn the line into a heading.
  7008. If point is in the middle of a headline or a list item, split the
  7009. headline or the item and create a new headline/item with the text
  7010. in the current line after point \(see `org-M-RET-may-split-line'
  7011. on how to modify this behavior).
  7012. With one universal prefix argument, set the user option
  7013. `org-insert-heading-respect-content' to t for the duration of
  7014. the command. This modifies the behavior described above in this
  7015. ways: on list items and at the beginning of normal lines, force
  7016. the insertion of a heading after the current subtree.
  7017. With two universal prefix arguments, insert the heading at the
  7018. end of the grandparent subtree. For example, if point is within
  7019. a 2nd-level heading, then it will insert a 2nd-level heading at
  7020. the end of the 1st-level parent heading.
  7021. If point is at the beginning of a headline, insert a sibling
  7022. before the current headline. If point is not at the beginning,
  7023. split the line and create a new headline with the text in the
  7024. current line after point \(see `org-M-RET-may-split-line' on how
  7025. to modify this behavior).
  7026. If point is at the beginning of a normal line, turn this line
  7027. into a heading.
  7028. When INVISIBLE-OK is set, stop at invisible headlines when going
  7029. back. This is important for non-interactive uses of the
  7030. command.
  7031. When optional argument TOP is non-nil, insert a level 1 heading,
  7032. unconditionally."
  7033. (interactive "P")
  7034. (let ((itemp (and (not top) (org-in-item-p)))
  7035. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7036. (respect-content (or org-insert-heading-respect-content
  7037. (equal arg '(4))))
  7038. (initial-content ""))
  7039. (cond
  7040. ((or (= (buffer-size) 0)
  7041. (and (not (save-excursion
  7042. (and (ignore-errors (org-back-to-heading invisible-ok))
  7043. (org-at-heading-p))))
  7044. (or arg (not itemp))))
  7045. ;; At beginning of buffer or so high up that only a heading
  7046. ;; makes sense.
  7047. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7048. ((not respect-content)
  7049. (unless may-split (end-of-line))
  7050. (insert "\n* "))
  7051. ((re-search-forward org-outline-regexp-bol nil t)
  7052. (beginning-of-line)
  7053. (insert "* \n")
  7054. (backward-char))
  7055. (t (goto-char (point-max))
  7056. (insert "\n* ")))
  7057. (run-hooks 'org-insert-heading-hook))
  7058. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7059. (t
  7060. ;; Maybe move at the end of the subtree
  7061. (when (equal arg '(16))
  7062. (org-up-heading-safe)
  7063. (org-end-of-subtree t))
  7064. ;; Insert a heading
  7065. (save-restriction
  7066. (widen)
  7067. (let* ((level nil)
  7068. (on-heading (org-at-heading-p))
  7069. (empty-line-p (if on-heading
  7070. (org-previous-line-empty-p)
  7071. ;; We will decide later
  7072. nil))
  7073. ;; Get a level string to fall back on.
  7074. (fix-level
  7075. (if (org-before-first-heading-p) "*"
  7076. (save-excursion
  7077. (org-back-to-heading t)
  7078. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7079. (looking-at org-outline-regexp)
  7080. (make-string (1- (length (match-string 0))) ?*))))
  7081. (stars
  7082. (save-excursion
  7083. (condition-case nil
  7084. (if top "* "
  7085. (org-back-to-heading invisible-ok)
  7086. (when (and (not on-heading)
  7087. (featurep 'org-inlinetask)
  7088. (integerp org-inlinetask-min-level)
  7089. (>= (length (match-string 0))
  7090. org-inlinetask-min-level))
  7091. ;; Find a heading level before the inline
  7092. ;; task.
  7093. (while (and (setq level (org-up-heading-safe))
  7094. (>= level org-inlinetask-min-level)))
  7095. (if (org-at-heading-p)
  7096. (org-back-to-heading invisible-ok)
  7097. (error "This should not happen")))
  7098. (unless (and (save-excursion
  7099. (save-match-data
  7100. (org-backward-heading-same-level
  7101. 1 invisible-ok))
  7102. (= (point) (match-beginning 0)))
  7103. (not (org-next-line-empty-p)))
  7104. (setq empty-line-p (or empty-line-p
  7105. (org-previous-line-empty-p))))
  7106. (match-string 0))
  7107. (error (or fix-level "* ")))))
  7108. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7109. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7110. ;; If we insert after content, move there and clean up
  7111. ;; whitespace.
  7112. (when (and respect-content
  7113. (not (looking-at-p org-outline-regexp-bol)))
  7114. (if (not (org-before-first-heading-p))
  7115. (org-end-of-subtree nil t)
  7116. (re-search-forward org-outline-regexp-bol)
  7117. (beginning-of-line 0))
  7118. (skip-chars-backward " \r\t\n")
  7119. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7120. (looking-at "[ \t]+") (replace-match ""))
  7121. (unless (eobp) (forward-char 1))
  7122. (when (looking-at "^\\*")
  7123. (unless (bobp) (backward-char 1))
  7124. (insert "\n")))
  7125. ;; If we are splitting, grab the text that should be moved
  7126. ;; to the new headline.
  7127. (when may-split
  7128. (if (org-at-heading-p)
  7129. ;; This is a heading: split intelligently (keeping
  7130. ;; tags).
  7131. (let ((pos (point)))
  7132. (beginning-of-line)
  7133. (unless (looking-at org-complex-heading-regexp)
  7134. (error "This should not happen"))
  7135. (when (and (match-beginning 4)
  7136. (> pos (match-beginning 4))
  7137. (< pos (match-end 4)))
  7138. (setq initial-content (buffer-substring pos (match-end 4)))
  7139. (goto-char pos)
  7140. (delete-region (point) (match-end 4))
  7141. (if (looking-at "[ \t]*$")
  7142. (replace-match "")
  7143. (insert (make-string (length initial-content) ?\s)))
  7144. (setq initial-content (org-trim initial-content)))
  7145. (goto-char pos))
  7146. ;; A normal line.
  7147. (setq initial-content
  7148. (org-trim
  7149. (delete-and-extract-region (point) (line-end-position))))))
  7150. ;; If we are at the beginning of the line, insert before it.
  7151. ;; Otherwise, after it.
  7152. (cond
  7153. ((and (bolp) (looking-at "[ \t]*$")))
  7154. ((bolp) (save-excursion (insert "\n")))
  7155. (t (end-of-line)
  7156. (insert "\n")))
  7157. ;; Insert the new heading
  7158. (insert stars)
  7159. (just-one-space)
  7160. (insert initial-content)
  7161. (unless (and blank (org-previous-line-empty-p))
  7162. (org-N-empty-lines-before-current (if blank 1 0)))
  7163. ;; Adjust visibility, which may be messed up if we removed
  7164. ;; blank lines while previous entry was hidden.
  7165. (let ((bol (line-beginning-position)))
  7166. (dolist (o (overlays-at (1- bol)))
  7167. (when (and (eq (overlay-get o 'invisible) 'outline)
  7168. (eq (overlay-end o) bol))
  7169. (move-overlay o (overlay-start o) (1- bol)))))
  7170. (run-hooks 'org-insert-heading-hook)))))))
  7171. (defun org-N-empty-lines-before-current (N)
  7172. "Make the number of empty lines before current exactly N.
  7173. So this will delete or add empty lines."
  7174. (save-excursion
  7175. (beginning-of-line)
  7176. (let ((p (point)))
  7177. (skip-chars-backward " \r\t\n")
  7178. (unless (bolp) (forward-line))
  7179. (delete-region (point) p))
  7180. (when (> N 0) (insert (make-string N ?\n)))))
  7181. (defun org-get-heading (&optional no-tags no-todo)
  7182. "Return the heading of the current entry, without the stars.
  7183. When NO-TAGS is non-nil, don't include tags.
  7184. When NO-TODO is non-nil, don't include TODO keywords."
  7185. (save-excursion
  7186. (org-back-to-heading t)
  7187. (let ((case-fold-search nil))
  7188. (cond
  7189. ((and no-tags no-todo)
  7190. (looking-at org-complex-heading-regexp)
  7191. (match-string 4))
  7192. (no-tags
  7193. (looking-at (concat org-outline-regexp
  7194. "\\(.*?\\)"
  7195. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7196. (match-string 1))
  7197. (no-todo
  7198. (looking-at org-todo-line-regexp)
  7199. (match-string 3))
  7200. (t (looking-at org-heading-regexp)
  7201. (match-string 2))))))
  7202. (defvar orgstruct-mode) ; defined below
  7203. (defun org-heading-components ()
  7204. "Return the components of the current heading.
  7205. This is a list with the following elements:
  7206. - the level as an integer
  7207. - the reduced level, different if `org-odd-levels-only' is set.
  7208. - the TODO keyword, or nil
  7209. - the priority character, like ?A, or nil if no priority is given
  7210. - the headline text itself, or the tags string if no headline text
  7211. - the tags string, or nil."
  7212. (save-excursion
  7213. (org-back-to-heading t)
  7214. (when (let (case-fold-search)
  7215. (looking-at
  7216. (if orgstruct-mode
  7217. org-heading-regexp
  7218. org-complex-heading-regexp)))
  7219. (if orgstruct-mode
  7220. (list (length (match-string 1))
  7221. (org-reduced-level (length (match-string 1)))
  7222. nil
  7223. nil
  7224. (match-string 2)
  7225. nil)
  7226. (list (length (match-string 1))
  7227. (org-reduced-level (length (match-string 1)))
  7228. (match-string-no-properties 2)
  7229. (and (match-end 3) (aref (match-string 3) 2))
  7230. (match-string-no-properties 4)
  7231. (match-string-no-properties 5))))))
  7232. (defun org-get-entry ()
  7233. "Get the entry text, after heading, entire subtree."
  7234. (save-excursion
  7235. (org-back-to-heading t)
  7236. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7237. (defun org-edit-headline (&optional heading)
  7238. "Edit the current headline.
  7239. Set it to HEADING when provided."
  7240. (interactive)
  7241. (org-with-wide-buffer
  7242. (org-back-to-heading t)
  7243. (when (looking-at org-complex-heading-regexp)
  7244. (let* ((old (match-string-no-properties 4))
  7245. (new (save-match-data
  7246. (org-trim (or heading (read-string "Edit: " old))))))
  7247. (unless (equal old new)
  7248. (if old (replace-match new t t nil 4)
  7249. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7250. (insert " " new))
  7251. (org-set-tags nil t)
  7252. (when (looking-at "[ \t]*$") (replace-match "")))))))
  7253. (defun org-insert-heading-after-current ()
  7254. "Insert a new heading with same level as current, after current subtree."
  7255. (interactive)
  7256. (org-back-to-heading)
  7257. (org-insert-heading)
  7258. (org-move-subtree-down)
  7259. (end-of-line 1))
  7260. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7261. "Insert heading with `org-insert-heading-respect-content' set to t."
  7262. (interactive)
  7263. (org-insert-heading '(4) invisible-ok))
  7264. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7265. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7266. (interactive)
  7267. (org-insert-todo-heading force-state '(4)))
  7268. (defun org-insert-todo-heading (arg &optional force-heading)
  7269. "Insert a new heading with the same level and TODO state as current heading.
  7270. If the heading has no TODO state, or if the state is DONE, use the first
  7271. state (TODO by default). Also with one prefix arg, force first state. With
  7272. two prefix args, force inserting at the end of the parent subtree."
  7273. (interactive "P")
  7274. (when (or force-heading (not (org-insert-item 'checkbox)))
  7275. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7276. force-heading))
  7277. (save-excursion
  7278. (org-back-to-heading)
  7279. (outline-previous-heading)
  7280. (looking-at org-todo-line-regexp))
  7281. (let*
  7282. ((new-mark-x
  7283. (if (or (equal arg '(4))
  7284. (not (match-beginning 2))
  7285. (member (match-string 2) org-done-keywords))
  7286. (car org-todo-keywords-1)
  7287. (match-string 2)))
  7288. (new-mark
  7289. (or
  7290. (run-hook-with-args-until-success
  7291. 'org-todo-get-default-hook new-mark-x nil)
  7292. new-mark-x)))
  7293. (beginning-of-line 1)
  7294. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7295. (if org-treat-insert-todo-heading-as-state-change
  7296. (org-todo new-mark)
  7297. (insert new-mark " "))))
  7298. (when org-provide-todo-statistics
  7299. (org-update-parent-todo-statistics))))
  7300. (defun org-insert-subheading (arg)
  7301. "Insert a new subheading and demote it.
  7302. Works for outline headings and for plain lists alike."
  7303. (interactive "P")
  7304. (org-insert-heading arg)
  7305. (cond
  7306. ((org-at-heading-p) (org-do-demote))
  7307. ((org-at-item-p) (org-indent-item))))
  7308. (defun org-insert-todo-subheading (arg)
  7309. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7310. Works for outline headings and for plain lists alike."
  7311. (interactive "P")
  7312. (org-insert-todo-heading arg)
  7313. (cond
  7314. ((org-at-heading-p) (org-do-demote))
  7315. ((org-at-item-p) (org-indent-item))))
  7316. ;;; Promotion and Demotion
  7317. (defvar org-after-demote-entry-hook nil
  7318. "Hook run after an entry has been demoted.
  7319. The cursor will be at the beginning of the entry.
  7320. When a subtree is being demoted, the hook will be called for each node.")
  7321. (defvar org-after-promote-entry-hook nil
  7322. "Hook run after an entry has been promoted.
  7323. The cursor will be at the beginning of the entry.
  7324. When a subtree is being promoted, the hook will be called for each node.")
  7325. (defun org-promote-subtree ()
  7326. "Promote the entire subtree.
  7327. See also `org-promote'."
  7328. (interactive)
  7329. (save-excursion
  7330. (org-with-limited-levels (org-map-tree 'org-promote)))
  7331. (org-fix-position-after-promote))
  7332. (defun org-demote-subtree ()
  7333. "Demote the entire subtree.
  7334. See `org-demote' and `org-promote'."
  7335. (interactive)
  7336. (save-excursion
  7337. (org-with-limited-levels (org-map-tree 'org-demote)))
  7338. (org-fix-position-after-promote))
  7339. (defun org-do-promote ()
  7340. "Promote the current heading higher up the tree.
  7341. If the region is active in `transient-mark-mode', promote all
  7342. headings in the region."
  7343. (interactive)
  7344. (save-excursion
  7345. (if (org-region-active-p)
  7346. (org-map-region 'org-promote (region-beginning) (region-end))
  7347. (org-promote)))
  7348. (org-fix-position-after-promote))
  7349. (defun org-do-demote ()
  7350. "Demote the current heading lower down the tree.
  7351. If the region is active in `transient-mark-mode', demote all
  7352. headings in the region."
  7353. (interactive)
  7354. (save-excursion
  7355. (if (org-region-active-p)
  7356. (org-map-region 'org-demote (region-beginning) (region-end))
  7357. (org-demote)))
  7358. (org-fix-position-after-promote))
  7359. (defun org-fix-position-after-promote ()
  7360. "Fix cursor position and indentation after demoting/promoting."
  7361. (let ((pos (point)))
  7362. (when (save-excursion
  7363. (beginning-of-line 1)
  7364. (looking-at org-todo-line-regexp)
  7365. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7366. (cond ((eobp) (insert " "))
  7367. ((eolp) (insert " "))
  7368. ((equal (char-after) ?\ ) (forward-char 1))))))
  7369. (defun org-current-level ()
  7370. "Return the level of the current entry, or nil if before the first headline.
  7371. The level is the number of stars at the beginning of the
  7372. headline. Use `org-reduced-level' to remove the effect of
  7373. `org-odd-levels'. Unlike to `org-outline-level', this function
  7374. ignores inlinetasks."
  7375. (let ((level (org-with-limited-levels (org-outline-level))))
  7376. (and (> level 0) level)))
  7377. (defun org-get-previous-line-level ()
  7378. "Return the outline depth of the last headline before the current line.
  7379. Returns 0 for the first headline in the buffer, and nil if before the
  7380. first headline."
  7381. (and (org-current-level)
  7382. (or (and (/= (line-beginning-position) (point-min))
  7383. (save-excursion (beginning-of-line 0) (org-current-level)))
  7384. 0)))
  7385. (defun org-reduced-level (l)
  7386. "Compute the effective level of a heading.
  7387. This takes into account the setting of `org-odd-levels-only'."
  7388. (cond
  7389. ((zerop l) 0)
  7390. (org-odd-levels-only (1+ (floor (/ l 2))))
  7391. (t l)))
  7392. (defun org-level-increment ()
  7393. "Return the number of stars that will be added or removed at a
  7394. time to headlines when structure editing, based on the value of
  7395. `org-odd-levels-only'."
  7396. (if org-odd-levels-only 2 1))
  7397. (defun org-get-valid-level (level &optional change)
  7398. "Rectify a level change under the influence of `org-odd-levels-only'
  7399. LEVEL is a current level, CHANGE is by how much the level should be
  7400. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7401. even level numbers will become the next higher odd number."
  7402. (if org-odd-levels-only
  7403. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7404. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7405. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7406. (max 1 (+ level (or change 0)))))
  7407. (defun org-promote ()
  7408. "Promote the current heading higher up the tree."
  7409. (org-with-wide-buffer
  7410. (org-back-to-heading t)
  7411. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7412. after-change-functions))
  7413. (level (save-match-data (funcall outline-level)))
  7414. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7415. (diff (abs (- level (length up-head) -1))))
  7416. (cond
  7417. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7418. (replace-match "# " nil t))
  7419. ((= level 1)
  7420. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7421. (t (replace-match up-head nil t)))
  7422. (unless (= level 1)
  7423. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7424. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7425. (run-hooks 'org-after-promote-entry-hook))))
  7426. (defun org-demote ()
  7427. "Demote the current heading lower down the tree."
  7428. (org-with-wide-buffer
  7429. (org-back-to-heading t)
  7430. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7431. after-change-functions))
  7432. (level (save-match-data (funcall outline-level)))
  7433. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7434. (diff (abs (- level (length down-head) -1))))
  7435. (replace-match down-head nil t)
  7436. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7437. (when org-adapt-indentation (org-fixup-indentation diff))
  7438. (run-hooks 'org-after-demote-entry-hook))))
  7439. (defun org-cycle-level ()
  7440. "Cycle the level of an empty headline through possible states.
  7441. This goes first to child, then to parent, level, then up the hierarchy.
  7442. After top level, it switches back to sibling level."
  7443. (interactive)
  7444. (let ((org-adapt-indentation nil))
  7445. (when (org-point-at-end-of-empty-headline)
  7446. (setq this-command 'org-cycle-level) ; Only needed for caching
  7447. (let ((cur-level (org-current-level))
  7448. (prev-level (org-get-previous-line-level)))
  7449. (cond
  7450. ;; If first headline in file, promote to top-level.
  7451. ((= prev-level 0)
  7452. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7453. do (org-do-promote)))
  7454. ;; If same level as prev, demote one.
  7455. ((= prev-level cur-level)
  7456. (org-do-demote))
  7457. ;; If parent is top-level, promote to top level if not already.
  7458. ((= prev-level 1)
  7459. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7460. do (org-do-promote)))
  7461. ;; If top-level, return to prev-level.
  7462. ((= cur-level 1)
  7463. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7464. do (org-do-demote)))
  7465. ;; If less than prev-level, promote one.
  7466. ((< cur-level prev-level)
  7467. (org-do-promote))
  7468. ;; If deeper than prev-level, promote until higher than
  7469. ;; prev-level.
  7470. ((> cur-level prev-level)
  7471. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7472. do (org-do-promote))))
  7473. t))))
  7474. (defun org-map-tree (fun)
  7475. "Call FUN for every heading underneath the current one."
  7476. (org-back-to-heading)
  7477. (let ((level (funcall outline-level)))
  7478. (save-excursion
  7479. (funcall fun)
  7480. (while (and (progn
  7481. (outline-next-heading)
  7482. (> (funcall outline-level) level))
  7483. (not (eobp)))
  7484. (funcall fun)))))
  7485. (defun org-map-region (fun beg end)
  7486. "Call FUN for every heading between BEG and END."
  7487. (let ((org-ignore-region t))
  7488. (save-excursion
  7489. (setq end (copy-marker end))
  7490. (goto-char beg)
  7491. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7492. (< (point) end))
  7493. (funcall fun))
  7494. (while (and (progn
  7495. (outline-next-heading)
  7496. (< (point) end))
  7497. (not (eobp)))
  7498. (funcall fun)))))
  7499. (defun org-fixup-indentation (diff)
  7500. "Change the indentation in the current entry by DIFF.
  7501. DIFF is an integer. Indentation is done according to the
  7502. following rules:
  7503. - Planning information and property drawers are always indented
  7504. according to the new level of the headline;
  7505. - Footnote definitions and their contents are ignored;
  7506. - Inlinetasks' boundaries are not shifted;
  7507. - Empty lines are ignored;
  7508. - Other lines' indentation are shifted by DIFF columns, unless
  7509. it would introduce a structural change in the document, in
  7510. which case no shifting is done at all.
  7511. Assume point is at a heading or an inlinetask beginning."
  7512. (org-with-wide-buffer
  7513. (narrow-to-region (line-beginning-position)
  7514. (save-excursion
  7515. (if (org-with-limited-levels (org-at-heading-p))
  7516. (org-with-limited-levels (outline-next-heading))
  7517. (org-inlinetask-goto-end))
  7518. (point)))
  7519. (forward-line)
  7520. ;; Indent properly planning info and property drawer.
  7521. (when (looking-at-p org-planning-line-re)
  7522. (org-indent-line)
  7523. (forward-line))
  7524. (when (looking-at org-property-drawer-re)
  7525. (goto-char (match-end 0))
  7526. (forward-line)
  7527. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7528. (catch 'no-shift
  7529. (when (zerop diff) (throw 'no-shift nil))
  7530. ;; If DIFF is negative, first check if a shift is possible at all
  7531. ;; (e.g., it doesn't break structure). This can only happen if
  7532. ;; some contents are not properly indented.
  7533. (let ((case-fold-search t))
  7534. (when (< diff 0)
  7535. (let ((diff (- diff))
  7536. (forbidden-re (concat org-outline-regexp
  7537. "\\|"
  7538. (substring org-footnote-definition-re 1))))
  7539. (save-excursion
  7540. (while (not (eobp))
  7541. (cond
  7542. ((looking-at-p "[ \t]*$") (forward-line))
  7543. ((and (looking-at-p org-footnote-definition-re)
  7544. (let ((e (org-element-at-point)))
  7545. (and (eq (org-element-type e) 'footnote-definition)
  7546. (goto-char (org-element-property :end e))))))
  7547. ((looking-at-p org-outline-regexp) (forward-line))
  7548. ;; Give up if shifting would move before column 0 or
  7549. ;; if it would introduce a headline or a footnote
  7550. ;; definition.
  7551. (t
  7552. (skip-chars-forward " \t")
  7553. (let ((ind (current-column)))
  7554. (when (or (< ind diff)
  7555. (and (= ind diff) (looking-at-p forbidden-re)))
  7556. (throw 'no-shift nil)))
  7557. ;; Ignore contents of example blocks and source
  7558. ;; blocks if their indentation is meant to be
  7559. ;; preserved. Jump to block's closing line.
  7560. (beginning-of-line)
  7561. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7562. (let ((e (org-element-at-point)))
  7563. (and (memq (org-element-type e)
  7564. '(example-block src-block))
  7565. (or org-src-preserve-indentation
  7566. (org-element-property :preserve-indent e))
  7567. (goto-char (org-element-property :end e))
  7568. (progn (skip-chars-backward " \r\t\n")
  7569. (beginning-of-line)
  7570. t))))
  7571. (forward-line))))))))
  7572. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7573. ;; by DIFF. Also skip contents of source or example blocks
  7574. ;; when indentation is meant to be preserved.
  7575. (while (not (eobp))
  7576. (cond
  7577. ((and (looking-at-p org-footnote-definition-re)
  7578. (let ((e (org-element-at-point)))
  7579. (and (eq (org-element-type e) 'footnote-definition)
  7580. (goto-char (org-element-property :end e))))))
  7581. ((looking-at-p org-outline-regexp) (forward-line))
  7582. ((looking-at-p "[ \t]*$") (forward-line))
  7583. (t
  7584. (indent-line-to (+ (org-get-indentation) diff))
  7585. (beginning-of-line)
  7586. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7587. (let ((e (org-element-at-point)))
  7588. (and (memq (org-element-type e)
  7589. '(example-block src-block))
  7590. (or org-src-preserve-indentation
  7591. (org-element-property :preserve-indent e))
  7592. (goto-char (org-element-property :end e))
  7593. (progn (skip-chars-backward " \r\t\n")
  7594. (beginning-of-line)
  7595. t))))
  7596. (forward-line)))))))))
  7597. (defun org-convert-to-odd-levels ()
  7598. "Convert an org-mode file with all levels allowed to one with odd levels.
  7599. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7600. level 5 etc."
  7601. (interactive)
  7602. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7603. (let ((outline-level 'org-outline-level)
  7604. (org-odd-levels-only nil) n)
  7605. (save-excursion
  7606. (goto-char (point-min))
  7607. (while (re-search-forward "^\\*\\*+ " nil t)
  7608. (setq n (- (length (match-string 0)) 2))
  7609. (while (>= (setq n (1- n)) 0)
  7610. (org-demote))
  7611. (end-of-line 1))))))
  7612. (defun org-convert-to-oddeven-levels ()
  7613. "Convert an org-mode file with only odd levels to one with odd/even levels.
  7614. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7615. file contains a section with an even level, conversion would
  7616. destroy the structure of the file. An error is signaled in this
  7617. case."
  7618. (interactive)
  7619. (goto-char (point-min))
  7620. ;; First check if there are no even levels
  7621. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7622. (org-show-set-visibility 'canonical)
  7623. (error "Not all levels are odd in this file. Conversion not possible"))
  7624. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7625. (let ((outline-regexp org-outline-regexp)
  7626. (outline-level 'org-outline-level)
  7627. (org-odd-levels-only nil) n)
  7628. (save-excursion
  7629. (goto-char (point-min))
  7630. (while (re-search-forward "^\\*\\*+ " nil t)
  7631. (setq n (/ (1- (length (match-string 0))) 2))
  7632. (while (>= (setq n (1- n)) 0)
  7633. (org-promote))
  7634. (end-of-line 1))))))
  7635. (defun org-tr-level (n)
  7636. "Make N odd if required."
  7637. (if org-odd-levels-only (1+ (/ n 2)) n))
  7638. ;;; Vertical tree motion, cutting and pasting of subtrees
  7639. (defun org-move-subtree-up (&optional arg)
  7640. "Move the current subtree up past ARG headlines of the same level."
  7641. (interactive "p")
  7642. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7643. (defun org-move-subtree-down (&optional arg)
  7644. "Move the current subtree down past ARG headlines of the same level."
  7645. (interactive "p")
  7646. (setq arg (prefix-numeric-value arg))
  7647. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7648. 'org-get-last-sibling))
  7649. (ins-point (make-marker))
  7650. (cnt (abs arg))
  7651. (col (current-column))
  7652. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7653. ;; Select the tree
  7654. (org-back-to-heading)
  7655. (setq beg0 (point))
  7656. (save-excursion
  7657. (setq ne-beg (org-back-over-empty-lines))
  7658. (setq beg (point)))
  7659. (save-match-data
  7660. (save-excursion (outline-end-of-heading)
  7661. (setq folded (outline-invisible-p)))
  7662. (progn (org-end-of-subtree nil t)
  7663. (unless (eobp) (backward-char))))
  7664. (outline-next-heading)
  7665. (setq ne-end (org-back-over-empty-lines))
  7666. (setq end (point))
  7667. (goto-char beg0)
  7668. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7669. ;; include less whitespace
  7670. (save-excursion
  7671. (goto-char beg)
  7672. (forward-line (- ne-beg ne-end))
  7673. (setq beg (point))))
  7674. ;; Find insertion point, with error handling
  7675. (while (> cnt 0)
  7676. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7677. (progn (goto-char beg0)
  7678. (user-error "Cannot move past superior level or buffer limit")))
  7679. (setq cnt (1- cnt)))
  7680. (when (> arg 0)
  7681. ;; Moving forward - still need to move over subtree
  7682. (org-end-of-subtree t t)
  7683. (save-excursion
  7684. (org-back-over-empty-lines)
  7685. (or (bolp) (newline))))
  7686. (setq ne-ins (org-back-over-empty-lines))
  7687. (move-marker ins-point (point))
  7688. (setq txt (buffer-substring beg end))
  7689. (org-save-markers-in-region beg end)
  7690. (delete-region beg end)
  7691. (org-remove-empty-overlays-at beg)
  7692. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7693. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7694. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7695. (let ((bbb (point)))
  7696. (insert-before-markers txt)
  7697. (org-reinstall-markers-in-region bbb)
  7698. (move-marker ins-point bbb))
  7699. (or (bolp) (insert "\n"))
  7700. (setq ins-end (point))
  7701. (goto-char ins-point)
  7702. (org-skip-whitespace)
  7703. (when (and (< arg 0)
  7704. (org-first-sibling-p)
  7705. (> ne-ins ne-beg))
  7706. ;; Move whitespace back to beginning
  7707. (save-excursion
  7708. (goto-char ins-end)
  7709. (let ((kill-whole-line t))
  7710. (kill-line (- ne-ins ne-beg)) (point)))
  7711. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7712. (move-marker ins-point nil)
  7713. (if folded
  7714. (outline-hide-subtree)
  7715. (org-show-entry)
  7716. (org-show-children)
  7717. (org-cycle-hide-drawers 'children))
  7718. (org-clean-visibility-after-subtree-move)
  7719. ;; move back to the initial column we were at
  7720. (move-to-column col)))
  7721. (defvar org-subtree-clip ""
  7722. "Clipboard for cut and paste of subtrees.
  7723. This is actually only a copy of the kill, because we use the normal kill
  7724. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7725. (defvar org-subtree-clip-folded nil
  7726. "Was the last copied subtree folded?
  7727. This is used to fold the tree back after pasting.")
  7728. (defun org-cut-subtree (&optional n)
  7729. "Cut the current subtree into the clipboard.
  7730. With prefix arg N, cut this many sequential subtrees.
  7731. This is a short-hand for marking the subtree and then cutting it."
  7732. (interactive "p")
  7733. (org-copy-subtree n 'cut))
  7734. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7735. "Copy the current subtree it in the clipboard.
  7736. With prefix arg N, copy this many sequential subtrees.
  7737. This is a short-hand for marking the subtree and then copying it.
  7738. If CUT is non-nil, actually cut the subtree.
  7739. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7740. of some markers in the region, even if CUT is non-nil. This is
  7741. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7742. (interactive "p")
  7743. (let (beg end folded (beg0 (point)))
  7744. (if (called-interactively-p 'any)
  7745. (org-back-to-heading nil) ; take what looks like a subtree
  7746. (org-back-to-heading t)) ; take what is really there
  7747. (setq beg (point))
  7748. (skip-chars-forward " \t\r\n")
  7749. (save-match-data
  7750. (if nosubtrees
  7751. (outline-next-heading)
  7752. (save-excursion (outline-end-of-heading)
  7753. (setq folded (outline-invisible-p)))
  7754. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7755. (org-end-of-subtree t t)))
  7756. ;; Include the end of an inlinetask
  7757. (when (and (featurep 'org-inlinetask)
  7758. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7759. "END[ \t]*$")))
  7760. (end-of-line))
  7761. (setq end (point))
  7762. (goto-char beg0)
  7763. (when (> end beg)
  7764. (setq org-subtree-clip-folded folded)
  7765. (when (or cut force-store-markers)
  7766. (org-save-markers-in-region beg end))
  7767. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7768. (setq org-subtree-clip (current-kill 0))
  7769. (message "%s: Subtree(s) with %d characters"
  7770. (if cut "Cut" "Copied")
  7771. (length org-subtree-clip)))))
  7772. (defun org-paste-subtree (&optional level tree for-yank remove)
  7773. "Paste the clipboard as a subtree, with modification of headline level.
  7774. The entire subtree is promoted or demoted in order to match a new headline
  7775. level.
  7776. If the cursor is at the beginning of a headline, the same level as
  7777. that headline is used to paste the tree.
  7778. If not, the new level is derived from the *visible* headings
  7779. before and after the insertion point, and taken to be the inferior headline
  7780. level of the two. So if the previous visible heading is level 3 and the
  7781. next is level 4 (or vice versa), level 4 will be used for insertion.
  7782. This makes sure that the subtree remains an independent subtree and does
  7783. not swallow low level entries.
  7784. You can also force a different level, either by using a numeric prefix
  7785. argument, or by inserting the heading marker by hand. For example, if the
  7786. cursor is after \"*****\", then the tree will be shifted to level 5.
  7787. If optional TREE is given, use this text instead of the kill ring.
  7788. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7789. move back over whitespace before inserting, and move point to the end of
  7790. the inserted text when done.
  7791. When REMOVE is non-nil, remove the subtree from the clipboard."
  7792. (interactive "P")
  7793. (setq tree (or tree (and kill-ring (current-kill 0))))
  7794. (unless (org-kill-is-subtree-p tree)
  7795. (user-error "%s"
  7796. (substitute-command-keys
  7797. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7798. (org-with-limited-levels
  7799. (let* ((visp (not (outline-invisible-p)))
  7800. (txt tree)
  7801. (^re_ "\\(\\*+\\)[ \t]*")
  7802. (old-level (if (string-match org-outline-regexp-bol txt)
  7803. (- (match-end 0) (match-beginning 0) 1)
  7804. -1))
  7805. (force-level (cond (level (prefix-numeric-value level))
  7806. ((and (looking-at "[ \t]*$")
  7807. (string-match
  7808. "^\\*+$" (buffer-substring
  7809. (point-at-bol) (point))))
  7810. (- (match-end 0) (match-beginning 0)))
  7811. ((and (bolp)
  7812. (looking-at org-outline-regexp))
  7813. (- (match-end 0) (point) 1))))
  7814. (previous-level (save-excursion
  7815. (condition-case nil
  7816. (progn
  7817. (outline-previous-visible-heading 1)
  7818. (if (looking-at ^re_)
  7819. (- (match-end 0) (match-beginning 0) 1)
  7820. 1))
  7821. (error 1))))
  7822. (next-level (save-excursion
  7823. (condition-case nil
  7824. (progn
  7825. (or (looking-at org-outline-regexp)
  7826. (outline-next-visible-heading 1))
  7827. (if (looking-at ^re_)
  7828. (- (match-end 0) (match-beginning 0) 1)
  7829. 1))
  7830. (error 1))))
  7831. (new-level (or force-level (max previous-level next-level)))
  7832. (shift (if (or (= old-level -1)
  7833. (= new-level -1)
  7834. (= old-level new-level))
  7835. 0
  7836. (- new-level old-level)))
  7837. (delta (if (> shift 0) -1 1))
  7838. (func (if (> shift 0) 'org-demote 'org-promote))
  7839. (org-odd-levels-only nil)
  7840. beg end newend)
  7841. ;; Remove the forced level indicator
  7842. (when force-level
  7843. (delete-region (point-at-bol) (point)))
  7844. ;; Paste
  7845. (beginning-of-line (if (bolp) 1 2))
  7846. (setq beg (point))
  7847. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7848. (insert-before-markers txt)
  7849. (unless (string-match "\n\\'" txt) (insert "\n"))
  7850. (setq newend (point))
  7851. (org-reinstall-markers-in-region beg)
  7852. (setq end (point))
  7853. (goto-char beg)
  7854. (skip-chars-forward " \t\n\r")
  7855. (setq beg (point))
  7856. (when (and (outline-invisible-p) visp)
  7857. (save-excursion (outline-show-heading)))
  7858. ;; Shift if necessary
  7859. (unless (= shift 0)
  7860. (save-restriction
  7861. (narrow-to-region beg end)
  7862. (while (not (= shift 0))
  7863. (org-map-region func (point-min) (point-max))
  7864. (setq shift (+ delta shift)))
  7865. (goto-char (point-min))
  7866. (setq newend (point-max))))
  7867. (when (or (called-interactively-p 'interactive) for-yank)
  7868. (message "Clipboard pasted as level %d subtree" new-level))
  7869. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7870. kill-ring
  7871. (eq org-subtree-clip (current-kill 0))
  7872. org-subtree-clip-folded)
  7873. ;; The tree was folded before it was killed/copied
  7874. (outline-hide-subtree))
  7875. (and for-yank (goto-char newend))
  7876. (and remove (setq kill-ring (cdr kill-ring))))))
  7877. (defun org-kill-is-subtree-p (&optional txt)
  7878. "Check if the current kill is an outline subtree, or a set of trees.
  7879. Returns nil if kill does not start with a headline, or if the first
  7880. headline level is not the largest headline level in the tree.
  7881. So this will actually accept several entries of equal levels as well,
  7882. which is OK for `org-paste-subtree'.
  7883. If optional TXT is given, check this string instead of the current kill."
  7884. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7885. (re (org-get-limited-outline-regexp))
  7886. (^re (concat "^" re))
  7887. (start-level (and kill
  7888. (string-match
  7889. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7890. kill)
  7891. (- (match-end 2) (match-beginning 2) 1)))
  7892. (start (1+ (or (match-beginning 2) -1))))
  7893. (if (not start-level)
  7894. (progn
  7895. nil) ;; does not even start with a heading
  7896. (catch 'exit
  7897. (while (setq start (string-match ^re kill (1+ start)))
  7898. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7899. (throw 'exit nil)))
  7900. t))))
  7901. (defvar org-markers-to-move nil
  7902. "Markers that should be moved with a cut-and-paste operation.
  7903. Those markers are stored together with their positions relative to
  7904. the start of the region.")
  7905. (defun org-save-markers-in-region (beg end)
  7906. "Check markers in region.
  7907. If these markers are between BEG and END, record their position relative
  7908. to BEG, so that after moving the block of text, we can put the markers back
  7909. into place.
  7910. This function gets called just before an entry or tree gets cut from the
  7911. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7912. called immediately, to move the markers with the entries."
  7913. (setq org-markers-to-move nil)
  7914. (when (featurep 'org-clock)
  7915. (org-clock-save-markers-for-cut-and-paste beg end))
  7916. (when (featurep 'org-agenda)
  7917. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7918. (defun org-check-and-save-marker (marker beg end)
  7919. "Check if MARKER is between BEG and END.
  7920. If yes, remember the marker and the distance to BEG."
  7921. (when (and (marker-buffer marker)
  7922. (equal (marker-buffer marker) (current-buffer))
  7923. (>= marker beg) (< marker end))
  7924. (push (cons marker (- marker beg)) org-markers-to-move)))
  7925. (defun org-reinstall-markers-in-region (beg)
  7926. "Move all remembered markers to their position relative to BEG."
  7927. (dolist (x org-markers-to-move)
  7928. (move-marker (car x) (+ beg (cdr x))))
  7929. (setq org-markers-to-move nil))
  7930. (defun org-narrow-to-subtree ()
  7931. "Narrow buffer to the current subtree."
  7932. (interactive)
  7933. (save-excursion
  7934. (save-match-data
  7935. (org-with-limited-levels
  7936. (narrow-to-region
  7937. (progn (org-back-to-heading t) (point))
  7938. (progn (org-end-of-subtree t t)
  7939. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7940. (point)))))))
  7941. (defun org-narrow-to-block ()
  7942. "Narrow buffer to the current block."
  7943. (interactive)
  7944. (let* ((case-fold-search t)
  7945. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7946. "^[ \t]*#\\+end_.*")))
  7947. (if blockp
  7948. (narrow-to-region (car blockp) (cdr blockp))
  7949. (user-error "Not in a block"))))
  7950. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7951. "Clone the task (subtree) at point N times.
  7952. The clones will be inserted as siblings.
  7953. In interactive use, the user will be prompted for the number of
  7954. clones to be produced. If the entry has a timestamp, the user
  7955. will also be prompted for a time shift, which may be a repeater
  7956. as used in time stamps, for example `+3d'. To disable this,
  7957. you can call the function with a universal prefix argument.
  7958. When a valid repeater is given and the entry contains any time
  7959. stamps, the clones will become a sequence in time, with time
  7960. stamps in the subtree shifted for each clone produced. If SHIFT
  7961. is nil or the empty string, time stamps will be left alone. The
  7962. ID property of the original subtree is removed.
  7963. If the original subtree did contain time stamps with a repeater,
  7964. the following will happen:
  7965. - the repeater will be removed in each clone
  7966. - an additional clone will be produced, with the current, unshifted
  7967. date(s) in the entry.
  7968. - the original entry will be placed *after* all the clones, with
  7969. repeater intact.
  7970. - the start days in the repeater in the original entry will be shifted
  7971. to past the last clone.
  7972. In this way you can spell out a number of instances of a repeating task,
  7973. and still retain the repeater to cover future instances of the task.
  7974. As described above, N+1 clones are produced when the original
  7975. subtree has a repeater. Setting N to 0, then, can be used to
  7976. remove the repeater from a subtree and create a shifted clone
  7977. with the original repeater."
  7978. (interactive "nNumber of clones to produce: ")
  7979. (let ((shift
  7980. (or shift
  7981. (if (and (not (equal current-prefix-arg '(4)))
  7982. (save-excursion
  7983. (re-search-forward org-ts-regexp-both
  7984. (save-excursion
  7985. (org-end-of-subtree t)
  7986. (point)) t)))
  7987. (read-from-minibuffer
  7988. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7989. ""))) ;; No time shift
  7990. (n-no-remove -1)
  7991. (drawer-re org-drawer-regexp)
  7992. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7993. beg end template task idprop
  7994. shift-n shift-what doshift nmin nmax)
  7995. (unless (wholenump n)
  7996. (user-error "Invalid number of replications %s" n))
  7997. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7998. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7999. shift)))
  8000. (user-error "Invalid shift specification %s" shift))
  8001. (when doshift
  8002. (setq shift-n (string-to-number (match-string 1 shift))
  8003. shift-what (cdr (assoc (match-string 2 shift)
  8004. '(("d" . day) ("w" . week)
  8005. ("m" . month) ("y" . year))))))
  8006. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  8007. (setq nmin 1 nmax n)
  8008. (org-back-to-heading t)
  8009. (setq beg (point))
  8010. (setq idprop (org-entry-get nil "ID"))
  8011. (org-end-of-subtree t t)
  8012. (or (bolp) (insert "\n"))
  8013. (setq end (point))
  8014. (setq template (buffer-substring beg end))
  8015. (when (and doshift
  8016. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  8017. (delete-region beg end)
  8018. (setq end beg)
  8019. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  8020. (goto-char end)
  8021. (cl-loop for n from nmin to nmax do
  8022. ;; prepare clone
  8023. (with-temp-buffer
  8024. (insert template)
  8025. (org-mode)
  8026. (goto-char (point-min))
  8027. (org-show-subtree)
  8028. (and idprop (if org-clone-delete-id
  8029. (org-entry-delete nil "ID")
  8030. (org-id-get-create t)))
  8031. (unless (= n 0)
  8032. (while (re-search-forward org-clock-re nil t)
  8033. (kill-whole-line))
  8034. (goto-char (point-min))
  8035. (while (re-search-forward drawer-re nil t)
  8036. (org-remove-empty-drawer-at (point))))
  8037. (goto-char (point-min))
  8038. (when doshift
  8039. (while (re-search-forward org-ts-regexp-both nil t)
  8040. (org-timestamp-change (* n shift-n) shift-what))
  8041. (unless (= n n-no-remove)
  8042. (goto-char (point-min))
  8043. (while (re-search-forward org-ts-regexp nil t)
  8044. (save-excursion
  8045. (goto-char (match-beginning 0))
  8046. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8047. (delete-region (match-beginning 1) (match-end 1)))))))
  8048. (setq task (buffer-string)))
  8049. (insert task))
  8050. (goto-char beg)))
  8051. ;;; Outline Sorting
  8052. (defun org-sort (with-case)
  8053. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8054. Optional argument WITH-CASE means sort case-sensitively."
  8055. (interactive "P")
  8056. (cond
  8057. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8058. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8059. (t
  8060. (org-call-with-arg 'org-sort-entries with-case))))
  8061. (defun org-sort-remove-invisible (s)
  8062. "Remove invisible links from string S."
  8063. (remove-text-properties 0 (length s) org-rm-props s)
  8064. (while (string-match org-bracket-link-regexp s)
  8065. (setq s (replace-match (if (match-end 2)
  8066. (match-string 3 s)
  8067. (match-string 1 s))
  8068. t t s)))
  8069. (let ((st (format " %s " s)))
  8070. (while (string-match org-emph-re st)
  8071. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8072. (setq s (substring st 1 -1)))
  8073. s)
  8074. (defvar org-priority-regexp) ; defined later in the file
  8075. (defvar org-after-sorting-entries-or-items-hook nil
  8076. "Hook that is run after a bunch of entries or items have been sorted.
  8077. When children are sorted, the cursor is in the parent line when this
  8078. hook gets called. When a region or a plain list is sorted, the cursor
  8079. will be in the first entry of the sorted region/list.")
  8080. (defun org-sort-entries
  8081. (&optional with-case sorting-type getkey-func compare-func property)
  8082. "Sort entries on a certain level of an outline tree.
  8083. If there is an active region, the entries in the region are sorted.
  8084. Else, if the cursor is before the first entry, sort the top-level items.
  8085. Else, the children of the entry at point are sorted.
  8086. Sorting can be alphabetically, numerically, by date/time as given by
  8087. a time stamp, by a property, by priority order, or by a custom function.
  8088. The command prompts for the sorting type unless it has been given to the
  8089. function through the SORTING-TYPE argument, which needs to be a character,
  8090. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8091. the precise meaning of each character:
  8092. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8093. c By creation time, which is assumed to be the first inactive time stamp
  8094. at the beginning of a line.
  8095. d By deadline date/time.
  8096. k By clocking time.
  8097. n Numerically, by converting the beginning of the entry/item to a number.
  8098. o By order of TODO keywords.
  8099. p By priority according to the cookie.
  8100. r By the value of a property.
  8101. s By scheduled date/time.
  8102. t By date/time, either the first active time stamp in the entry, or, if
  8103. none exist, by the first inactive one.
  8104. Capital letters will reverse the sort order.
  8105. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8106. called with point at the beginning of the record. It must return either
  8107. a string or a number that should serve as the sorting key for that record.
  8108. Comparing entries ignores case by default. However, with an optional argument
  8109. WITH-CASE, the sorting considers case as well.
  8110. Sorting is done against the visible part of the headlines, it ignores hidden
  8111. links.
  8112. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8113. (interactive "P")
  8114. (let ((case-func (if with-case 'identity 'downcase))
  8115. (cmstr
  8116. ;; The clock marker is lost when using `sort-subr', let's
  8117. ;; store the clocking string.
  8118. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8119. (save-excursion
  8120. (goto-char org-clock-marker)
  8121. (buffer-substring-no-properties (line-beginning-position)
  8122. (point)))))
  8123. start beg end stars re re2
  8124. txt what tmp)
  8125. ;; Find beginning and end of region to sort
  8126. (cond
  8127. ((org-region-active-p)
  8128. ;; we will sort the region
  8129. (setq end (region-end)
  8130. what "region")
  8131. (goto-char (region-beginning))
  8132. (unless (org-at-heading-p) (outline-next-heading))
  8133. (setq start (point)))
  8134. ((or (org-at-heading-p)
  8135. (ignore-errors (progn (org-back-to-heading) t)))
  8136. ;; we will sort the children of the current headline
  8137. (org-back-to-heading)
  8138. (setq start (point)
  8139. end (progn (org-end-of-subtree t t)
  8140. (or (bolp) (insert "\n"))
  8141. (when (>= (org-back-over-empty-lines) 1)
  8142. (forward-line 1))
  8143. (point))
  8144. what "children")
  8145. (goto-char start)
  8146. (outline-show-subtree)
  8147. (outline-next-heading))
  8148. (t
  8149. ;; we will sort the top-level entries in this file
  8150. (goto-char (point-min))
  8151. (or (org-at-heading-p) (outline-next-heading))
  8152. (setq start (point))
  8153. (goto-char (point-max))
  8154. (beginning-of-line 1)
  8155. (when (looking-at ".*?\\S-")
  8156. ;; File ends in a non-white line
  8157. (end-of-line 1)
  8158. (insert "\n"))
  8159. (setq end (point-max))
  8160. (setq what "top-level")
  8161. (goto-char start)
  8162. (outline-show-all)))
  8163. (setq beg (point))
  8164. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8165. (looking-at "\\(\\*+\\)")
  8166. (setq stars (match-string 1)
  8167. re (concat "^" (regexp-quote stars) " +")
  8168. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8169. txt (buffer-substring beg end))
  8170. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8171. (when (and (not (equal stars "*")) (string-match re2 txt))
  8172. (user-error "Region to sort contains a level above the first entry"))
  8173. (unless sorting-type
  8174. (message
  8175. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8176. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8177. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8178. what)
  8179. (setq sorting-type (read-char-exclusive))
  8180. (unless getkey-func
  8181. (and (= (downcase sorting-type) ?f)
  8182. (setq getkey-func
  8183. (completing-read "Sort using function: "
  8184. obarray 'fboundp t nil nil))
  8185. (setq getkey-func (intern getkey-func))))
  8186. (and (= (downcase sorting-type) ?r)
  8187. (not property)
  8188. (setq property
  8189. (completing-read "Property: "
  8190. (mapcar #'list (org-buffer-property-keys t))
  8191. nil t))))
  8192. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8193. (message "Sorting entries...")
  8194. (save-restriction
  8195. (narrow-to-region start end)
  8196. (let ((dcst (downcase sorting-type))
  8197. (case-fold-search nil)
  8198. (now (current-time)))
  8199. (sort-subr
  8200. (/= dcst sorting-type)
  8201. ;; This function moves to the beginning character of the "record" to
  8202. ;; be sorted.
  8203. (lambda nil
  8204. (if (re-search-forward re nil t)
  8205. (goto-char (match-beginning 0))
  8206. (goto-char (point-max))))
  8207. ;; This function moves to the last character of the "record" being
  8208. ;; sorted.
  8209. (lambda nil
  8210. (save-match-data
  8211. (condition-case nil
  8212. (outline-forward-same-level 1)
  8213. (error
  8214. (goto-char (point-max))))))
  8215. ;; This function returns the value that gets sorted against.
  8216. (lambda nil
  8217. (cond
  8218. ((= dcst ?n)
  8219. (if (looking-at org-complex-heading-regexp)
  8220. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8221. nil))
  8222. ((= dcst ?a)
  8223. (if (looking-at org-complex-heading-regexp)
  8224. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8225. nil))
  8226. ((= dcst ?k)
  8227. (or (get-text-property (point) :org-clock-minutes) 0))
  8228. ((= dcst ?t)
  8229. (let ((end (save-excursion (outline-next-heading) (point))))
  8230. (if (or (re-search-forward org-ts-regexp end t)
  8231. (re-search-forward org-ts-regexp-both end t))
  8232. (org-time-string-to-seconds (match-string 0))
  8233. (float-time now))))
  8234. ((= dcst ?c)
  8235. (let ((end (save-excursion (outline-next-heading) (point))))
  8236. (if (re-search-forward
  8237. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8238. end t)
  8239. (org-time-string-to-seconds (match-string 0))
  8240. (float-time now))))
  8241. ((= dcst ?s)
  8242. (let ((end (save-excursion (outline-next-heading) (point))))
  8243. (if (re-search-forward org-scheduled-time-regexp end t)
  8244. (org-time-string-to-seconds (match-string 1))
  8245. (float-time now))))
  8246. ((= dcst ?d)
  8247. (let ((end (save-excursion (outline-next-heading) (point))))
  8248. (if (re-search-forward org-deadline-time-regexp end t)
  8249. (org-time-string-to-seconds (match-string 1))
  8250. (float-time now))))
  8251. ((= dcst ?p)
  8252. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8253. (string-to-char (match-string 2))
  8254. org-default-priority))
  8255. ((= dcst ?r)
  8256. (or (org-entry-get nil property) ""))
  8257. ((= dcst ?o)
  8258. (when (looking-at org-complex-heading-regexp)
  8259. (let* ((m (match-string 2))
  8260. (s (if (member m org-done-keywords) '- '+)))
  8261. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8262. ((= dcst ?f)
  8263. (if getkey-func
  8264. (progn
  8265. (setq tmp (funcall getkey-func))
  8266. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8267. tmp)
  8268. (error "Invalid key function `%s'" getkey-func)))
  8269. (t (error "Invalid sorting type `%c'" sorting-type))))
  8270. nil
  8271. (cond
  8272. ((= dcst ?a) 'string<)
  8273. ((= dcst ?f) compare-func)
  8274. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8275. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8276. ;; Reset the clock marker if needed
  8277. (when cmstr
  8278. (save-excursion
  8279. (goto-char start)
  8280. (search-forward cmstr nil t)
  8281. (move-marker org-clock-marker (point))))
  8282. (message "Sorting entries...done")))
  8283. ;;; The orgstruct minor mode
  8284. ;; Define a minor mode which can be used in other modes in order to
  8285. ;; integrate the org-mode structure editing commands.
  8286. ;; This is really a hack, because the org-mode structure commands use
  8287. ;; keys which normally belong to the major mode. Here is how it
  8288. ;; works: The minor mode defines all the keys necessary to operate the
  8289. ;; structure commands, but wraps the commands into a function which
  8290. ;; tests if the cursor is currently at a headline or a plain list
  8291. ;; item. If that is the case, the structure command is used,
  8292. ;; temporarily setting many Org-mode variables like regular
  8293. ;; expressions for filling etc. However, when any of those keys is
  8294. ;; used at a different location, function uses `key-binding' to look
  8295. ;; up if the key has an associated command in another currently active
  8296. ;; keymap (minor modes, major mode, global), and executes that
  8297. ;; command. There might be problems if any of the keys is otherwise
  8298. ;; used as a prefix key.
  8299. (defcustom orgstruct-heading-prefix-regexp ""
  8300. "Regexp that matches the custom prefix of Org headlines in
  8301. orgstruct(++)-mode."
  8302. :group 'org
  8303. :version "24.4"
  8304. :package-version '(Org . "8.3")
  8305. :type 'regexp)
  8306. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8307. (defcustom orgstruct-setup-hook nil
  8308. "Hook run after orgstruct-mode-map is filled."
  8309. :group 'org
  8310. :version "24.4"
  8311. :package-version '(Org . "8.0")
  8312. :type 'hook)
  8313. (defvar orgstruct-initialized nil)
  8314. (defvar org-local-vars nil
  8315. "List of local variables, for use by `orgstruct-mode'.")
  8316. ;;;###autoload
  8317. (define-minor-mode orgstruct-mode
  8318. "Toggle the minor mode `orgstruct-mode'.
  8319. This mode is for using Org-mode structure commands in other
  8320. modes. The following keys behave as if Org-mode were active, if
  8321. the cursor is on a headline, or on a plain list item (both as
  8322. defined by Org-mode)."
  8323. nil " OrgStruct" (make-sparse-keymap)
  8324. (funcall (if orgstruct-mode
  8325. 'add-to-invisibility-spec
  8326. 'remove-from-invisibility-spec)
  8327. '(outline . t))
  8328. (when orgstruct-mode
  8329. (org-load-modules-maybe)
  8330. (unless orgstruct-initialized
  8331. (orgstruct-setup)
  8332. (setq orgstruct-initialized t))))
  8333. ;;;###autoload
  8334. (defun turn-on-orgstruct ()
  8335. "Unconditionally turn on `orgstruct-mode'."
  8336. (orgstruct-mode 1))
  8337. (defvar-local orgstruct-is-++ nil
  8338. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8339. (defvar-local org-fb-vars nil)
  8340. (defun orgstruct++-mode (&optional arg)
  8341. "Toggle `orgstruct-mode', the enhanced version of it.
  8342. In addition to setting orgstruct-mode, this also exports all
  8343. indentation and autofilling variables from org-mode into the
  8344. buffer. It will also recognize item context in multiline items."
  8345. (interactive "P")
  8346. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8347. (if (< arg 1)
  8348. (progn (orgstruct-mode -1)
  8349. (dolist (v org-fb-vars)
  8350. (set (make-local-variable (car v))
  8351. (if (eq (car-safe (cadr v)) 'quote)
  8352. (cl-cadadr v)
  8353. (nth 1 v)))))
  8354. (orgstruct-mode 1)
  8355. (setq org-fb-vars nil)
  8356. (unless org-local-vars
  8357. (setq org-local-vars (org-get-local-variables)))
  8358. (let (var val)
  8359. (dolist (x org-local-vars)
  8360. (when (string-match
  8361. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8362. \\|fill-prefix\\|indent-\\)"
  8363. (symbol-name (car x)))
  8364. (setq var (car x) val (nth 1 x))
  8365. (push (list var `(quote ,(eval var))) org-fb-vars)
  8366. (set (make-local-variable var)
  8367. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8368. (setq-local orgstruct-is-++ t))))
  8369. ;;;###autoload
  8370. (defun turn-on-orgstruct++ ()
  8371. "Unconditionally turn on `orgstruct++-mode'."
  8372. (orgstruct++-mode 1))
  8373. (defun orgstruct-error ()
  8374. "Error when there is no default binding for a structure key."
  8375. (interactive)
  8376. (funcall (if (fboundp 'user-error)
  8377. 'user-error
  8378. 'error)
  8379. "This key has no function outside structure elements"))
  8380. (defun orgstruct-setup ()
  8381. "Setup orgstruct keymap."
  8382. (dolist (cell '((org-demote . t)
  8383. (org-metaleft . t)
  8384. (org-metaright . t)
  8385. (org-promote . t)
  8386. (org-shiftmetaleft . t)
  8387. (org-shiftmetaright . t)
  8388. org-backward-element
  8389. org-backward-heading-same-level
  8390. org-ctrl-c-ret
  8391. org-ctrl-c-minus
  8392. org-ctrl-c-star
  8393. org-cycle
  8394. org-force-cycle-archived
  8395. org-forward-heading-same-level
  8396. org-insert-heading
  8397. org-insert-heading-respect-content
  8398. org-kill-note-or-show-branches
  8399. org-mark-subtree
  8400. org-meta-return
  8401. org-metadown
  8402. org-metaup
  8403. org-narrow-to-subtree
  8404. org-promote-subtree
  8405. org-reveal
  8406. org-shiftdown
  8407. org-shiftleft
  8408. org-shiftmetadown
  8409. org-shiftmetaup
  8410. org-shiftright
  8411. org-shifttab
  8412. org-shifttab
  8413. org-shiftup
  8414. org-show-children
  8415. org-show-subtree
  8416. org-sort
  8417. org-up-element
  8418. outline-demote
  8419. outline-next-visible-heading
  8420. outline-previous-visible-heading
  8421. outline-promote
  8422. outline-up-heading))
  8423. (let ((f (or (car-safe cell) cell))
  8424. (disable-when-heading-prefix (cdr-safe cell)))
  8425. (when (fboundp f)
  8426. (let ((new-bindings))
  8427. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8428. (where-is-internal f outline-mode-map)))
  8429. (push binding new-bindings)
  8430. ;; TODO use local-function-key-map
  8431. (dolist (rep '(("<tab>" . "TAB")
  8432. ("<return>" . "RET")
  8433. ("<escape>" . "ESC")
  8434. ("<delete>" . "DEL")))
  8435. (setq binding (read-kbd-macro
  8436. (let ((case-fold-search))
  8437. (replace-regexp-in-string
  8438. (regexp-quote (cdr rep))
  8439. (car rep)
  8440. (key-description binding)))))
  8441. (cl-pushnew binding new-bindings :test 'equal)))
  8442. (dolist (binding new-bindings)
  8443. (let ((key (lookup-key orgstruct-mode-map binding)))
  8444. (when (or (not key) (numberp key))
  8445. (ignore-errors
  8446. (org-defkey orgstruct-mode-map
  8447. binding
  8448. (orgstruct-make-binding
  8449. f binding disable-when-heading-prefix))))))))))
  8450. (run-hooks 'orgstruct-setup-hook))
  8451. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8452. "Create a function for binding in the structure minor mode.
  8453. FUN is the command to call inside a table. KEY is the key that
  8454. should be checked in for a command to execute outside of tables.
  8455. Non-nil `disable-when-heading-prefix' means to disable the command
  8456. if `orgstruct-heading-prefix-regexp' is not empty."
  8457. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8458. (let ((nname name)
  8459. (i 0))
  8460. (while (fboundp (intern nname))
  8461. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8462. (setq name (intern nname)))
  8463. (eval
  8464. (let ((bindings '((org-heading-regexp
  8465. (concat "^"
  8466. orgstruct-heading-prefix-regexp
  8467. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8468. (org-outline-regexp
  8469. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8470. (org-outline-regexp-bol
  8471. (concat "^" org-outline-regexp))
  8472. (outline-regexp org-outline-regexp)
  8473. (outline-heading-end-regexp "\n")
  8474. (outline-level 'org-outline-level)
  8475. (outline-heading-alist))))
  8476. `(defun ,name (arg)
  8477. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8478. "Outside of structure, run the binding of `"
  8479. (key-description key) "'."
  8480. (when disable-when-heading-prefix
  8481. (concat
  8482. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8483. "back to the default binding due to limitations of Org's implementation of\n"
  8484. "`" (symbol-name fun) "'.")))
  8485. (interactive "p")
  8486. (let* ((disable
  8487. ,(and disable-when-heading-prefix
  8488. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8489. (fallback
  8490. (or disable
  8491. (not
  8492. (let* ,bindings
  8493. (org-context-p 'headline 'item
  8494. ,(when (memq fun
  8495. '(org-insert-heading
  8496. org-insert-heading-respect-content
  8497. org-meta-return))
  8498. '(when orgstruct-is-++
  8499. 'item-body))))))))
  8500. (if fallback
  8501. (let* ((orgstruct-mode)
  8502. (binding
  8503. (let ((key ,key))
  8504. (catch 'exit
  8505. (dolist
  8506. (rep
  8507. '(nil
  8508. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8509. ("<\\([^>]*\\)return>" . "\\1RET")
  8510. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8511. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8512. nil)
  8513. (when rep
  8514. (setq key (read-kbd-macro
  8515. (let ((case-fold-search))
  8516. (replace-regexp-in-string
  8517. (car rep)
  8518. (cdr rep)
  8519. (key-description key))))))
  8520. (when (key-binding key)
  8521. (throw 'exit (key-binding key))))))))
  8522. (if (keymapp binding)
  8523. (org-set-transient-map binding)
  8524. (let ((func (or binding
  8525. (unless disable
  8526. 'orgstruct-error))))
  8527. (when func
  8528. (call-interactively func)))))
  8529. (org-run-like-in-org-mode
  8530. (lambda ()
  8531. (interactive)
  8532. (let* ,bindings
  8533. (call-interactively ',fun)))))))))
  8534. name))
  8535. (defun org-contextualize-keys (alist contexts)
  8536. "Return valid elements in ALIST depending on CONTEXTS.
  8537. `org-agenda-custom-commands' or `org-capture-templates' are the
  8538. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8539. or `org-capture-templates-contexts' are the associated contexts
  8540. definitions."
  8541. (let ((contexts
  8542. ;; normalize contexts
  8543. (mapcar
  8544. (lambda(c) (cond ((listp (cadr c))
  8545. (list (car c) (car c) (nth 1 c)))
  8546. ((string= "" (cadr c))
  8547. (list (car c) (car c) (nth 2 c)))
  8548. (t c)))
  8549. contexts))
  8550. (a alist) r s)
  8551. ;; loop over all commands or templates
  8552. (dolist (c a)
  8553. (let (vrules repl)
  8554. (cond
  8555. ((not (assoc (car c) contexts))
  8556. (push c r))
  8557. ((and (assoc (car c) contexts)
  8558. (setq vrules (org-contextualize-validate-key
  8559. (car c) contexts)))
  8560. (mapc (lambda (vr)
  8561. (unless (equal (car vr) (cadr vr))
  8562. (setq repl vr)))
  8563. vrules)
  8564. (if (not repl) (push c r)
  8565. (push (cadr repl) s)
  8566. (push
  8567. (cons (car c)
  8568. (cdr (or (assoc (cadr repl) alist)
  8569. (error "Undefined key `%s' as contextual replacement for `%s'"
  8570. (cadr repl) (car c)))))
  8571. r))))))
  8572. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8573. (delq
  8574. nil
  8575. (delete-dups
  8576. (mapcar (lambda (x)
  8577. (let ((tpl (car x)))
  8578. (unless (delq
  8579. nil
  8580. (mapcar (lambda (y)
  8581. (equal y tpl))
  8582. s))
  8583. x)))
  8584. (reverse r))))))
  8585. (defun org-contextualize-validate-key (key contexts)
  8586. "Check CONTEXTS for agenda or capture KEY."
  8587. (let (res)
  8588. (dolist (r contexts)
  8589. (dolist (rr (car (last r)))
  8590. (when
  8591. (and (equal key (car r))
  8592. (if (functionp rr) (funcall rr)
  8593. (or (and (eq (car rr) 'in-file)
  8594. (buffer-file-name)
  8595. (string-match (cdr rr) (buffer-file-name)))
  8596. (and (eq (car rr) 'in-mode)
  8597. (string-match (cdr rr) (symbol-name major-mode)))
  8598. (and (eq (car rr) 'in-buffer)
  8599. (string-match (cdr rr) (buffer-name)))
  8600. (when (and (eq (car rr) 'not-in-file)
  8601. (buffer-file-name))
  8602. (not (string-match (cdr rr) (buffer-file-name))))
  8603. (when (eq (car rr) 'not-in-mode)
  8604. (not (string-match (cdr rr) (symbol-name major-mode))))
  8605. (when (eq (car rr) 'not-in-buffer)
  8606. (not (string-match (cdr rr) (buffer-name)))))))
  8607. (push r res))))
  8608. (delete-dups (delq nil res))))
  8609. (defun org-context-p (&rest contexts)
  8610. "Check if local context is any of CONTEXTS.
  8611. Possible values in the list of contexts are `table', `headline', and `item'."
  8612. (let ((pos (point)))
  8613. (goto-char (point-at-bol))
  8614. (prog1 (or (and (memq 'table contexts)
  8615. (looking-at "[ \t]*|"))
  8616. (and (memq 'headline contexts)
  8617. (looking-at org-outline-regexp))
  8618. (and (memq 'item contexts)
  8619. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8620. (and (memq 'item-body contexts)
  8621. (org-in-item-p)))
  8622. (goto-char pos))))
  8623. (defconst org-unique-local-variables
  8624. '(org-element--cache
  8625. org-element--cache-objects
  8626. org-element--cache-sync-keys
  8627. org-element--cache-sync-requests
  8628. org-element--cache-sync-timer)
  8629. "List of local variables that cannot be transferred to another buffer.")
  8630. (defun org-get-local-variables ()
  8631. "Return a list of all local variables in an Org mode buffer."
  8632. (delq nil
  8633. (mapcar
  8634. (lambda (x)
  8635. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8636. (name (car binding)))
  8637. (and (not (get name 'org-state))
  8638. (not (memq name org-unique-local-variables))
  8639. (string-match-p
  8640. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8641. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8642. (symbol-name name))
  8643. binding)))
  8644. (with-temp-buffer
  8645. (org-mode)
  8646. (buffer-local-variables)))))
  8647. (defun org-clone-local-variables (from-buffer &optional regexp)
  8648. "Clone local variables from FROM-BUFFER.
  8649. Optional argument REGEXP selects variables to clone."
  8650. (dolist (pair (buffer-local-variables from-buffer))
  8651. (let ((name (car pair)))
  8652. (when (and (symbolp name)
  8653. (not (memq name org-unique-local-variables))
  8654. (or (null regexp) (string-match regexp (symbol-name name))))
  8655. (set (make-local-variable name) (cdr pair))))))
  8656. ;;;###autoload
  8657. (defun org-run-like-in-org-mode (cmd)
  8658. "Run a command, pretending that the current buffer is in Org-mode.
  8659. This will temporarily bind local variables that are typically bound in
  8660. Org-mode to the values they have in Org-mode, and then interactively
  8661. call CMD."
  8662. (org-load-modules-maybe)
  8663. (unless org-local-vars
  8664. (setq org-local-vars (org-get-local-variables)))
  8665. (let (binds)
  8666. (dolist (var org-local-vars)
  8667. (when (or (not (boundp (car var)))
  8668. (eq (symbol-value (car var))
  8669. (default-value (car var))))
  8670. (push (list (car var) `(quote ,(cadr var))) binds)))
  8671. (eval `(let ,binds
  8672. (call-interactively (quote ,cmd))))))
  8673. (defun org-get-category (&optional pos force-refresh)
  8674. "Get the category applying to position POS."
  8675. (save-match-data
  8676. (when force-refresh (org-refresh-category-properties))
  8677. (let ((pos (or pos (point))))
  8678. (or (get-text-property pos 'org-category)
  8679. (progn (org-refresh-category-properties)
  8680. (get-text-property pos 'org-category))))))
  8681. ;;; Refresh properties
  8682. (defun org-refresh-properties (dprop tprop)
  8683. "Refresh buffer text properties.
  8684. DPROP is the drawer property and TPROP is either the
  8685. corresponding text property to set, or an alist with each element
  8686. being a text property (as a symbol) and a function to apply to
  8687. the value of the drawer property."
  8688. (let ((case-fold-search t)
  8689. (inhibit-read-only t))
  8690. (org-with-silent-modifications
  8691. (save-excursion
  8692. (save-restriction
  8693. (widen)
  8694. (goto-char (point-min))
  8695. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8696. (org-refresh-property tprop (match-string-no-properties 1))))))))
  8697. (defun org-refresh-property (tprop p)
  8698. "Refresh the buffer text property TPROP from the drawer property P.
  8699. The refresh happens only for the current tree (not subtree)."
  8700. (unless (org-before-first-heading-p)
  8701. (save-excursion
  8702. (org-back-to-heading t)
  8703. (if (symbolp tprop)
  8704. ;; TPROP is a text property symbol
  8705. (put-text-property
  8706. (point) (or (outline-next-heading) (point-max)) tprop p)
  8707. ;; TPROP is an alist with (properties . function) elements
  8708. (dolist (al tprop)
  8709. (save-excursion
  8710. (put-text-property
  8711. (line-beginning-position) (or (outline-next-heading) (point-max))
  8712. (car al)
  8713. (funcall (cdr al) p))))))))
  8714. (defun org-refresh-category-properties ()
  8715. "Refresh category text properties in the buffer."
  8716. (let ((case-fold-search t)
  8717. (inhibit-read-only t)
  8718. (default-category
  8719. (cond ((null org-category)
  8720. (if buffer-file-name
  8721. (file-name-sans-extension
  8722. (file-name-nondirectory buffer-file-name))
  8723. "???"))
  8724. ((symbolp org-category) (symbol-name org-category))
  8725. (t org-category))))
  8726. (org-with-silent-modifications
  8727. (org-with-wide-buffer
  8728. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8729. ;; This is the default category for the buffer. If none is
  8730. ;; found, fall-back to `org-category' or buffer file name.
  8731. (put-text-property
  8732. (point-min) (point-max)
  8733. 'org-category
  8734. (catch 'buffer-category
  8735. (goto-char (point-max))
  8736. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8737. (let ((element (org-element-at-point)))
  8738. (when (eq (org-element-type element) 'keyword)
  8739. (throw 'buffer-category
  8740. (org-element-property :value element)))))
  8741. default-category))
  8742. ;; Set sub-tree specific categories.
  8743. (goto-char (point-min))
  8744. (let ((regexp (org-re-property "CATEGORY")))
  8745. (while (re-search-forward regexp nil t)
  8746. (let ((value (match-string-no-properties 3)))
  8747. (when (org-at-property-p)
  8748. (put-text-property
  8749. (save-excursion (org-back-to-heading t) (point))
  8750. (save-excursion (org-end-of-subtree t t) (point))
  8751. 'org-category
  8752. value)))))))))
  8753. (defun org-refresh-stats-properties ()
  8754. "Refresh stats text properties in the buffer."
  8755. (let (stats)
  8756. (org-with-silent-modifications
  8757. (save-excursion
  8758. (save-restriction
  8759. (widen)
  8760. (goto-char (point-min))
  8761. (while (re-search-forward
  8762. (concat org-outline-regexp-bol ".*"
  8763. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8764. nil t)
  8765. (setq stats (cond ((equal (match-string 3) "0") 0)
  8766. ((match-string 2)
  8767. (/ (* (string-to-number (match-string 2)) 100)
  8768. (string-to-number (match-string 3))))
  8769. (t (string-to-number (match-string 1)))))
  8770. (org-back-to-heading t)
  8771. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8772. 'org-stats stats)))))))
  8773. (defun org-refresh-effort-properties ()
  8774. "Refresh effort properties"
  8775. (org-refresh-properties
  8776. org-effort-property
  8777. '((effort . identity)
  8778. (effort-minutes . org-duration-string-to-minutes))))
  8779. ;;;; Link Stuff
  8780. ;;; Link abbreviations
  8781. (defun org-link-expand-abbrev (link)
  8782. "Apply replacements as defined in `org-link-abbrev-alist'."
  8783. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8784. (let* ((key (match-string 1 link))
  8785. (as (or (assoc key org-link-abbrev-alist-local)
  8786. (assoc key org-link-abbrev-alist)))
  8787. (tag (and (match-end 2) (match-string 3 link)))
  8788. rpl)
  8789. (if (not as)
  8790. link
  8791. (setq rpl (cdr as))
  8792. (cond
  8793. ((symbolp rpl) (funcall rpl tag))
  8794. ((string-match "%(\\([^)]+\\))" rpl)
  8795. (replace-match
  8796. (save-match-data
  8797. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8798. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8799. ((string-match "%h" rpl)
  8800. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8801. (t (concat rpl tag)))))
  8802. link))
  8803. ;;; Storing and inserting links
  8804. (defvar org-insert-link-history nil
  8805. "Minibuffer history for links inserted with `org-insert-link'.")
  8806. (defvar org-stored-links nil
  8807. "Contains the links stored with `org-store-link'.")
  8808. (defvar org-store-link-plist nil
  8809. "Plist with info about the most recently link created with `org-store-link'.")
  8810. (defun org-store-link-functions ()
  8811. "Return a list of functions that are called to create and store a link.
  8812. The functions defined in the :store property of
  8813. `org-link-parameters'.
  8814. Each function will be called in turn until one returns a non-nil
  8815. value. Each function should check if it is responsible for
  8816. creating this link (for example by looking at the major mode).
  8817. If not, it must exit and return nil. If yes, it should return
  8818. a non-nil value after calling `org-store-link-props' with a list
  8819. of properties and values. Special properties are:
  8820. :type The link prefix, like \"http\". This must be given.
  8821. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8822. This is obligatory as well.
  8823. :description Optional default description for the second pair
  8824. of brackets in an Org mode link. The user can still change
  8825. this when inserting this link into an Org mode buffer.
  8826. In addition to these, any additional properties can be specified
  8827. and then used in capture templates."
  8828. (cl-loop for link in org-link-parameters
  8829. with store-func
  8830. do (setq store-func (org-link-get-parameter (car link) :store))
  8831. if store-func
  8832. collect store-func))
  8833. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8834. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8835. ;;;###autoload
  8836. (defun org-store-link (arg)
  8837. "\\<org-mode-map>Store an org-link to the current location.
  8838. This link is added to `org-stored-links' and can later be inserted
  8839. into an Org buffer with \\[org-insert-link].
  8840. For some link types, a prefix ARG is interpreted.
  8841. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8842. For file links, ARG negates `org-context-in-file-links'.
  8843. A double prefix ARG force skipping storing functions that are not
  8844. part of Org's core.
  8845. A triple prefix ARG force storing a link for each line in the
  8846. active region."
  8847. (interactive "P")
  8848. (org-load-modules-maybe)
  8849. (if (and (equal arg '(64)) (org-region-active-p))
  8850. (save-excursion
  8851. (let ((end (region-end)))
  8852. (goto-char (region-beginning))
  8853. (set-mark (point))
  8854. (while (< (point-at-eol) end)
  8855. (move-end-of-line 1) (activate-mark)
  8856. (let (current-prefix-arg)
  8857. (call-interactively 'org-store-link))
  8858. (move-beginning-of-line 2)
  8859. (set-mark (point)))))
  8860. (org-with-limited-levels
  8861. (setq org-store-link-plist nil)
  8862. (let (link cpltxt desc description search
  8863. txt custom-id agenda-link sfuns sfunsn)
  8864. (cond
  8865. ;; Store a link using an external link type
  8866. ((and (not (equal arg '(16)))
  8867. (setq sfuns
  8868. (delq
  8869. nil (mapcar (lambda (f)
  8870. (let (fs) (if (funcall f) (push f fs))))
  8871. (org-store-link-functions)))
  8872. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8873. (or (and (cdr sfuns)
  8874. (funcall (intern
  8875. (completing-read
  8876. "Which function for creating the link? "
  8877. sfunsn nil t (car sfunsn)))))
  8878. (funcall (caar sfuns)))
  8879. (setq link (plist-get org-store-link-plist :link)
  8880. desc (or (plist-get org-store-link-plist
  8881. :description)
  8882. link))))
  8883. ;; Store a link from a source code buffer.
  8884. ((org-src-edit-buffer-p)
  8885. (cond
  8886. ((save-excursion
  8887. (beginning-of-line)
  8888. (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
  8889. "[ \t]*$")))
  8890. (setq link (format "(%s)" (match-string-no-properties 1))))
  8891. ((called-interactively-p 'any)
  8892. (let (label)
  8893. (while (or (not label)
  8894. (org-with-wide-buffer
  8895. (goto-char (point-min))
  8896. (re-search-forward
  8897. (regexp-quote (format org-coderef-label-format label))
  8898. nil t)))
  8899. (when label (message "Label exists already") (sit-for 2))
  8900. (setq label (read-string "Code line label: " label)))
  8901. (end-of-line)
  8902. (setq link (format org-coderef-label-format label))
  8903. (let ((gc (- 79 (length link))))
  8904. (if (< (current-column) gc) (org-move-to-column gc t)
  8905. (insert " ")))
  8906. (insert link)
  8907. (setq link (concat "(" label ")") desc nil)))
  8908. (t (setq link nil))))
  8909. ;; We are in the agenda, link to referenced location
  8910. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8911. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8912. (get-text-property (point) 'org-marker))))
  8913. (when m
  8914. (org-with-point-at m
  8915. (setq agenda-link
  8916. (if (called-interactively-p 'any)
  8917. (call-interactively 'org-store-link)
  8918. (org-store-link nil)))))))
  8919. ((eq major-mode 'calendar-mode)
  8920. (let ((cd (calendar-cursor-to-date)))
  8921. (setq link
  8922. (format-time-string
  8923. (car org-time-stamp-formats)
  8924. (apply 'encode-time
  8925. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8926. nil nil nil))))
  8927. (org-store-link-props :type "calendar" :date cd)))
  8928. ((eq major-mode 'help-mode)
  8929. (setq link (concat "help:" (save-excursion
  8930. (goto-char (point-min))
  8931. (looking-at "^[^ ]+")
  8932. (match-string 0))))
  8933. (org-store-link-props :type "help"))
  8934. ((eq major-mode 'w3-mode)
  8935. (setq cpltxt (if (and (buffer-name)
  8936. (not (string-match "Untitled" (buffer-name))))
  8937. (buffer-name)
  8938. (url-view-url t))
  8939. link (url-view-url t))
  8940. (org-store-link-props :type "w3" :url (url-view-url t)))
  8941. ((eq major-mode 'image-mode)
  8942. (setq cpltxt (concat "file:"
  8943. (abbreviate-file-name buffer-file-name))
  8944. link cpltxt)
  8945. (org-store-link-props :type "image" :file buffer-file-name))
  8946. ;; In dired, store a link to the file of the current line
  8947. ((derived-mode-p 'dired-mode)
  8948. (let ((file (dired-get-filename nil t)))
  8949. (setq file (if file
  8950. (abbreviate-file-name
  8951. (expand-file-name (dired-get-filename nil t)))
  8952. ;; otherwise, no file so use current directory.
  8953. default-directory))
  8954. (setq cpltxt (concat "file:" file)
  8955. link cpltxt)))
  8956. ((setq search (run-hook-with-args-until-success
  8957. 'org-create-file-search-functions))
  8958. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8959. "::" search))
  8960. (setq cpltxt (or description link)))
  8961. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8962. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8963. (cond
  8964. ;; Store a link using the target at point
  8965. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8966. (setq cpltxt
  8967. (concat "file:"
  8968. (abbreviate-file-name
  8969. (buffer-file-name (buffer-base-buffer)))
  8970. "::" (match-string 1))
  8971. link cpltxt))
  8972. ((and (featurep 'org-id)
  8973. (or (eq org-id-link-to-org-use-id t)
  8974. (and (called-interactively-p 'any)
  8975. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8976. (and (eq org-id-link-to-org-use-id
  8977. 'create-if-interactive-and-no-custom-id)
  8978. (not custom-id))))
  8979. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8980. ;; Store a link using the ID at point
  8981. (setq link (condition-case nil
  8982. (prog1 (org-id-store-link)
  8983. (setq desc (or (plist-get org-store-link-plist
  8984. :description)
  8985. "")))
  8986. (error
  8987. ;; Probably before first headline, link only to file
  8988. (concat "file:"
  8989. (abbreviate-file-name
  8990. (buffer-file-name (buffer-base-buffer))))))))
  8991. (t
  8992. ;; Just link to current headline
  8993. (setq cpltxt (concat "file:"
  8994. (abbreviate-file-name
  8995. (buffer-file-name (buffer-base-buffer)))))
  8996. ;; Add a context search string
  8997. (when (org-xor org-context-in-file-links arg)
  8998. (let* ((element (org-element-at-point))
  8999. (name (org-element-property :name element)))
  9000. (setq txt (cond
  9001. ((org-at-heading-p) nil)
  9002. (name)
  9003. ((org-region-active-p)
  9004. (buffer-substring (region-beginning) (region-end)))))
  9005. (when (or (null txt) (string-match "\\S-" txt))
  9006. (setq cpltxt
  9007. (concat cpltxt "::"
  9008. (condition-case nil
  9009. (org-make-org-heading-search-string txt)
  9010. (error "")))
  9011. desc (or name
  9012. (nth 4 (ignore-errors (org-heading-components)))
  9013. "NONE")))))
  9014. (when (string-match "::\\'" cpltxt)
  9015. (setq cpltxt (substring cpltxt 0 -2)))
  9016. (setq link cpltxt))))
  9017. ((buffer-file-name (buffer-base-buffer))
  9018. ;; Just link to this file here.
  9019. (setq cpltxt (concat "file:"
  9020. (abbreviate-file-name
  9021. (buffer-file-name (buffer-base-buffer)))))
  9022. ;; Add a context string.
  9023. (when (org-xor org-context-in-file-links arg)
  9024. (setq txt (if (org-region-active-p)
  9025. (buffer-substring (region-beginning) (region-end))
  9026. (buffer-substring (point-at-bol) (point-at-eol))))
  9027. ;; Only use search option if there is some text.
  9028. (when (string-match "\\S-" txt)
  9029. (setq cpltxt
  9030. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  9031. desc "NONE")))
  9032. (setq link cpltxt))
  9033. ((called-interactively-p 'interactive)
  9034. (user-error "No method for storing a link from this buffer"))
  9035. (t (setq link nil)))
  9036. ;; We're done setting link and desc, clean up
  9037. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9038. (setq link (or link cpltxt)
  9039. desc (or desc cpltxt))
  9040. (cond ((not desc))
  9041. ((equal desc "NONE") (setq desc nil))
  9042. (t (setq desc
  9043. (replace-regexp-in-string
  9044. org-bracket-link-analytic-regexp
  9045. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9046. desc))))
  9047. ;; Return the link
  9048. (if (not (and (or (called-interactively-p 'any)
  9049. executing-kbd-macro)
  9050. link))
  9051. (or agenda-link (and link (org-make-link-string link desc)))
  9052. (push (list link desc) org-stored-links)
  9053. (message "Stored: %s" (or desc link))
  9054. (when custom-id
  9055. (setq link (concat "file:" (abbreviate-file-name
  9056. (buffer-file-name)) "::#" custom-id))
  9057. (push (list link desc) org-stored-links))
  9058. (car org-stored-links))))))
  9059. (defun org-store-link-props (&rest plist)
  9060. "Store link properties, extract names, addresses and dates."
  9061. (let ((x (plist-get plist :from)))
  9062. (when x
  9063. (let ((adr (mail-extract-address-components x)))
  9064. (setq plist (plist-put plist :fromname (car adr)))
  9065. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9066. (let ((x (plist-get plist :to)))
  9067. (when x
  9068. (let ((adr (mail-extract-address-components x)))
  9069. (setq plist (plist-put plist :toname (car adr)))
  9070. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9071. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9072. (when x
  9073. (setq plist (plist-put plist :date-timestamp
  9074. (format-time-string
  9075. (org-time-stamp-format t) x)))
  9076. (setq plist (plist-put plist :date-timestamp-inactive
  9077. (format-time-string
  9078. (org-time-stamp-format t t) x)))))
  9079. (let ((from (plist-get plist :from))
  9080. (to (plist-get plist :to)))
  9081. (when (and from to org-from-is-user-regexp)
  9082. (setq plist
  9083. (plist-put plist :fromto
  9084. (if (string-match org-from-is-user-regexp from)
  9085. (concat "to %t")
  9086. (concat "from %f"))))))
  9087. (setq org-store-link-plist plist))
  9088. (defun org-add-link-props (&rest plist)
  9089. "Add these properties to the link property list."
  9090. (let (key value)
  9091. (while plist
  9092. (setq key (pop plist) value (pop plist))
  9093. (setq org-store-link-plist
  9094. (plist-put org-store-link-plist key value)))))
  9095. (defun org-email-link-description (&optional fmt)
  9096. "Return the description part of an email link.
  9097. This takes information from `org-store-link-plist' and formats it
  9098. according to FMT (default from `org-email-link-description-format')."
  9099. (setq fmt (or fmt org-email-link-description-format))
  9100. (let* ((p org-store-link-plist)
  9101. (to (plist-get p :toaddress))
  9102. (from (plist-get p :fromaddress))
  9103. (table
  9104. (list
  9105. (cons "%c" (plist-get p :fromto))
  9106. (cons "%F" (plist-get p :from))
  9107. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9108. (cons "%T" (plist-get p :to))
  9109. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9110. (cons "%s" (plist-get p :subject))
  9111. (cons "%d" (plist-get p :date))
  9112. (cons "%m" (plist-get p :message-id)))))
  9113. (when (string-match "%c" fmt)
  9114. ;; Check if the user wrote this message
  9115. (if (and org-from-is-user-regexp from to
  9116. (save-match-data (string-match org-from-is-user-regexp from)))
  9117. (setq fmt (replace-match "to %t" t t fmt))
  9118. (setq fmt (replace-match "from %f" t t fmt))))
  9119. (org-replace-escapes fmt table)))
  9120. (defun org-make-org-heading-search-string (&optional string)
  9121. "Make search string for the current headline or STRING."
  9122. (let ((s (or string
  9123. (and (derived-mode-p 'org-mode)
  9124. (save-excursion
  9125. (org-back-to-heading t)
  9126. (org-element-property :raw-value (org-element-at-point))))))
  9127. (lines org-context-in-file-links))
  9128. (or string (setq s (concat "*" s))) ; Add * for headlines
  9129. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9130. (when (and string (integerp lines) (> lines 0))
  9131. (let ((slines (org-split-string s "\n")))
  9132. (when (< lines (length slines))
  9133. (setq s (mapconcat
  9134. 'identity
  9135. (reverse (nthcdr (- (length slines) lines)
  9136. (reverse slines))) "\n")))))
  9137. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9138. (defun org-make-link-string (link &optional description)
  9139. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9140. (unless (org-string-nw-p link) (error "Empty link"))
  9141. (let ((uri (cond ((string-match org-link-types-re link)
  9142. (concat (match-string 1 link)
  9143. (org-link-escape (substring link (match-end 1)))))
  9144. ;; For readability, url-encode internal links only
  9145. ;; when absolutely needed (i.e, when they contain
  9146. ;; square brackets). File links however, are
  9147. ;; encoded since, e.g., spaces are significant.
  9148. ((or (file-name-absolute-p link)
  9149. (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
  9150. (org-link-escape link))
  9151. (t link)))
  9152. (description
  9153. (and (org-string-nw-p description)
  9154. ;; Remove brackets from description, as they are fatal.
  9155. (replace-regexp-in-string
  9156. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9157. (org-trim description)))))
  9158. (format "[[%s]%s]"
  9159. uri
  9160. (if description (format "[%s]" description) ""))))
  9161. (defconst org-link-escape-chars
  9162. ;;%20 %5B %5D %25
  9163. '(?\s ?\[ ?\] ?%)
  9164. "List of characters that should be escaped in a link when stored to Org.
  9165. This is the list that is used for internal purposes.")
  9166. (defun org-link-escape (text &optional table merge)
  9167. "Return percent escaped representation of TEXT.
  9168. TEXT is a string with the text to escape.
  9169. Optional argument TABLE is a list with characters that should be
  9170. escaped. When nil, `org-link-escape-chars' is used.
  9171. If optional argument MERGE is set, merge TABLE into
  9172. `org-link-escape-chars'."
  9173. (let ((characters-to-encode
  9174. (cond ((null table) org-link-escape-chars)
  9175. (merge (append org-link-escape-chars table))
  9176. (t table))))
  9177. (mapconcat
  9178. (lambda (c)
  9179. (if (or (memq c characters-to-encode)
  9180. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9181. (mapconcat (lambda (e) (format "%%%.2X" e))
  9182. (or (encode-coding-char c 'utf-8)
  9183. (error "Unable to percent escape character: %c" c))
  9184. "")
  9185. (char-to-string c)))
  9186. text "")))
  9187. (defun org-link-unescape (str)
  9188. "Unhex hexified Unicode parts in string STR.
  9189. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9190. reciprocal of `org-link-escape', which see."
  9191. (if (org-string-nw-p str)
  9192. (replace-regexp-in-string
  9193. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9194. str))
  9195. (defun org-link-unescape-compound (hex)
  9196. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9197. Note: this function also decodes single byte encodings like
  9198. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9199. (save-match-data
  9200. (let* ((bytes (cdr (split-string hex "%")))
  9201. (ret "")
  9202. (eat 0)
  9203. (sum 0))
  9204. (while bytes
  9205. (let* ((val (string-to-number (pop bytes) 16))
  9206. (shift-xor
  9207. (if (= 0 eat)
  9208. (cond
  9209. ((>= val 252) (cons 6 252))
  9210. ((>= val 248) (cons 5 248))
  9211. ((>= val 240) (cons 4 240))
  9212. ((>= val 224) (cons 3 224))
  9213. ((>= val 192) (cons 2 192))
  9214. (t (cons 0 0)))
  9215. (cons 6 128))))
  9216. (when (>= val 192) (setq eat (car shift-xor)))
  9217. (setq val (logxor val (cdr shift-xor)))
  9218. (setq sum (+ (lsh sum (car shift-xor)) val))
  9219. (when (> eat 0) (setq eat (- eat 1)))
  9220. (cond
  9221. ((= 0 eat) ;multi byte
  9222. (setq ret (concat ret (char-to-string sum)))
  9223. (setq sum 0))
  9224. ((not bytes) ; single byte(s)
  9225. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9226. ret)))
  9227. (defun org-link-unescape-single-byte-sequence (hex)
  9228. "Unhexify hex-encoded single byte character sequences."
  9229. (mapconcat (lambda (byte)
  9230. (char-to-string (string-to-number byte 16)))
  9231. (cdr (split-string hex "%")) ""))
  9232. (defun org-xor (a b)
  9233. "Exclusive or."
  9234. (if a (not b) b))
  9235. (defun org-fixup-message-id-for-http (s)
  9236. "Replace special characters in a message id, so it can be used in an http query."
  9237. (when (string-match "%" s)
  9238. (setq s (mapconcat (lambda (c)
  9239. (if (eq c ?%)
  9240. "%25"
  9241. (char-to-string c)))
  9242. s "")))
  9243. (while (string-match "<" s)
  9244. (setq s (replace-match "%3C" t t s)))
  9245. (while (string-match ">" s)
  9246. (setq s (replace-match "%3E" t t s)))
  9247. (while (string-match "@" s)
  9248. (setq s (replace-match "%40" t t s)))
  9249. s)
  9250. (defun org-link-prettify (link)
  9251. "Return a human-readable representation of LINK.
  9252. The car of LINK must be a raw link.
  9253. The cdr of LINK must be either a link description or nil."
  9254. (let ((desc (or (cadr link) "<no description>")))
  9255. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9256. "<" (car link) ">")))
  9257. ;;;###autoload
  9258. (defun org-insert-link-global ()
  9259. "Insert a link like Org-mode does.
  9260. This command can be called in any mode to insert a link in Org-mode syntax."
  9261. (interactive)
  9262. (org-load-modules-maybe)
  9263. (org-run-like-in-org-mode 'org-insert-link))
  9264. (defun org-insert-all-links (arg &optional pre post)
  9265. "Insert all links in `org-stored-links'.
  9266. When a universal prefix, do not delete the links from `org-stored-links'.
  9267. When `ARG' is a number, insert the last N link(s).
  9268. `PRE' and `POST' are optional arguments to define a string to
  9269. prepend or to append."
  9270. (interactive "P")
  9271. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9272. (links (copy-sequence org-stored-links))
  9273. (pr (or pre "- "))
  9274. (po (or post "\n"))
  9275. (cnt 1) l)
  9276. (if (null org-stored-links)
  9277. (message "No link to insert")
  9278. (while (and (or (listp arg) (>= arg cnt))
  9279. (setq l (if (listp arg)
  9280. (pop links)
  9281. (pop org-stored-links))))
  9282. (setq cnt (1+ cnt))
  9283. (insert pr)
  9284. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9285. (insert po)))))
  9286. (defun org-insert-last-stored-link (arg)
  9287. "Insert the last link stored in `org-stored-links'."
  9288. (interactive "p")
  9289. (org-insert-all-links arg "" "\n"))
  9290. (defun org-link-fontify-links-to-this-file ()
  9291. "Fontify links to the current file in `org-stored-links'."
  9292. (let ((f (buffer-file-name)) a b)
  9293. (setq a (mapcar (lambda(l)
  9294. (let ((ll (car l)))
  9295. (when (and (string-match "^file:\\(.+\\)::" ll)
  9296. (equal f (expand-file-name (match-string 1 ll))))
  9297. ll)))
  9298. org-stored-links))
  9299. (when (featurep 'org-id)
  9300. (setq b (mapcar (lambda(l)
  9301. (let ((ll (car l)))
  9302. (when (and (string-match "^id:\\(.+\\)$" ll)
  9303. (equal f (expand-file-name
  9304. (or (org-id-find-id-file
  9305. (match-string 1 ll)) ""))))
  9306. ll)))
  9307. org-stored-links)))
  9308. (mapcar (lambda(l)
  9309. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9310. (delq nil (append a b)))))
  9311. (defvar org--links-history nil)
  9312. (defun org-insert-link (&optional complete-file link-location default-description)
  9313. "Insert a link. At the prompt, enter the link.
  9314. Completion can be used to insert any of the link protocol prefixes like
  9315. http or ftp in use.
  9316. The history can be used to select a link previously stored with
  9317. `org-store-link'. When the empty string is entered (i.e. if you just
  9318. press RET at the prompt), the link defaults to the most recently
  9319. stored link. As SPC triggers completion in the minibuffer, you need to
  9320. use M-SPC or C-q SPC to force the insertion of a space character.
  9321. You will also be prompted for a description, and if one is given, it will
  9322. be displayed in the buffer instead of the link.
  9323. If there is already a link at point, this command will allow you to edit link
  9324. and description parts.
  9325. With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
  9326. be selected using completion. The path to the file will be relative to the
  9327. current directory if the file is in the current directory or a subdirectory.
  9328. Otherwise, the link will be the absolute path as completed in the minibuffer
  9329. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9330. option `org-link-file-path-type'.
  9331. With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
  9332. the current directory or below.
  9333. With three \\[universal-argument] prefixes, negate the meaning of
  9334. `org-keep-stored-link-after-insertion'.
  9335. If `org-make-link-description-function' is non-nil, this function will be
  9336. called with the link target, and the result will be the default
  9337. link description.
  9338. If the LINK-LOCATION parameter is non-nil, this value will be
  9339. used as the link location instead of reading one interactively.
  9340. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9341. be used as the default description."
  9342. (interactive "P")
  9343. (let* ((wcf (current-window-configuration))
  9344. (origbuf (current-buffer))
  9345. (region (when (org-region-active-p)
  9346. (buffer-substring (region-beginning) (region-end))))
  9347. (remove (and region (list (region-beginning) (region-end))))
  9348. (desc region)
  9349. (link link-location)
  9350. (abbrevs org-link-abbrev-alist-local)
  9351. entry all-prefixes auto-desc)
  9352. (cond
  9353. (link-location) ; specified by arg, just use it.
  9354. ((org-in-regexp org-bracket-link-regexp 1)
  9355. ;; We do have a link at point, and we are going to edit it.
  9356. (setq remove (list (match-beginning 0) (match-end 0)))
  9357. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9358. (setq link (read-string "Link: "
  9359. (org-link-unescape
  9360. (match-string-no-properties 1)))))
  9361. ((or (org-in-regexp org-angle-link-re)
  9362. (org-in-regexp org-plain-link-re))
  9363. ;; Convert to bracket link
  9364. (setq remove (list (match-beginning 0) (match-end 0))
  9365. link (read-string "Link: "
  9366. (org-remove-angle-brackets (match-string 0)))))
  9367. ((member complete-file '((4) (16)))
  9368. ;; Completing read for file names.
  9369. (setq link (org-file-complete-link complete-file)))
  9370. (t
  9371. ;; Read link, with completion for stored links.
  9372. (org-link-fontify-links-to-this-file)
  9373. (org-switch-to-buffer-other-window "*Org Links*")
  9374. (with-current-buffer "*Org Links*"
  9375. (erase-buffer)
  9376. (insert "Insert a link.
  9377. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9378. (when org-stored-links
  9379. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9380. (insert (mapconcat 'org-link-prettify
  9381. (reverse org-stored-links) "\n")))
  9382. (goto-char (point-min)))
  9383. (let ((cw (selected-window)))
  9384. (select-window (get-buffer-window "*Org Links*" 'visible))
  9385. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9386. (unless (pos-visible-in-window-p (point-max))
  9387. (org-fit-window-to-buffer))
  9388. (and (window-live-p cw) (select-window cw)))
  9389. (setq all-prefixes (append (mapcar 'car abbrevs)
  9390. (mapcar 'car org-link-abbrev-alist)
  9391. (org-link-types)))
  9392. (unwind-protect
  9393. ;; Fake a link history, containing the stored links.
  9394. (let ((org--links-history
  9395. (append (mapcar #'car org-stored-links)
  9396. org-insert-link-history)))
  9397. (setq link
  9398. (org-completing-read
  9399. "Link: "
  9400. (append
  9401. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9402. (mapcar #'car org-stored-links))
  9403. nil nil nil
  9404. 'org--links-history
  9405. (caar org-stored-links)))
  9406. (unless (org-string-nw-p link) (user-error "No link selected"))
  9407. (dolist (l org-stored-links)
  9408. (when (equal link (cadr l))
  9409. (setq link (car l))
  9410. (setq auto-desc t)))
  9411. (when (or (member link all-prefixes)
  9412. (and (equal ":" (substring link -1))
  9413. (member (substring link 0 -1) all-prefixes)
  9414. (setq link (substring link 0 -1))))
  9415. (setq link (with-current-buffer origbuf
  9416. (org-link-try-special-completion link)))))
  9417. (set-window-configuration wcf)
  9418. (kill-buffer "*Org Links*"))
  9419. (setq entry (assoc link org-stored-links))
  9420. (or entry (push link org-insert-link-history))
  9421. (setq desc (or desc (nth 1 entry)))))
  9422. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9423. (not org-keep-stored-link-after-insertion))
  9424. (setq org-stored-links (delq (assoc link org-stored-links)
  9425. org-stored-links)))
  9426. (when (and (string-match org-plain-link-re link)
  9427. (not (string-match org-ts-regexp link)))
  9428. ;; URL-like link, normalize the use of angular brackets.
  9429. (setq link (org-remove-angle-brackets link)))
  9430. ;; Check if we are linking to the current file with a search
  9431. ;; option If yes, simplify the link by using only the search
  9432. ;; option.
  9433. (when (and buffer-file-name
  9434. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9435. (let* ((path (match-string 1 link))
  9436. (case-fold-search nil)
  9437. (search (match-string 2 link)))
  9438. (save-match-data
  9439. (when (equal (file-truename buffer-file-name) (file-truename path))
  9440. ;; We are linking to this same file, with a search option
  9441. (setq link search)))))
  9442. ;; Check if we can/should use a relative path. If yes, simplify the link
  9443. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9444. (let* ((type (match-string 1 link))
  9445. (path (match-string 2 link))
  9446. (origpath path)
  9447. (case-fold-search nil))
  9448. (cond
  9449. ((or (eq org-link-file-path-type 'absolute)
  9450. (equal complete-file '(16)))
  9451. (setq path (abbreviate-file-name (expand-file-name path))))
  9452. ((eq org-link-file-path-type 'noabbrev)
  9453. (setq path (expand-file-name path)))
  9454. ((eq org-link-file-path-type 'relative)
  9455. (setq path (file-relative-name path)))
  9456. (t
  9457. (save-match-data
  9458. (if (string-match (concat "^" (regexp-quote
  9459. (expand-file-name
  9460. (file-name-as-directory
  9461. default-directory))))
  9462. (expand-file-name path))
  9463. ;; We are linking a file with relative path name.
  9464. (setq path (substring (expand-file-name path)
  9465. (match-end 0)))
  9466. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9467. (setq link (concat type path))
  9468. (when (equal desc origpath)
  9469. (setq desc path))))
  9470. (if org-make-link-description-function
  9471. (setq desc
  9472. (or (condition-case nil
  9473. (funcall org-make-link-description-function link desc)
  9474. (error (progn (message "Can't get link description from `%s'"
  9475. (symbol-name org-make-link-description-function))
  9476. (sit-for 2) nil)))
  9477. (read-string "Description: " default-description)))
  9478. (if default-description (setq desc default-description)
  9479. (setq desc (or (and auto-desc desc)
  9480. (read-string "Description: " desc)))))
  9481. (unless (string-match "\\S-" desc) (setq desc nil))
  9482. (when remove (apply 'delete-region remove))
  9483. (insert (org-make-link-string link desc))
  9484. ;; Redisplay so as the new link has proper invisible characters.
  9485. (sit-for 0)))
  9486. (defun org-link-try-special-completion (type)
  9487. "If there is completion support for link type TYPE, offer it."
  9488. (let ((fun (org-link-get-parameter type :complete)))
  9489. (if (functionp fun)
  9490. (funcall fun)
  9491. (read-string "Link (no completion support): " (concat type ":")))))
  9492. (defun org-file-complete-link (&optional arg)
  9493. "Create a file link using completion."
  9494. (let ((file (read-file-name "File: "))
  9495. (pwd (file-name-as-directory (expand-file-name ".")))
  9496. (pwd1 (file-name-as-directory (abbreviate-file-name
  9497. (expand-file-name ".")))))
  9498. (cond ((equal arg '(16))
  9499. (concat "file:"
  9500. (abbreviate-file-name (expand-file-name file))))
  9501. ((string-match
  9502. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9503. (concat "file:" (match-string 1 file)))
  9504. ((string-match
  9505. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9506. (expand-file-name file))
  9507. (concat "file:"
  9508. (match-string 1 (expand-file-name file))))
  9509. (t (concat "file:" file)))))
  9510. (defun org-completing-read (&rest args)
  9511. "Completing-read with SPACE being a normal character."
  9512. (let ((enable-recursive-minibuffers t)
  9513. (minibuffer-local-completion-map
  9514. (copy-keymap minibuffer-local-completion-map)))
  9515. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9516. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9517. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9518. 'org-time-stamp-inactive)
  9519. (apply #'completing-read args)))
  9520. ;;; Opening/following a link
  9521. (defvar org-link-search-failed nil)
  9522. (defvar org-open-link-functions nil
  9523. "Hook for functions finding a plain text link.
  9524. These functions must take a single argument, the link content.
  9525. They will be called for links that look like [[link text][description]]
  9526. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9527. like a filename (e.g. \"./blue.png\").
  9528. These functions will be called *before* Org attempts to resolve the
  9529. link by doing text searches in the current buffer - so if you want a
  9530. link \"[[target]]\" to still find \"<<target>>\", your function should
  9531. handle this as a special case.
  9532. When the function does handle the link, it must return a non-nil value.
  9533. If it decides that it is not responsible for this link, it must return
  9534. nil to indicate that that Org-mode can continue with other options
  9535. like exact and fuzzy text search.")
  9536. (defun org-next-link (&optional search-backward)
  9537. "Move forward to the next link.
  9538. If the link is in hidden text, expose it."
  9539. (interactive "P")
  9540. (when (and org-link-search-failed (eq this-command last-command))
  9541. (goto-char (point-min))
  9542. (message "Link search wrapped back to beginning of buffer"))
  9543. (setq org-link-search-failed nil)
  9544. (let* ((pos (point))
  9545. (ct (org-context))
  9546. (a (assoc :link ct))
  9547. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9548. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9549. ((looking-at org-any-link-re)
  9550. ;; Don't stay stuck at link without an org-link face
  9551. (forward-char (if search-backward -1 1))))
  9552. (if (funcall srch-fun org-any-link-re nil t)
  9553. (progn
  9554. (goto-char (match-beginning 0))
  9555. (when (outline-invisible-p) (org-show-context)))
  9556. (goto-char pos)
  9557. (setq org-link-search-failed t)
  9558. (message "No further link found"))))
  9559. (defun org-previous-link ()
  9560. "Move backward to the previous link.
  9561. If the link is in hidden text, expose it."
  9562. (interactive)
  9563. (funcall 'org-next-link t))
  9564. (defun org-translate-link (s)
  9565. "Translate a link string if a translation function has been defined."
  9566. (with-temp-buffer
  9567. (insert (org-trim s))
  9568. (org-trim (org-element-interpret-data (org-element-context)))))
  9569. (defun org-translate-link-from-planner (type path)
  9570. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9571. This is still an experimental function, your mileage may vary."
  9572. (cond
  9573. ((member type '("http" "https" "news" "ftp"))
  9574. ;; standard Internet links are the same.
  9575. nil)
  9576. ((and (equal type "irc") (string-match "^//" path))
  9577. ;; Planner has two / at the beginning of an irc link, we have 1.
  9578. ;; We should have zero, actually....
  9579. (setq path (substring path 1)))
  9580. ((and (equal type "lisp") (string-match "^/" path))
  9581. ;; Planner has a slash, we do not.
  9582. (setq type "elisp" path (substring path 1)))
  9583. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9584. ;; A typical message link. Planner has the id after the final slash,
  9585. ;; we separate it with a hash mark
  9586. (setq path (concat (match-string 1 path) "#"
  9587. (org-remove-angle-brackets (match-string 2 path))))))
  9588. (cons type path))
  9589. (defun org-find-file-at-mouse (ev)
  9590. "Open file link or URL at mouse."
  9591. (interactive "e")
  9592. (mouse-set-point ev)
  9593. (org-open-at-point 'in-emacs))
  9594. (defun org-open-at-mouse (ev)
  9595. "Open file link or URL at mouse.
  9596. See the docstring of `org-open-file' for details."
  9597. (interactive "e")
  9598. (mouse-set-point ev)
  9599. (when (eq major-mode 'org-agenda-mode)
  9600. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9601. (org-open-at-point))
  9602. (defvar org-window-config-before-follow-link nil
  9603. "The window configuration before following a link.
  9604. This is saved in case the need arises to restore it.")
  9605. ;;;###autoload
  9606. (defun org-open-at-point-global ()
  9607. "Follow a link or time-stamp like Org mode does.
  9608. This command can be called in any mode to follow an external link
  9609. or a time-stamp that has Org mode syntax. Its behavior is
  9610. undefined when called on internal links (e.g., fuzzy links).
  9611. Raise an error when there is nothing to follow. "
  9612. (interactive)
  9613. (cond ((org-in-regexp org-any-link-re)
  9614. (org-open-link-from-string (match-string-no-properties 0)))
  9615. ((or (org-in-regexp org-ts-regexp-both nil t)
  9616. (org-in-regexp org-tsr-regexp-both nil t))
  9617. (org-follow-timestamp-link))
  9618. (t (user-error "No link found"))))
  9619. ;;;###autoload
  9620. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9621. "Open a link in the string S, as if it was in Org-mode."
  9622. (interactive "sLink: \nP")
  9623. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9624. (with-temp-buffer
  9625. (let ((org-inhibit-startup (not reference-buffer)))
  9626. (org-mode)
  9627. (insert s)
  9628. (goto-char (point-min))
  9629. (when reference-buffer
  9630. (setq org-link-abbrev-alist-local
  9631. (with-current-buffer reference-buffer
  9632. org-link-abbrev-alist-local)))
  9633. (org-open-at-point arg reference-buffer)))))
  9634. (defvar org-open-at-point-functions nil
  9635. "Hook that is run when following a link at point.
  9636. Functions in this hook must return t if they identify and follow
  9637. a link at point. If they don't find anything interesting at point,
  9638. they must return nil.")
  9639. (defvar org-link-search-inhibit-query nil)
  9640. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9641. (defun org--open-doi-link (path)
  9642. "Open a \"doi\" type link.
  9643. PATH is a the path to search for, as a string."
  9644. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9645. (defun org--open-elisp-link (path)
  9646. "Open a \"elisp\" type link.
  9647. PATH is the sexp to evaluate, as a string."
  9648. (let ((cmd path))
  9649. (if (or (and (org-string-nw-p
  9650. org-confirm-elisp-link-not-regexp)
  9651. (org-string-match-p
  9652. org-confirm-elisp-link-not-regexp cmd))
  9653. (not org-confirm-elisp-link-function)
  9654. (funcall org-confirm-elisp-link-function
  9655. (format "Execute \"%s\" as elisp? "
  9656. (org-add-props cmd nil
  9657. 'face 'org-warning))))
  9658. (message "%s => %s" cmd
  9659. (if (eq (string-to-char cmd) ?\()
  9660. (eval (read cmd))
  9661. (call-interactively (read cmd))))
  9662. (user-error "Abort"))))
  9663. (defun org--open-help-link (path)
  9664. "Open a \"help\" type link.
  9665. PATH is a symbol name, as a string."
  9666. (pcase (intern path)
  9667. ((and (pred fboundp) variable) (describe-function variable))
  9668. ((and (pred boundp) function) (describe-variable function))
  9669. (name (user-error "Unknown function or variable: %s" name))))
  9670. (defun org--open-shell-link (path)
  9671. "Open a \"shell\" type link.
  9672. PATH is the command to execute, as a string."
  9673. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9674. (cmd path))
  9675. (if (or (and (org-string-nw-p
  9676. org-confirm-shell-link-not-regexp)
  9677. (string-match
  9678. org-confirm-shell-link-not-regexp cmd))
  9679. (not org-confirm-shell-link-function)
  9680. (funcall org-confirm-shell-link-function
  9681. (format "Execute \"%s\" in shell? "
  9682. (org-add-props cmd nil
  9683. 'face 'org-warning))))
  9684. (progn
  9685. (message "Executing %s" cmd)
  9686. (shell-command cmd buf)
  9687. (when (featurep 'midnight)
  9688. (setq clean-buffer-list-kill-buffer-names
  9689. (cons (buffer-name buf)
  9690. clean-buffer-list-kill-buffer-names))))
  9691. (user-error "Abort"))))
  9692. (defun org-open-at-point (&optional arg reference-buffer)
  9693. "Open link, timestamp, footnote or tags at point.
  9694. When point is on a link, follow it. Normally, files will be
  9695. opened by an appropriate application. If the optional prefix
  9696. argument ARG is non-nil, Emacs will visit the file. With
  9697. a double prefix argument, try to open outside of Emacs, in the
  9698. application the system uses for this file type.
  9699. When point is on a timestamp, open the agenda at the day
  9700. specified.
  9701. When point is a footnote definition, move to the first reference
  9702. found. If it is on a reference, move to the associated
  9703. definition.
  9704. When point is on a headline, display a list of every link in the
  9705. entry, so it is possible to pick one, or all, of them. If point
  9706. is on a tag, call `org-tags-view' instead.
  9707. When optional argument REFERENCE-BUFFER is non-nil, it should
  9708. specify a buffer from where the link search should happen. This
  9709. is used internally by `org-open-link-from-string'.
  9710. On top of syntactically correct links, this function will open
  9711. the link at point in comments or comment blocks and the first
  9712. link in a property drawer line."
  9713. (interactive "P")
  9714. ;; On a code block, open block's results.
  9715. (unless (call-interactively 'org-babel-open-src-block-result)
  9716. (org-load-modules-maybe)
  9717. (setq org-window-config-before-follow-link (current-window-configuration))
  9718. (org-remove-occur-highlights nil nil t)
  9719. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9720. (let* ((context
  9721. ;; Only consider supported types, even if they are not
  9722. ;; the closest one.
  9723. (org-element-lineage
  9724. (org-element-context)
  9725. '(clock comment comment-block footnote-definition
  9726. footnote-reference headline inlinetask keyword link
  9727. node-property timestamp)
  9728. t))
  9729. (type (org-element-type context))
  9730. (value (org-element-property :value context)))
  9731. (cond
  9732. ((not context) (user-error "No link found"))
  9733. ;; Exception: open timestamps and links in properties
  9734. ;; drawers, keywords and comments.
  9735. ((memq type '(comment comment-block keyword node-property))
  9736. (call-interactively #'org-open-at-point-global))
  9737. ;; On a headline or an inlinetask, but not on a timestamp,
  9738. ;; a link, a footnote reference or on tags.
  9739. ((and (memq type '(headline inlinetask))
  9740. ;; Not on tags.
  9741. (progn (save-excursion (beginning-of-line)
  9742. (looking-at org-complex-heading-regexp))
  9743. (or (not (match-beginning 5))
  9744. (< (point) (match-beginning 5)))))
  9745. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9746. (links (car data))
  9747. (links-end (cdr data)))
  9748. (if links
  9749. (dolist (link (if (stringp links) (list links) links))
  9750. (search-forward link nil links-end)
  9751. (goto-char (match-beginning 0))
  9752. (org-open-at-point))
  9753. (require 'org-attach)
  9754. (org-attach-reveal 'if-exists))))
  9755. ;; On a clock line, make sure point is on the timestamp
  9756. ;; before opening it.
  9757. ((and (eq type 'clock)
  9758. value
  9759. (>= (point) (org-element-property :begin value))
  9760. (<= (point) (org-element-property :end value)))
  9761. (org-follow-timestamp-link))
  9762. ;; Do nothing on white spaces after an object.
  9763. ((>= (point)
  9764. (save-excursion
  9765. (goto-char (org-element-property :end context))
  9766. (skip-chars-backward " \t")
  9767. (point)))
  9768. (user-error "No link found"))
  9769. ((eq type 'timestamp) (org-follow-timestamp-link))
  9770. ;; On tags within a headline or an inlinetask.
  9771. ((and (memq type '(headline inlinetask))
  9772. (progn (save-excursion (beginning-of-line)
  9773. (looking-at org-complex-heading-regexp))
  9774. (and (match-beginning 5)
  9775. (>= (point) (match-beginning 5)))))
  9776. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9777. ((eq type 'link)
  9778. ;; When link is located within the description of another
  9779. ;; link (e.g., an inline image), always open the parent
  9780. ;; link.
  9781. (let* ((link (let ((up (org-element-property :parent context)))
  9782. (if (eq (org-element-type up) 'link) up context)))
  9783. (type (org-element-property :type link))
  9784. (path (org-link-unescape (org-element-property :path link))))
  9785. ;; Switch back to REFERENCE-BUFFER needed when called in
  9786. ;; a temporary buffer through `org-open-link-from-string'.
  9787. (with-current-buffer (or reference-buffer (current-buffer))
  9788. (cond
  9789. ((equal type "file")
  9790. (if (string-match "[*?{]" (file-name-nondirectory path))
  9791. (dired path)
  9792. ;; Look into `org-link-parameters' in order to find
  9793. ;; a DEDICATED-FUNCTION to open file. The function
  9794. ;; will be applied on raw link instead of parsed
  9795. ;; link due to the limitation in `org-add-link-type'
  9796. ;; ("open" function called with a single argument).
  9797. ;; If no such function is found, fallback to
  9798. ;; `org-open-file'.
  9799. ;;
  9800. ;; Note : "file+emacs" and "file+sys" types are
  9801. ;; hard-coded in order to escape the previous
  9802. ;; limitation.
  9803. (let* ((option (org-element-property :search-option link))
  9804. (app (org-element-property :application link))
  9805. (dedicated-function
  9806. (org-link-get-parameter
  9807. (if app (concat type "+" app) type)
  9808. :follow)))
  9809. (if dedicated-function
  9810. (funcall dedicated-function
  9811. (concat path
  9812. (and option (concat "::" option))))
  9813. (apply #'org-open-file
  9814. path
  9815. (cond (arg)
  9816. ((equal app "emacs") 'emacs)
  9817. ((equal app "sys") 'system))
  9818. (cond ((not option) nil)
  9819. ((org-string-match-p "\\`[0-9]+\\'" option)
  9820. (list (string-to-number option)))
  9821. (t (list nil
  9822. (org-link-unescape option)))))))))
  9823. ((functionp (org-link-get-parameter type :follow))
  9824. (funcall (org-link-get-parameter type :follow) path))
  9825. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9826. (unless (run-hook-with-args-until-success
  9827. 'org-open-link-functions path)
  9828. (if (not arg) (org-mark-ring-push)
  9829. (switch-to-buffer-other-window
  9830. (org-get-buffer-for-internal-link (current-buffer))))
  9831. (let ((destination
  9832. (org-with-wide-buffer
  9833. (if (equal type "radio")
  9834. (org-search-radio-target
  9835. (org-element-property :path link))
  9836. (org-link-search
  9837. (if (member type '("custom-id" "coderef"))
  9838. (org-element-property :raw-link link)
  9839. path)
  9840. ;; Prevent fuzzy links from matching
  9841. ;; themselves.
  9842. (and (equal type "fuzzy")
  9843. (+ 2 (org-element-property :begin link)))))
  9844. (point))))
  9845. (unless (and (<= (point-min) destination)
  9846. (>= (point-max) destination))
  9847. (widen))
  9848. (goto-char destination))))
  9849. (t (browse-url-at-point))))))
  9850. ;; On a footnote reference or at a footnote definition's label.
  9851. ((or (eq type 'footnote-reference)
  9852. (and (eq type 'footnote-definition)
  9853. (save-excursion
  9854. ;; Do not validate action when point is on the
  9855. ;; spaces right after the footnote label, in
  9856. ;; order to be on par with behaviour on links.
  9857. (skip-chars-forward " \t")
  9858. (let ((begin
  9859. (org-element-property :contents-begin context)))
  9860. (if begin (< (point) begin)
  9861. (= (org-element-property :post-affiliated context)
  9862. (line-beginning-position)))))))
  9863. (org-footnote-action))
  9864. (t (user-error "No link found")))))
  9865. (run-hook-with-args 'org-follow-link-hook)))
  9866. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9867. "Offer links in the current entry and return the selected link.
  9868. If there is only one link, return it.
  9869. If NTH is an integer, return the NTH link found.
  9870. If ZERO is a string, check also this string for a link, and if
  9871. there is one, return it."
  9872. (with-current-buffer buffer
  9873. (save-excursion
  9874. (save-restriction
  9875. (widen)
  9876. (goto-char marker)
  9877. (let ((cnt ?0)
  9878. have-zero end links link c)
  9879. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9880. (push (match-string 0 zero) links)
  9881. (setq cnt (1- cnt) have-zero t))
  9882. (save-excursion
  9883. (org-back-to-heading t)
  9884. (setq end (save-excursion (outline-next-heading) (point)))
  9885. (while (re-search-forward org-any-link-re end t)
  9886. (push (match-string 0) links))
  9887. (setq links (org-uniquify (reverse links))))
  9888. (cond
  9889. ((null links)
  9890. (message "No links"))
  9891. ((equal (length links) 1)
  9892. (setq link (car links)))
  9893. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9894. (setq link (nth (if have-zero nth (1- nth)) links)))
  9895. (t ; we have to select a link
  9896. (save-excursion
  9897. (save-window-excursion
  9898. (delete-other-windows)
  9899. (with-output-to-temp-buffer "*Select Link*"
  9900. (dolist (l links)
  9901. (cond
  9902. ((not (string-match org-bracket-link-regexp l))
  9903. (princ (format "[%c] %s\n" (cl-incf cnt)
  9904. (org-remove-angle-brackets l))))
  9905. ((match-end 3)
  9906. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9907. (match-string 3 l) (match-string 1 l))))
  9908. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9909. (match-string 1 l)))))))
  9910. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9911. (message "Select link to open, RET to open all:")
  9912. (setq c (read-char-exclusive))
  9913. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9914. (when (equal c ?q) (user-error "Abort"))
  9915. (if (equal c ?\C-m)
  9916. (setq link links)
  9917. (setq nth (- c ?0))
  9918. (when have-zero (setq nth (1+ nth)))
  9919. (unless (and (integerp nth) (>= (length links) nth))
  9920. (user-error "Invalid link selection"))
  9921. (setq link (nth (1- nth) links)))))
  9922. (cons link end))))))
  9923. ;; TODO: These functions are deprecated since `org-open-at-point'
  9924. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9925. (defun org-open-file-with-system (path)
  9926. "Open file at PATH using the system way of opening it."
  9927. (org-open-file path 'system))
  9928. (defun org-open-file-with-emacs (path)
  9929. "Open file at PATH in Emacs."
  9930. (org-open-file path 'emacs))
  9931. ;;; File search
  9932. (defvar org-create-file-search-functions nil
  9933. "List of functions to construct the right search string for a file link.
  9934. These functions are called in turn with point at the location to
  9935. which the link should point.
  9936. A function in the hook should first test if it would like to
  9937. handle this file type, for example by checking the `major-mode'
  9938. or the file extension. If it decides not to handle this file, it
  9939. should just return nil to give other functions a chance. If it
  9940. does handle the file, it must return the search string to be used
  9941. when following the link. The search string will be part of the
  9942. file link, given after a double colon, and `org-open-at-point'
  9943. will automatically search for it. If special measures must be
  9944. taken to make the search successful, another function should be
  9945. added to the companion hook `org-execute-file-search-functions',
  9946. which see.
  9947. A function in this hook may also use `setq' to set the variable
  9948. `description' to provide a suggestion for the descriptive text to
  9949. be used for this link when it gets inserted into an Org-mode
  9950. buffer with \\[org-insert-link].")
  9951. (defvar org-execute-file-search-functions nil
  9952. "List of functions to execute a file search triggered by a link.
  9953. Functions added to this hook must accept a single argument, the
  9954. search string that was part of the file link, the part after the
  9955. double colon. The function must first check if it would like to
  9956. handle this search, for example by checking the `major-mode' or
  9957. the file extension. If it decides not to handle this search, it
  9958. should just return nil to give other functions a chance. If it
  9959. does handle the search, it must return a non-nil value to keep
  9960. other functions from trying.
  9961. Each function can access the current prefix argument through the
  9962. variable `current-prefix-arg'. Note that a single prefix is used
  9963. to force opening a link in Emacs, so it may be good to only use a
  9964. numeric or double prefix to guide the search function.
  9965. In case this is needed, a function in this hook can also restore
  9966. the window configuration before `org-open-at-point' was called using:
  9967. \(set-window-configuration org-window-config-before-follow-link)")
  9968. (defun org-search-radio-target (target)
  9969. "Search a radio target matching TARGET in current buffer.
  9970. White spaces are not significant."
  9971. (let ((re (format "<<<%s>>>"
  9972. (mapconcat #'regexp-quote
  9973. (org-split-string target "[ \t\n]+")
  9974. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9975. (origin (point)))
  9976. (goto-char (point-min))
  9977. (catch :radio-match
  9978. (while (re-search-forward re nil t)
  9979. (backward-char)
  9980. (let ((object (org-element-context)))
  9981. (when (eq (org-element-type object) 'radio-target)
  9982. (goto-char (org-element-property :begin object))
  9983. (org-show-context 'link-search)
  9984. (throw :radio-match nil))))
  9985. (goto-char origin)
  9986. (user-error "No match for radio target: %s" target))))
  9987. (defun org-link-search (s &optional avoid-pos stealth)
  9988. "Search for a search string S.
  9989. If S starts with \"#\", it triggers a custom ID search.
  9990. If S is enclosed within parenthesis, it initiates a coderef
  9991. search.
  9992. If S is surrounded by forward slashes, it is interpreted as
  9993. a regular expression. In Org mode files, this will create an
  9994. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9995. to list matches. If the current buffer is in `dired-mode', grep
  9996. will be used to search in all files.
  9997. When AVOID-POS is given, ignore matches near that position.
  9998. When optional argument STEALTH is non-nil, do not modify
  9999. visibility around point, thus ignoring `org-show-context-detail'
  10000. variable.
  10001. Search is case-insensitive and ignores white spaces. Return type
  10002. of matched result, with is either `dedicated' or `fuzzy'."
  10003. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  10004. (let* ((case-fold-search t)
  10005. (origin (point))
  10006. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  10007. (words (org-split-string s "[ \t\n]+"))
  10008. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  10009. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  10010. type)
  10011. (cond
  10012. ;; Check if there are any special search functions.
  10013. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  10014. ((eq (string-to-char s) ?#)
  10015. ;; Look for a custom ID S if S starts with "#".
  10016. (let* ((id (substring normalized 1))
  10017. (match (org-find-property "CUSTOM_ID" id)))
  10018. (if match (progn (goto-char match) (setf type 'dedicated))
  10019. (error "No match for custom ID: %s" id))))
  10020. ((string-match "\\`(\\(.*\\))\\'" normalized)
  10021. ;; Look for coderef targets if S is enclosed within parenthesis.
  10022. (let ((coderef (match-string-no-properties 1 normalized))
  10023. (re (substring s-single-re 1 -1)))
  10024. (goto-char (point-min))
  10025. (catch :coderef-match
  10026. (while (re-search-forward re nil t)
  10027. (let ((element (org-element-at-point)))
  10028. (when (and (memq (org-element-type element)
  10029. '(example-block src-block))
  10030. ;; Build proper regexp according to current
  10031. ;; block's label format.
  10032. (let ((label-fmt
  10033. (regexp-quote
  10034. (or (org-element-property :label-fmt element)
  10035. org-coderef-label-format))))
  10036. (save-excursion
  10037. (beginning-of-line)
  10038. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  10039. (format label-fmt coderef))))))
  10040. (setq type 'dedicated)
  10041. (goto-char (match-beginning 1))
  10042. (throw :coderef-match nil))))
  10043. (goto-char origin)
  10044. (error "No match for coderef: %s" coderef))))
  10045. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10046. ;; Look for a regular expression.
  10047. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10048. (match-string 1 s)))
  10049. ;; Fuzzy links.
  10050. (t
  10051. (let ((starred (eq (string-to-char normalized) ?*)))
  10052. (cond
  10053. ;; Look for targets, only if not in a headline search.
  10054. ((and (not starred)
  10055. (let ((target (format "<<%s>>" s-multi-re)))
  10056. (catch :target-match
  10057. (goto-char (point-min))
  10058. (while (re-search-forward target nil t)
  10059. (backward-char)
  10060. (let ((context (org-element-context)))
  10061. (when (eq (org-element-type context) 'target)
  10062. (setq type 'dedicated)
  10063. (goto-char (org-element-property :begin context))
  10064. (throw :target-match t))))
  10065. nil))))
  10066. ;; Look for elements named after S, only if not in a headline
  10067. ;; search.
  10068. ((and (not starred)
  10069. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10070. (catch :name-match
  10071. (goto-char (point-min))
  10072. (while (re-search-forward name nil t)
  10073. (let ((element (org-element-at-point)))
  10074. (when (equal (org-split-string
  10075. (org-element-property :name element)
  10076. "[ \t]+")
  10077. words)
  10078. (setq type 'dedicated)
  10079. (beginning-of-line)
  10080. (throw :name-match t))))
  10081. nil))))
  10082. ;; Regular text search. Prefer headlines in Org mode
  10083. ;; buffers.
  10084. ((and (derived-mode-p 'org-mode)
  10085. (let* ((wspace "[ \t]")
  10086. (wspaceopt (concat wspace "*"))
  10087. (cookie (concat "\\(?:"
  10088. wspaceopt
  10089. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  10090. wspaceopt
  10091. "\\)"))
  10092. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10093. (re (concat
  10094. org-outline-regexp-bol
  10095. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  10096. "\\(?:\\[#.\\][ \t]+\\)?"
  10097. "\\(?:" org-comment-string "[ \t]+\\)?"
  10098. sep "?"
  10099. (let ((title (mapconcat #'regexp-quote
  10100. words
  10101. sep)))
  10102. (if starred (substring title 1) title))
  10103. sep "?"
  10104. "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
  10105. "[ \t]*$")))
  10106. (goto-char (point-min))
  10107. (re-search-forward re nil t)))
  10108. (goto-char (match-beginning 0))
  10109. (setq type 'dedicated))
  10110. ;; Offer to create non-existent headline depending on
  10111. ;; `org-link-search-must-match-exact-headline'.
  10112. ((and (derived-mode-p 'org-mode)
  10113. (not org-link-search-inhibit-query)
  10114. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10115. (yes-or-no-p "No match - create this as a new heading? "))
  10116. (goto-char (point-max))
  10117. (unless (bolp) (newline))
  10118. (org-insert-heading nil t t)
  10119. (insert s "\n")
  10120. (beginning-of-line 0))
  10121. ;; Only headlines are looked after. No need to process
  10122. ;; further: throw an error.
  10123. ((and (derived-mode-p 'org-mode)
  10124. (or starred org-link-search-must-match-exact-headline))
  10125. (goto-char origin)
  10126. (error "No match for fuzzy expression: %s" normalized))
  10127. ;; Regular text search.
  10128. ((catch :fuzzy-match
  10129. (goto-char (point-min))
  10130. (while (re-search-forward s-multi-re nil t)
  10131. ;; Skip match if it contains AVOID-POS or it is included
  10132. ;; in a link with a description but outside the
  10133. ;; description.
  10134. (unless (or (and avoid-pos
  10135. (<= (match-beginning 0) avoid-pos)
  10136. (> (match-end 0) avoid-pos))
  10137. (and (save-match-data
  10138. (org-in-regexp org-bracket-link-regexp))
  10139. (match-beginning 3)
  10140. (or (> (match-beginning 3) (point))
  10141. (<= (match-end 3) (point)))
  10142. (org-element-lineage
  10143. (save-match-data (org-element-context))
  10144. '(link) t)))
  10145. (goto-char (match-beginning 0))
  10146. (setq type 'fuzzy)
  10147. (throw :fuzzy-match t)))
  10148. nil))
  10149. ;; All failed. Throw an error.
  10150. (t (goto-char origin)
  10151. (error "No match for fuzzy expression: %s" normalized))))))
  10152. ;; Disclose surroundings of match, if appropriate.
  10153. (when (and (derived-mode-p 'org-mode) (not stealth))
  10154. (org-show-context 'link-search))
  10155. type))
  10156. (defun org-get-buffer-for-internal-link (buffer)
  10157. "Return a buffer to be used for displaying the link target of internal links."
  10158. (cond
  10159. ((not org-display-internal-link-with-indirect-buffer)
  10160. buffer)
  10161. ((string-match "(Clone)$" (buffer-name buffer))
  10162. (message "Buffer is already a clone, not making another one")
  10163. ;; we also do not modify visibility in this case
  10164. buffer)
  10165. (t ; make a new indirect buffer for displaying the link
  10166. (let* ((bn (buffer-name buffer))
  10167. (ibn (concat bn "(Clone)"))
  10168. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10169. (with-current-buffer ib (org-overview))
  10170. ib))))
  10171. (defun org-do-occur (regexp &optional cleanup)
  10172. "Call the Emacs command `occur'.
  10173. If CLEANUP is non-nil, remove the printout of the regular expression
  10174. in the *Occur* buffer. This is useful if the regex is long and not useful
  10175. to read."
  10176. (occur regexp)
  10177. (when cleanup
  10178. (let ((cwin (selected-window)) win beg end)
  10179. (when (setq win (get-buffer-window "*Occur*"))
  10180. (select-window win))
  10181. (goto-char (point-min))
  10182. (when (re-search-forward "match[a-z]+" nil t)
  10183. (setq beg (match-end 0))
  10184. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10185. (setq end (1- (match-beginning 0)))))
  10186. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10187. (goto-char (point-min))
  10188. (select-window cwin))))
  10189. ;;; The mark ring for links jumps
  10190. (defvar org-mark-ring nil
  10191. "Mark ring for positions before jumps in Org-mode.")
  10192. (defvar org-mark-ring-last-goto nil
  10193. "Last position in the mark ring used to go back.")
  10194. ;; Fill and close the ring
  10195. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10196. (dotimes (_ org-mark-ring-length)
  10197. (push (make-marker) org-mark-ring))
  10198. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10199. org-mark-ring)
  10200. (defun org-mark-ring-push (&optional pos buffer)
  10201. "Put the current position or POS into the mark ring and rotate it."
  10202. (interactive)
  10203. (setq pos (or pos (point)))
  10204. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10205. (move-marker (car org-mark-ring)
  10206. (or pos (point))
  10207. (or buffer (current-buffer)))
  10208. (message "%s"
  10209. (substitute-command-keys
  10210. "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
  10211. (defun org-mark-ring-goto (&optional n)
  10212. "Jump to the previous position in the mark ring.
  10213. With prefix arg N, jump back that many stored positions. When
  10214. called several times in succession, walk through the entire ring.
  10215. Org-mode commands jumping to a different position in the current file,
  10216. or to another Org-mode file, automatically push the old position
  10217. onto the ring."
  10218. (interactive "p")
  10219. (let (p m)
  10220. (if (eq last-command this-command)
  10221. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10222. (setq p org-mark-ring))
  10223. (setq org-mark-ring-last-goto p)
  10224. (setq m (car p))
  10225. (pop-to-buffer-same-window (marker-buffer m))
  10226. (goto-char m)
  10227. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10228. ;;; TODO: Use string-remove-prefix and -suffix once we only support
  10229. ;;; Emacs 24.4+
  10230. (defun org-remove-angle-brackets (s)
  10231. (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
  10232. (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
  10233. s)
  10234. (defun org-add-angle-brackets (s)
  10235. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10236. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10237. s)
  10238. (defun org-remove-double-quotes (s)
  10239. (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
  10240. (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
  10241. s)
  10242. ;;; Following specific links
  10243. (defvar org-agenda-buffer-tmp-name)
  10244. (defvar org-agenda-start-on-weekday)
  10245. (defun org-follow-timestamp-link ()
  10246. "Open an agenda view for the time-stamp date/range at point."
  10247. (cond
  10248. ((org-at-date-range-p t)
  10249. (let ((org-agenda-start-on-weekday)
  10250. (t1 (match-string 1))
  10251. (t2 (match-string 2)) tt1 tt2)
  10252. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10253. tt2 (time-to-days (org-time-string-to-time t2)))
  10254. (let ((org-agenda-buffer-tmp-name
  10255. (format "*Org Agenda(a:%s)"
  10256. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10257. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10258. ((org-at-timestamp-p t)
  10259. (let ((org-agenda-buffer-tmp-name
  10260. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10261. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10262. (substring (match-string 1) 0 10)))
  10263. 1)))
  10264. (t (error "This should not happen"))))
  10265. ;;; Following file links
  10266. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10267. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10268. (declare-function mailcap-mime-info
  10269. "mailcap" (string &optional request no-decode))
  10270. (defvar org-wait nil)
  10271. (defun org-open-file (path &optional in-emacs line search)
  10272. "Open the file at PATH.
  10273. First, this expands any special file name abbreviations. Then the
  10274. configuration variable `org-file-apps' is checked if it contains an
  10275. entry for this file type, and if yes, the corresponding command is launched.
  10276. If no application is found, Emacs simply visits the file.
  10277. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10278. With a double \\[universal-argument] \\[universal-argument] \
  10279. prefix arg, Org tries to avoid opening in Emacs
  10280. and to use an external application to visit the file.
  10281. Optional LINE specifies a line to go to, optional SEARCH a string
  10282. to search for. If LINE or SEARCH is given, the file will be
  10283. opened in Emacs, unless an entry from org-file-apps that makes
  10284. use of groups in a regexp matches.
  10285. If you want to change the way frames are used when following a
  10286. link, please customize `org-link-frame-setup'.
  10287. If the file does not exist, an error is thrown."
  10288. (let* ((file (if (equal path "")
  10289. buffer-file-name
  10290. (substitute-in-file-name (expand-file-name path))))
  10291. (file-apps (append org-file-apps (org-default-apps)))
  10292. (apps (cl-remove-if
  10293. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10294. (apps-dlink (cl-remove-if-not
  10295. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10296. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10297. (dirp (unless remp (file-directory-p file)))
  10298. (file (if (and dirp org-open-directory-means-index-dot-org)
  10299. (concat (file-name-as-directory file) "index.org")
  10300. file))
  10301. (a-m-a-p (assq 'auto-mode apps))
  10302. (dfile (downcase file))
  10303. ;; Reconstruct the original link from the PATH, LINE and
  10304. ;; SEARCH args.
  10305. (link (cond (line (concat file "::" (number-to-string line)))
  10306. (search (concat file "::" search))
  10307. (t file)))
  10308. (dlink (downcase link))
  10309. (old-buffer (current-buffer))
  10310. (old-pos (point))
  10311. (old-mode major-mode)
  10312. (ext
  10313. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10314. (match-string 1 dfile)))
  10315. cmd link-match-data)
  10316. (cond
  10317. ((member in-emacs '((16) system))
  10318. (setq cmd (cdr (assq 'system apps))))
  10319. (in-emacs (setq cmd 'emacs))
  10320. (t
  10321. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10322. (and dirp (cdr (assq 'directory apps)))
  10323. ;; First, try matching against apps-dlink if we
  10324. ;; get a match here, store the match data for
  10325. ;; later.
  10326. (let ((match (assoc-default dlink apps-dlink
  10327. 'string-match)))
  10328. (if match
  10329. (progn (setq link-match-data (match-data))
  10330. match)
  10331. (progn (setq in-emacs (or in-emacs line search))
  10332. nil))) ; if we have no match in apps-dlink,
  10333. ; always open the file in emacs if line or search
  10334. ; is given (for backwards compatibility)
  10335. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10336. 'string-match)
  10337. (cdr (assoc ext apps))
  10338. (cdr (assq t apps))))))
  10339. (when (eq cmd 'system)
  10340. (setq cmd (cdr (assoc 'system apps))))
  10341. (when (eq cmd 'default)
  10342. (setq cmd (cdr (assoc t apps))))
  10343. (when (eq cmd 'mailcap)
  10344. (require 'mailcap)
  10345. (mailcap-parse-mailcaps)
  10346. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10347. (command (mailcap-mime-info mime-type)))
  10348. (if (stringp command)
  10349. (setq cmd command)
  10350. (setq cmd 'emacs))))
  10351. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10352. (not (file-exists-p file))
  10353. (not org-open-non-existing-files))
  10354. (user-error "No such file: %s" file))
  10355. (cond
  10356. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10357. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10358. (while (string-match "['\"]%s['\"]" cmd)
  10359. (setq cmd (replace-match "%s" t t cmd)))
  10360. (while (string-match "%s" cmd)
  10361. (setq cmd (replace-match
  10362. (save-match-data
  10363. (shell-quote-argument
  10364. (convert-standard-filename file)))
  10365. t t cmd)))
  10366. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10367. (save-match-data
  10368. (let ((match-index 1)
  10369. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10370. (set-match-data link-match-data)
  10371. (while (<= match-index number-of-groups)
  10372. (let ((regex (concat "%" (number-to-string match-index)))
  10373. (replace-with (match-string match-index dlink)))
  10374. (while (string-match regex cmd)
  10375. (setq cmd (replace-match replace-with t t cmd))))
  10376. (setq match-index (+ match-index 1)))))
  10377. (save-window-excursion
  10378. (message "Running %s...done" cmd)
  10379. (start-process-shell-command cmd nil cmd)
  10380. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10381. ((or (stringp cmd)
  10382. (eq cmd 'emacs))
  10383. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10384. (widen)
  10385. (cond (line (org-goto-line line)
  10386. (when (derived-mode-p 'org-mode) (org-reveal)))
  10387. (search (org-link-search search))))
  10388. ((functionp cmd)
  10389. (save-match-data
  10390. (set-match-data link-match-data)
  10391. (condition-case nil
  10392. (funcall cmd file link)
  10393. ;; FIXME: Remove this check when most default installations
  10394. ;; of Emacs have at least Org 9.0.
  10395. ((debug wrong-number-of-arguments wrong-type-argument
  10396. invalid-function)
  10397. (user-error "Please see Org News for version 9.0 about \
  10398. `org-file-apps'--Lisp error: %S" cmd)))))
  10399. ((consp cmd)
  10400. ;; FIXME: Remove this check when most default installations of
  10401. ;; Emacs have at least Org 9.0.
  10402. ;; Heads-up instead of silently fall back to
  10403. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10404. ;; with sexp instead of a function for `cmd'.
  10405. (user-error "Please see Org News for version 9.0 about \
  10406. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10407. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10408. (and (derived-mode-p 'org-mode)
  10409. (eq old-mode 'org-mode)
  10410. (or (not (eq old-buffer (current-buffer)))
  10411. (not (eq old-pos (point))))
  10412. (org-mark-ring-push old-pos old-buffer))))
  10413. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10414. "This function returns non-nil if `entry' uses a regular
  10415. expression which should be matched against the whole link by
  10416. org-open-file.
  10417. It assumes that is the case when the entry uses a regular
  10418. expression which has at least one grouping construct and the
  10419. action is either a lisp form or a command string containing
  10420. `%1', i.e. using at least one subexpression match as a
  10421. parameter."
  10422. (let ((selector (car entry))
  10423. (action (cdr entry)))
  10424. (if (stringp selector)
  10425. (and (> (regexp-opt-depth selector) 0)
  10426. (or (and (stringp action)
  10427. (string-match "%[0-9]" action))
  10428. (consp action)))
  10429. nil)))
  10430. (defun org-default-apps ()
  10431. "Return the default applications for this operating system."
  10432. (cond
  10433. ((eq system-type 'darwin)
  10434. org-file-apps-defaults-macosx)
  10435. ((eq system-type 'windows-nt)
  10436. org-file-apps-defaults-windowsnt)
  10437. (t org-file-apps-defaults-gnu)))
  10438. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10439. "Convert extensions to regular expressions in the cars of LIST.
  10440. Also, weed out any non-string entries, because the return value is used
  10441. only for regexp matching.
  10442. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10443. point to the symbol `emacs', indicating that the file should
  10444. be opened in Emacs."
  10445. (append
  10446. (delq nil
  10447. (mapcar (lambda (x)
  10448. (unless (not (stringp (car x)))
  10449. (if (string-match "\\W" (car x))
  10450. x
  10451. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10452. list))
  10453. (when add-auto-mode
  10454. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10455. (defvar ange-ftp-name-format)
  10456. (defun org-file-remote-p (file)
  10457. "Test whether FILE specifies a location on a remote system.
  10458. Return non-nil if the location is indeed remote.
  10459. For example, the filename \"/user@host:/foo\" specifies a location
  10460. on the system \"/user@host:\"."
  10461. (cond ((fboundp 'file-remote-p)
  10462. (file-remote-p file))
  10463. ((fboundp 'tramp-handle-file-remote-p)
  10464. (tramp-handle-file-remote-p file))
  10465. ((and (boundp 'ange-ftp-name-format)
  10466. (string-match (car ange-ftp-name-format) file))
  10467. t)))
  10468. ;;;; Refiling
  10469. (defun org-get-org-file ()
  10470. "Read a filename, with default directory `org-directory'."
  10471. (let ((default (or org-default-notes-file remember-data-file)))
  10472. (read-file-name (format "File name [%s]: " default)
  10473. (file-name-as-directory org-directory)
  10474. default)))
  10475. (defun org-notes-order-reversed-p ()
  10476. "Check if the current file should receive notes in reversed order."
  10477. (cond
  10478. ((not org-reverse-note-order) nil)
  10479. ((eq t org-reverse-note-order) t)
  10480. ((not (listp org-reverse-note-order)) nil)
  10481. (t (catch 'exit
  10482. (dolist (entry org-reverse-note-order)
  10483. (when (string-match (car entry) buffer-file-name)
  10484. (throw 'exit (cdr entry))))))))
  10485. (defvar org-refile-target-table nil
  10486. "The list of refile targets, created by `org-refile'.")
  10487. (defvar org-agenda-new-buffers nil
  10488. "Buffers created to visit agenda files.")
  10489. (defvar org-refile-cache nil
  10490. "Cache for refile targets.")
  10491. (defvar org-refile-markers nil
  10492. "All the markers used for caching refile locations.")
  10493. (defun org-refile-marker (pos)
  10494. "Get a new refile marker, but only if caching is in use."
  10495. (if (not org-refile-use-cache)
  10496. pos
  10497. (let ((m (make-marker)))
  10498. (move-marker m pos)
  10499. (push m org-refile-markers)
  10500. m)))
  10501. (defun org-refile-cache-clear ()
  10502. "Clear the refile cache and disable all the markers."
  10503. (dolist (m org-refile-markers) (move-marker m nil))
  10504. (setq org-refile-markers nil)
  10505. (setq org-refile-cache nil)
  10506. (message "Refile cache has been cleared"))
  10507. (defun org-refile-cache-check-set (set)
  10508. "Check if all the markers in the cache still have live buffers."
  10509. (let (marker)
  10510. (catch 'exit
  10511. (while (and set (setq marker (nth 3 (pop set))))
  10512. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10513. (when (and marker (null (marker-buffer marker)))
  10514. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10515. (sit-for 3)
  10516. (throw 'exit nil)))
  10517. t)))
  10518. (defun org-refile-cache-put (set &rest identifiers)
  10519. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10520. (let* ((key (sha1 (prin1-to-string identifiers)))
  10521. (entry (assoc key org-refile-cache)))
  10522. (if entry
  10523. (setcdr entry set)
  10524. (push (cons key set) org-refile-cache))))
  10525. (defun org-refile-cache-get (&rest identifiers)
  10526. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10527. (cond
  10528. ((not org-refile-cache) nil)
  10529. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10530. (t
  10531. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10532. org-refile-cache))))
  10533. (and set (org-refile-cache-check-set set) set)))))
  10534. (defvar org-outline-path-cache nil
  10535. "Alist between buffer positions and outline paths.
  10536. It value is an alist (POSITION . PATH) where POSITION is the
  10537. buffer position at the beginning of an entry and PATH is a list
  10538. of strings describing the outline path for that entry, in reverse
  10539. order.")
  10540. (defun org-refile-get-targets (&optional default-buffer)
  10541. "Produce a table with refile targets."
  10542. (let ((case-fold-search nil)
  10543. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10544. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10545. targets tgs files desc descre)
  10546. (message "Getting targets...")
  10547. (with-current-buffer (or default-buffer (current-buffer))
  10548. (dolist (entry entries)
  10549. (setq files (car entry) desc (cdr entry))
  10550. (cond
  10551. ((null files) (setq files (list (current-buffer))))
  10552. ((eq files 'org-agenda-files)
  10553. (setq files (org-agenda-files 'unrestricted)))
  10554. ((and (symbolp files) (fboundp files))
  10555. (setq files (funcall files)))
  10556. ((and (symbolp files) (boundp files))
  10557. (setq files (symbol-value files))))
  10558. (when (stringp files) (setq files (list files)))
  10559. (cond
  10560. ((eq (car desc) :tag)
  10561. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10562. ((eq (car desc) :todo)
  10563. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10564. ((eq (car desc) :regexp)
  10565. (setq descre (cdr desc)))
  10566. ((eq (car desc) :level)
  10567. (setq descre (concat "^\\*\\{" (number-to-string
  10568. (if org-odd-levels-only
  10569. (1- (* 2 (cdr desc)))
  10570. (cdr desc)))
  10571. "\\}[ \t]")))
  10572. ((eq (car desc) :maxlevel)
  10573. (setq descre (concat "^\\*\\{1," (number-to-string
  10574. (if org-odd-levels-only
  10575. (1- (* 2 (cdr desc)))
  10576. (cdr desc)))
  10577. "\\}[ \t]")))
  10578. (t (error "Bad refiling target description %s" desc)))
  10579. (dolist (f files)
  10580. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10581. (or
  10582. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10583. (progn
  10584. (when (bufferp f)
  10585. (setq f (buffer-file-name (buffer-base-buffer f))))
  10586. (setq f (and f (expand-file-name f)))
  10587. (when (eq org-refile-use-outline-path 'file)
  10588. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10589. (org-with-wide-buffer
  10590. (goto-char (point-min))
  10591. (setq org-outline-path-cache nil)
  10592. (while (re-search-forward descre nil t)
  10593. (beginning-of-line)
  10594. (looking-at org-complex-heading-regexp)
  10595. (let ((begin (point))
  10596. (heading (match-string-no-properties 4)))
  10597. (unless (or (and
  10598. org-refile-target-verify-function
  10599. (not
  10600. (funcall org-refile-target-verify-function)))
  10601. (not heading))
  10602. (let ((re (format org-complex-heading-regexp-format
  10603. (regexp-quote heading)))
  10604. (target
  10605. (if (not org-refile-use-outline-path) heading
  10606. (mapconcat
  10607. #'org-protect-slash
  10608. (append
  10609. (pcase org-refile-use-outline-path
  10610. (`file (list (file-name-nondirectory
  10611. (buffer-file-name
  10612. (buffer-base-buffer)))))
  10613. (`full-file-path
  10614. (list (buffer-file-name
  10615. (buffer-base-buffer))))
  10616. (_ nil))
  10617. (org-get-outline-path t t))
  10618. "/"))))
  10619. (push (list target f re (org-refile-marker (point)))
  10620. tgs)))
  10621. (when (= (point) begin)
  10622. ;; Verification function has not moved point.
  10623. (end-of-line)))))))
  10624. (when org-refile-use-cache
  10625. (org-refile-cache-put tgs (buffer-file-name) descre))
  10626. (setq targets (append tgs targets))))))
  10627. (message "Getting targets...done")
  10628. (nreverse targets)))
  10629. (defun org-protect-slash (s)
  10630. (while (string-match "/" s)
  10631. (setq s (replace-match "\\" t t s)))
  10632. s)
  10633. (defun org--get-outline-path-1 (&optional use-cache)
  10634. "Return outline path to current headline.
  10635. Outline path is a list of strings, in reverse order. When
  10636. optional argument USE-CACHE is non-nil, make use of a cache. See
  10637. `org-get-outline-path' for details.
  10638. Assume buffer is widened and point is on a headline."
  10639. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10640. (let ((p (point))
  10641. (heading (progn
  10642. (looking-at org-complex-heading-regexp)
  10643. (if (not (match-end 4)) ""
  10644. ;; Remove statistics cookies.
  10645. (org-trim
  10646. (org-link-display-format
  10647. (replace-regexp-in-string
  10648. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10649. (match-string-no-properties 4))))))))
  10650. (if (org-up-heading-safe)
  10651. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10652. (when use-cache
  10653. (push (cons p path) org-outline-path-cache))
  10654. path)
  10655. ;; This is a new root node. Since we assume we are moving
  10656. ;; forward, we can drop previous cache so as to limit number
  10657. ;; of associations there.
  10658. (let ((path (list heading)))
  10659. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10660. path)))))
  10661. (defun org-get-outline-path (&optional with-self use-cache)
  10662. "Return the outline path to the current entry.
  10663. An outline path is a list of ancestors for current headline, as
  10664. a list of strings. Statistics cookies are removed and links are
  10665. replaced with their description, if any, or their path otherwise.
  10666. When optional argument WITH-SELF is non-nil, the path also
  10667. includes the current headline.
  10668. When optional argument USE-CACHE is non-nil, cache outline paths
  10669. between calls to this function so as to avoid backtracking. This
  10670. argument is useful when planning to find more than one outline
  10671. path in the same document. In that case, there are two
  10672. conditions to satisfy:
  10673. - `org-outline-path-cache' is set to nil before starting the
  10674. process;
  10675. - outline paths are computed by increasing buffer positions."
  10676. (org-with-wide-buffer
  10677. (and (or (and with-self (org-back-to-heading t))
  10678. (org-up-heading-safe))
  10679. (reverse (org--get-outline-path-1 use-cache)))))
  10680. (defun org-format-outline-path (path &optional width prefix separator)
  10681. "Format the outline path PATH for display.
  10682. WIDTH is the maximum number of characters that is available.
  10683. PREFIX is a prefix to be included in the returned string,
  10684. such as the file name.
  10685. SEPARATOR is inserted between the different parts of the path,
  10686. the default is \"/\"."
  10687. (setq width (or width 79))
  10688. (setq path (delq nil path))
  10689. (unless (> width 0)
  10690. (user-error "Argument `width' must be positive"))
  10691. (setq separator (or separator "/"))
  10692. (let* ((org-odd-levels-only nil)
  10693. (fpath (concat
  10694. prefix (and prefix path separator)
  10695. (mapconcat
  10696. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10697. (cl-loop for head in path
  10698. for n from 0
  10699. collect (org-add-props
  10700. head nil 'face
  10701. (nth (% n org-n-level-faces) org-level-faces)))
  10702. separator))))
  10703. (when (> (length fpath) width)
  10704. (if (< width 7)
  10705. ;; It's unlikely that `width' will be this small, but don't
  10706. ;; waste characters by adding ".." if it is.
  10707. (setq fpath (substring fpath 0 width))
  10708. (setf (substring fpath (- width 2)) "..")))
  10709. fpath))
  10710. (defun org-display-outline-path (&optional file current separator just-return-string)
  10711. "Display the current outline path in the echo area.
  10712. If FILE is non-nil, prepend the output with the file name.
  10713. If CURRENT is non-nil, append the current heading to the output.
  10714. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10715. the different parts of the path and defaults to \"/\".
  10716. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10717. (interactive "P")
  10718. (let* (case-fold-search
  10719. (bfn (buffer-file-name (buffer-base-buffer)))
  10720. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10721. res)
  10722. (when current (setq path (append path
  10723. (save-excursion
  10724. (org-back-to-heading t)
  10725. (when (looking-at org-complex-heading-regexp)
  10726. (list (match-string 4)))))))
  10727. (setq res
  10728. (org-format-outline-path
  10729. path
  10730. (1- (frame-width))
  10731. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10732. separator))
  10733. (if just-return-string
  10734. (org-no-properties res)
  10735. (org-unlogged-message "%s" res))))
  10736. (defvar org-refile-history nil
  10737. "History for refiling operations.")
  10738. (defvar org-after-refile-insert-hook nil
  10739. "Hook run after `org-refile' has inserted its stuff at the new location.
  10740. Note that this is still *before* the stuff will be removed from
  10741. the *old* location.")
  10742. (defvar org-capture-last-stored-marker)
  10743. (defvar org-refile-keep nil
  10744. "Non-nil means `org-refile' will copy instead of refile.")
  10745. (defun org-copy ()
  10746. "Like `org-refile', but copy."
  10747. (interactive)
  10748. (let ((org-refile-keep t))
  10749. (funcall 'org-refile nil nil nil "Copy")))
  10750. (defun org-refile (&optional arg default-buffer rfloc msg)
  10751. "Move the entry or entries at point to another heading.
  10752. The list of target headings is compiled using the information in
  10753. `org-refile-targets', which see.
  10754. At the target location, the entry is filed as a subitem of the
  10755. target heading. Depending on `org-reverse-note-order', the new
  10756. subitem will either be the first or the last subitem.
  10757. If there is an active region, all entries in that region will be
  10758. refiled. However, the region must fulfill the requirement that
  10759. the first heading sets the top-level of the moved text.
  10760. With prefix arg ARG, the command will only visit the target
  10761. location and not actually move anything.
  10762. With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
  10763. refiling operation has put the subtree.
  10764. With a numeric prefix argument of `2', refile to the running clock.
  10765. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10766. being set to t and copy to the target location, don't move it.
  10767. Beware that keeping refiled entries may result in duplicated ID
  10768. properties.
  10769. RFLOC can be a refile location obtained in a different way.
  10770. MSG is a string to replace \"Refile\" in the default prompt with
  10771. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10772. See also `org-refile-use-outline-path'.
  10773. If you are using target caching (see `org-refile-use-cache'), you
  10774. have to clear the target cache in order to find new targets.
  10775. This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
  10776. prefix argument (`C-u C-u C-u C-c C-w')."
  10777. (interactive "P")
  10778. (if (member arg '(0 (64)))
  10779. (org-refile-cache-clear)
  10780. (let* ((actionmsg (cond (msg msg)
  10781. ((equal arg 3) "Refile (and keep)")
  10782. (t "Refile")))
  10783. (regionp (org-region-active-p))
  10784. (region-start (and regionp (region-beginning)))
  10785. (region-end (and regionp (region-end)))
  10786. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10787. pos it nbuf file level reversed)
  10788. (setq last-command nil)
  10789. (when regionp
  10790. (goto-char region-start)
  10791. (or (bolp) (goto-char (point-at-bol)))
  10792. (setq region-start (point))
  10793. (unless (or (org-kill-is-subtree-p
  10794. (buffer-substring region-start region-end))
  10795. (prog1 org-refile-active-region-within-subtree
  10796. (let ((s (point-at-eol)))
  10797. (org-toggle-heading)
  10798. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10799. (user-error "The region is not a (sequence of) subtree(s)")))
  10800. (if (equal arg '(16))
  10801. (org-refile-goto-last-stored)
  10802. (when (or
  10803. (and (equal arg 2)
  10804. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10805. (prog1
  10806. (setq it (list (or org-clock-heading "running clock")
  10807. (buffer-file-name
  10808. (marker-buffer org-clock-hd-marker))
  10809. ""
  10810. (marker-position org-clock-hd-marker)))
  10811. (setq arg nil)))
  10812. (setq it
  10813. (or rfloc
  10814. (let (heading-text)
  10815. (save-excursion
  10816. (unless (and arg (listp arg))
  10817. (org-back-to-heading t)
  10818. (setq heading-text
  10819. (replace-regexp-in-string
  10820. org-bracket-link-regexp
  10821. "\\3"
  10822. (or (nth 4 (org-heading-components))
  10823. ""))))
  10824. (org-refile-get-location
  10825. (cond ((and arg (listp arg)) "Goto")
  10826. (regionp (concat actionmsg " region to"))
  10827. (t (concat actionmsg " subtree \""
  10828. heading-text "\" to")))
  10829. default-buffer
  10830. (and (not (equal '(4) arg))
  10831. org-refile-allow-creating-parent-nodes)))))))
  10832. (setq file (nth 1 it)
  10833. pos (nth 3 it))
  10834. (when (and (not arg)
  10835. pos
  10836. (equal (buffer-file-name) file)
  10837. (if regionp
  10838. (and (>= pos region-start)
  10839. (<= pos region-end))
  10840. (and (>= pos (point))
  10841. (< pos (save-excursion
  10842. (org-end-of-subtree t t))))))
  10843. (error "Cannot refile to position inside the tree or region"))
  10844. (setq nbuf (or (find-buffer-visiting file)
  10845. (find-file-noselect file)))
  10846. (if (and arg (not (equal arg 3)))
  10847. (progn
  10848. (pop-to-buffer-same-window nbuf)
  10849. (goto-char pos)
  10850. (org-show-context 'org-goto))
  10851. (if regionp
  10852. (progn
  10853. (org-kill-new (buffer-substring region-start region-end))
  10854. (org-save-markers-in-region region-start region-end))
  10855. (org-copy-subtree 1 nil t))
  10856. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10857. (find-file-noselect file)))
  10858. (setq reversed (org-notes-order-reversed-p))
  10859. (save-excursion
  10860. (save-restriction
  10861. (widen)
  10862. (if pos
  10863. (progn
  10864. (goto-char pos)
  10865. (looking-at org-outline-regexp)
  10866. (setq level (org-get-valid-level (funcall outline-level) 1))
  10867. (goto-char
  10868. (if reversed
  10869. (or (outline-next-heading) (point-max))
  10870. (or (save-excursion (org-get-next-sibling))
  10871. (org-end-of-subtree t t)
  10872. (point-max)))))
  10873. (setq level 1)
  10874. (if (not reversed)
  10875. (goto-char (point-max))
  10876. (goto-char (point-min))
  10877. (or (outline-next-heading) (goto-char (point-max)))))
  10878. (unless (bolp) (newline))
  10879. (org-paste-subtree level nil nil t)
  10880. (when org-log-refile
  10881. (org-add-log-setup 'refile nil nil org-log-refile)
  10882. (unless (eq org-log-refile 'note)
  10883. (save-excursion (org-add-log-note))))
  10884. (and org-auto-align-tags
  10885. (let ((org-loop-over-headlines-in-active-region nil))
  10886. (org-set-tags nil t)))
  10887. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10888. :last-refile)))
  10889. (when bookmark-name
  10890. (with-demoted-errors
  10891. (bookmark-set bookmark-name))))
  10892. ;; If we are refiling for capture, make sure that the
  10893. ;; last-capture pointers point here
  10894. (when (bound-and-true-p org-capture-is-refiling)
  10895. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10896. :last-capture-marker)))
  10897. (when bookmark-name
  10898. (with-demoted-errors
  10899. (bookmark-set bookmark-name))))
  10900. (move-marker org-capture-last-stored-marker (point)))
  10901. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10902. (run-hooks 'org-after-refile-insert-hook))))
  10903. (unless org-refile-keep
  10904. (if regionp
  10905. (delete-region (point) (+ (point) (- region-end region-start)))
  10906. (delete-region
  10907. (and (org-back-to-heading t) (point))
  10908. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10909. (when (featurep 'org-inlinetask)
  10910. (org-inlinetask-remove-END-maybe))
  10911. (setq org-markers-to-move nil)
  10912. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10913. (defun org-refile-goto-last-stored ()
  10914. "Go to the location where the last refile was stored."
  10915. (interactive)
  10916. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10917. (message "This is the location of the last refile"))
  10918. (defun org-refile--get-location (refloc tbl)
  10919. "When user refile to REFLOC, find the associated target in TBL.
  10920. Also check `org-refile-target-table'."
  10921. (car (delq
  10922. nil
  10923. (mapcar
  10924. (lambda (r) (or (assoc r tbl)
  10925. (assoc r org-refile-target-table)))
  10926. (list (replace-regexp-in-string "/$" "" refloc)
  10927. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10928. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10929. "Prompt the user for a refile location, using PROMPT.
  10930. PROMPT should not be suffixed with a colon and a space, because
  10931. this function appends the default value from
  10932. `org-refile-history' automatically, if that is not empty."
  10933. (let ((org-refile-targets org-refile-targets)
  10934. (org-refile-use-outline-path org-refile-use-outline-path))
  10935. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10936. (unless org-refile-target-table
  10937. (user-error "No refile targets"))
  10938. (let* ((cbuf (current-buffer))
  10939. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10940. (cfunc (if (and org-refile-use-outline-path
  10941. org-outline-path-complete-in-steps)
  10942. #'org-olpath-completing-read
  10943. #'completing-read))
  10944. (extra (if org-refile-use-outline-path "/" ""))
  10945. (cbnex (concat (buffer-name) extra))
  10946. (filename (and cfn (expand-file-name cfn)))
  10947. (tbl (mapcar
  10948. (lambda (x)
  10949. (if (and (not (member org-refile-use-outline-path
  10950. '(file full-file-path)))
  10951. (not (equal filename (nth 1 x))))
  10952. (cons (concat (car x) extra " ("
  10953. (file-name-nondirectory (nth 1 x)) ")")
  10954. (cdr x))
  10955. (cons (concat (car x) extra) (cdr x))))
  10956. org-refile-target-table))
  10957. (completion-ignore-case t)
  10958. cdef
  10959. (prompt (concat prompt
  10960. (or (and (car org-refile-history)
  10961. (concat " (default " (car org-refile-history) ")"))
  10962. (and (assoc cbnex tbl) (setq cdef cbnex)
  10963. (concat " (default " cbnex ")"))) ": "))
  10964. pa answ parent-target child parent old-hist)
  10965. (setq old-hist org-refile-history)
  10966. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10967. nil 'org-refile-history (or cdef (car org-refile-history))))
  10968. (if (setq pa (org-refile--get-location answ tbl))
  10969. (progn
  10970. (org-refile-check-position pa)
  10971. (when (or (not org-refile-history)
  10972. (not (eq old-hist org-refile-history))
  10973. (not (equal (car pa) (car org-refile-history))))
  10974. (setq org-refile-history
  10975. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10976. org-refile-history
  10977. (cdr org-refile-history))))
  10978. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10979. (pop org-refile-history)))
  10980. pa)
  10981. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10982. (progn
  10983. (setq parent (match-string 1 answ)
  10984. child (match-string 2 answ))
  10985. (setq parent-target (org-refile--get-location parent tbl))
  10986. (when (and parent-target
  10987. (or (eq new-nodes t)
  10988. (and (eq new-nodes 'confirm)
  10989. (y-or-n-p (format "Create new node \"%s\"? "
  10990. child)))))
  10991. (org-refile-new-child parent-target child)))
  10992. (user-error "Invalid target location")))))
  10993. (declare-function org-string-nw-p "org-macs" (s))
  10994. (defun org-refile-check-position (refile-pointer)
  10995. "Check if the refile pointer matches the headline to which it points."
  10996. (let* ((file (nth 1 refile-pointer))
  10997. (re (nth 2 refile-pointer))
  10998. (pos (nth 3 refile-pointer))
  10999. buffer)
  11000. (if (and (not (markerp pos)) (not file))
  11001. (user-error "Please indicate a target file in the refile path")
  11002. (when (org-string-nw-p re)
  11003. (setq buffer (if (markerp pos)
  11004. (marker-buffer pos)
  11005. (or (find-buffer-visiting file)
  11006. (find-file-noselect file))))
  11007. (with-current-buffer buffer
  11008. (save-excursion
  11009. (save-restriction
  11010. (widen)
  11011. (goto-char pos)
  11012. (beginning-of-line 1)
  11013. (unless (looking-at-p re)
  11014. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
  11015. (defun org-refile-new-child (parent-target child)
  11016. "Use refile target PARENT-TARGET to add new CHILD below it."
  11017. (unless parent-target
  11018. (error "Cannot find parent for new node"))
  11019. (let ((file (nth 1 parent-target))
  11020. (pos (nth 3 parent-target))
  11021. level)
  11022. (with-current-buffer (or (find-buffer-visiting file)
  11023. (find-file-noselect file))
  11024. (save-excursion
  11025. (save-restriction
  11026. (widen)
  11027. (if pos
  11028. (goto-char pos)
  11029. (goto-char (point-max))
  11030. (unless (bolp) (newline)))
  11031. (when (looking-at org-outline-regexp)
  11032. (setq level (funcall outline-level))
  11033. (org-end-of-subtree t t))
  11034. (org-back-over-empty-lines)
  11035. (insert "\n" (make-string
  11036. (if pos (org-get-valid-level level 1) 1) ?*)
  11037. " " child "\n")
  11038. (beginning-of-line 0)
  11039. (list (concat (car parent-target) "/" child) file "" (point)))))))
  11040. (defun org-olpath-completing-read (prompt collection &rest args)
  11041. "Read an outline path like a file name."
  11042. (let ((thetable collection))
  11043. (apply #'completing-read
  11044. prompt
  11045. (lambda (string predicate &optional flag)
  11046. (cond
  11047. ((eq flag nil) (try-completion string thetable))
  11048. ((eq flag t)
  11049. (let ((l (length string)))
  11050. (mapcar (lambda (x)
  11051. (let ((r (substring x l))
  11052. (f (if (string-match " ([^)]*)$" x)
  11053. (match-string 0 x)
  11054. "")))
  11055. (if (string-match "/" r)
  11056. (concat string (substring r 0 (match-end 0)) f)
  11057. x)))
  11058. (all-completions string thetable predicate))))
  11059. ;; Exact match?
  11060. ((eq flag 'lambda) (assoc string thetable))))
  11061. args)))
  11062. ;;;; Dynamic blocks
  11063. (defun org-find-dblock (name)
  11064. "Find the first dynamic block with name NAME in the buffer.
  11065. If not found, stay at current position and return nil."
  11066. (let ((case-fold-search t) pos)
  11067. (save-excursion
  11068. (goto-char (point-min))
  11069. (setq pos (and (re-search-forward
  11070. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11071. (match-beginning 0))))
  11072. (when pos (goto-char pos))
  11073. pos))
  11074. (defun org-create-dblock (plist)
  11075. "Create a dynamic block section, with parameters taken from PLIST.
  11076. PLIST must contain a :name entry which is used as the name of the block."
  11077. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11078. (end-of-line 1)
  11079. (newline))
  11080. (let ((col (current-column))
  11081. (name (plist-get plist :name)))
  11082. (insert "#+BEGIN: " name)
  11083. (while plist
  11084. (if (eq (car plist) :name)
  11085. (setq plist (cddr plist))
  11086. (insert " " (prin1-to-string (pop plist)))))
  11087. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11088. (beginning-of-line -2)))
  11089. (defun org-prepare-dblock ()
  11090. "Prepare dynamic block for refresh.
  11091. This empties the block, puts the cursor at the insert position and returns
  11092. the property list including an extra property :name with the block name."
  11093. (unless (looking-at org-dblock-start-re)
  11094. (user-error "Not at a dynamic block"))
  11095. (let* ((begdel (1+ (match-end 0)))
  11096. (name (org-no-properties (match-string 1)))
  11097. (params (append (list :name name)
  11098. (read (concat "(" (match-string 3) ")")))))
  11099. (save-excursion
  11100. (beginning-of-line 1)
  11101. (skip-chars-forward " \t")
  11102. (setq params (plist-put params :indentation-column (current-column))))
  11103. (unless (re-search-forward org-dblock-end-re nil t)
  11104. (error "Dynamic block not terminated"))
  11105. (setq params
  11106. (append params
  11107. (list :content (buffer-substring
  11108. begdel (match-beginning 0)))))
  11109. (delete-region begdel (match-beginning 0))
  11110. (goto-char begdel)
  11111. (open-line 1)
  11112. params))
  11113. (defun org-map-dblocks (&optional command)
  11114. "Apply COMMAND to all dynamic blocks in the current buffer.
  11115. If COMMAND is not given, use `org-update-dblock'."
  11116. (let ((cmd (or command 'org-update-dblock)))
  11117. (save-excursion
  11118. (goto-char (point-min))
  11119. (while (re-search-forward org-dblock-start-re nil t)
  11120. (goto-char (match-beginning 0))
  11121. (save-excursion
  11122. (condition-case nil
  11123. (funcall cmd)
  11124. (error (message "Error during update of dynamic block"))))
  11125. (unless (re-search-forward org-dblock-end-re nil t)
  11126. (error "Dynamic block not terminated"))))))
  11127. (defun org-dblock-update (&optional arg)
  11128. "User command for updating dynamic blocks.
  11129. Update the dynamic block at point. With prefix ARG, update all dynamic
  11130. blocks in the buffer."
  11131. (interactive "P")
  11132. (if arg
  11133. (org-update-all-dblocks)
  11134. (or (looking-at org-dblock-start-re)
  11135. (org-beginning-of-dblock))
  11136. (org-update-dblock)))
  11137. (defun org-update-dblock ()
  11138. "Update the dynamic block at point.
  11139. This means to empty the block, parse for parameters and then call
  11140. the correct writing function."
  11141. (interactive)
  11142. (save-excursion
  11143. (let* ((win (selected-window))
  11144. (pos (point))
  11145. (line (org-current-line))
  11146. (params (org-prepare-dblock))
  11147. (name (plist-get params :name))
  11148. (indent (plist-get params :indentation-column))
  11149. (cmd (intern (concat "org-dblock-write:" name))))
  11150. (message "Updating dynamic block `%s' at line %d..." name line)
  11151. (funcall cmd params)
  11152. (message "Updating dynamic block `%s' at line %d...done" name line)
  11153. (goto-char pos)
  11154. (when (and indent (> indent 0))
  11155. (setq indent (make-string indent ?\ ))
  11156. (save-excursion
  11157. (select-window win)
  11158. (org-beginning-of-dblock)
  11159. (forward-line 1)
  11160. (while (not (looking-at org-dblock-end-re))
  11161. (insert indent)
  11162. (beginning-of-line 2))
  11163. (when (looking-at org-dblock-end-re)
  11164. (and (looking-at "[ \t]+")
  11165. (replace-match ""))
  11166. (insert indent)))))))
  11167. (defun org-beginning-of-dblock ()
  11168. "Find the beginning of the dynamic block at point.
  11169. Error if there is no such block at point."
  11170. (let ((pos (point))
  11171. beg)
  11172. (end-of-line 1)
  11173. (if (and (re-search-backward org-dblock-start-re nil t)
  11174. (setq beg (match-beginning 0))
  11175. (re-search-forward org-dblock-end-re nil t)
  11176. (> (match-end 0) pos))
  11177. (goto-char beg)
  11178. (goto-char pos)
  11179. (error "Not in a dynamic block"))))
  11180. (defun org-update-all-dblocks ()
  11181. "Update all dynamic blocks in the buffer.
  11182. This function can be used in a hook."
  11183. (interactive)
  11184. (when (derived-mode-p 'org-mode)
  11185. (org-map-dblocks 'org-update-dblock)))
  11186. ;;;; Completion
  11187. (declare-function org-export-backend-options "ox" (cl-x) t)
  11188. (defun org-get-export-keywords ()
  11189. "Return a list of all currently understood export keywords.
  11190. Export keywords include options, block names, attributes and
  11191. keywords relative to each registered export back-end."
  11192. (let (keywords)
  11193. (dolist (backend
  11194. (bound-and-true-p org-export-registered-backends)
  11195. (delq nil keywords))
  11196. ;; Back-end name (for keywords, like #+LATEX:)
  11197. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11198. (dolist (option-entry (org-export-backend-options backend))
  11199. ;; Back-end options.
  11200. (push (nth 1 option-entry) keywords)))))
  11201. (defconst org-options-keywords
  11202. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11203. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11204. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11205. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11206. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11207. (defcustom org-structure-template-alist
  11208. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11209. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11210. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11211. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11212. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11213. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11214. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11215. ("L" "#+LaTeX: ")
  11216. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11217. ("H" "#+HTML: ")
  11218. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11219. ("A" "#+ASCII: ")
  11220. ("i" "#+INDEX: ?")
  11221. ("I" "#+INCLUDE: %file ?"))
  11222. "Structure completion elements.
  11223. This is a list of abbreviation keys and values. The value gets inserted
  11224. if you type `<' followed by the key and then press the completion key,
  11225. usually `TAB'. %file will be replaced by a file name after prompting
  11226. for the file using completion. The cursor will be placed at the position
  11227. of the `?' in the template.
  11228. There are two templates for each key, the first uses the original Org syntax,
  11229. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11230. the default when the /org-mtags.el/ module has been loaded. See also the
  11231. variable `org-mtags-prefer-muse-templates'."
  11232. :group 'org-completion
  11233. :type '(repeat
  11234. (list
  11235. (string :tag "Key")
  11236. (string :tag "Template")))
  11237. :version "25.1"
  11238. :package-version '(Org . "8.3"))
  11239. (defun org-try-structure-completion ()
  11240. "Try to complete a structure template before point.
  11241. This looks for strings like \"<e\" on an otherwise empty line and
  11242. expands them."
  11243. (let ((l (buffer-substring (point-at-bol) (point)))
  11244. a)
  11245. (when (and (looking-at "[ \t]*$")
  11246. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11247. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11248. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11249. (match-beginning 1)) a)
  11250. t)))
  11251. (defun org-complete-expand-structure-template (start cell)
  11252. "Expand a structure template."
  11253. (let ((rpl (nth 1 cell))
  11254. (ind ""))
  11255. (delete-region start (point))
  11256. (when (string-match "\\`[ \t]*#\\+" rpl)
  11257. (cond
  11258. ((bolp))
  11259. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11260. (setq ind (buffer-substring (point-at-bol) (point))))
  11261. (t (newline))))
  11262. (setq start (point))
  11263. (when (string-match "%file" rpl)
  11264. (setq rpl (replace-match
  11265. (concat
  11266. "\""
  11267. (save-match-data
  11268. (abbreviate-file-name (read-file-name "Include file: ")))
  11269. "\"")
  11270. t t rpl)))
  11271. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11272. (concat "\n" ind)))
  11273. (insert rpl)
  11274. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11275. ;;;; TODO, DEADLINE, Comments
  11276. (defun org-toggle-comment ()
  11277. "Change the COMMENT state of an entry."
  11278. (interactive)
  11279. (save-excursion
  11280. (org-back-to-heading)
  11281. (looking-at org-complex-heading-regexp)
  11282. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11283. (skip-chars-forward " \t")
  11284. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11285. (if (org-in-commented-heading-p t)
  11286. (delete-region (point)
  11287. (progn (search-forward " " (line-end-position) 'move)
  11288. (skip-chars-forward " \t")
  11289. (point)))
  11290. (insert org-comment-string)
  11291. (unless (eolp) (insert " ")))))
  11292. (defvar org-last-todo-state-is-todo nil
  11293. "This is non-nil when the last TODO state change led to a TODO state.
  11294. If the last change removed the TODO tag or switched to DONE, then
  11295. this is nil.")
  11296. (defvar org-setting-tags nil) ; dynamically skipped
  11297. (defvar org-todo-setup-filter-hook nil
  11298. "Hook for functions that pre-filter todo specs.
  11299. Each function takes a todo spec and returns either nil or the spec
  11300. transformed into canonical form." )
  11301. (defvar org-todo-get-default-hook nil
  11302. "Hook for functions that get a default item for todo.
  11303. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11304. nil or a string to be used for the todo mark." )
  11305. (defvar org-agenda-headline-snapshot-before-repeat)
  11306. (defun org-current-effective-time ()
  11307. "Return current time adjusted for `org-extend-today-until' variable."
  11308. (let* ((ct (org-current-time))
  11309. (dct (decode-time ct))
  11310. (ct1
  11311. (cond
  11312. (org-use-last-clock-out-time-as-effective-time
  11313. (or (org-clock-get-last-clock-out-time) ct))
  11314. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11315. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11316. (t ct))))
  11317. ct1))
  11318. (defun org-todo-yesterday (&optional arg)
  11319. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11320. (interactive "P")
  11321. (if (eq major-mode 'org-agenda-mode)
  11322. (apply 'org-agenda-todo-yesterday arg)
  11323. (let* ((org-use-effective-time t)
  11324. (hour (nth 2 (decode-time (org-current-time))))
  11325. (org-extend-today-until (1+ hour)))
  11326. (org-todo arg))))
  11327. (defvar org-block-entry-blocking ""
  11328. "First entry preventing the TODO state change.")
  11329. (defun org-cancel-repeater ()
  11330. "Cancel a repeater by setting its numeric value to zero."
  11331. (interactive)
  11332. (save-excursion
  11333. (org-back-to-heading t)
  11334. (let ((bound1 (point))
  11335. (bound0 (save-excursion (outline-next-heading) (point))))
  11336. (when (and (re-search-forward
  11337. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11338. org-deadline-time-regexp "\\)\\|\\("
  11339. org-ts-regexp "\\)")
  11340. bound0 t)
  11341. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11342. bound1 t))
  11343. (replace-match "0" t nil nil 1)))))
  11344. (defvar org-state) ;; dynamically scoped into this function
  11345. (defun org-todo (&optional arg)
  11346. "Change the TODO state of an item.
  11347. The state of an item is given by a keyword at the start of the heading,
  11348. like
  11349. *** TODO Write paper
  11350. *** DONE Call mom
  11351. The different keywords are specified in the variable `org-todo-keywords'.
  11352. By default the available states are \"TODO\" and \"DONE\".
  11353. So for this example: when the item starts with TODO, it is changed to DONE.
  11354. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11355. DONE are present, add TODO at the beginning of the heading.
  11356. With \\[universal-argument] prefix arg, use completion to determine the new \
  11357. state.
  11358. With numeric prefix arg, switch to that state.
  11359. With a double \\[universal-argument] prefix, switch to the next set of TODO \
  11360. keywords (nextset).
  11361. With a triple \\[universal-argument] prefix, circumvent any state blocking.
  11362. With a numeric prefix arg of 0, inhibit note taking for the change.
  11363. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11364. When called through ELisp, arg is also interpreted in the following way:
  11365. `none' -> empty state
  11366. \"\"(empty string) -> switch to empty state
  11367. `done' -> switch to DONE
  11368. `nextset' -> switch to the next set of keywords
  11369. `previousset' -> switch to the previous set of keywords
  11370. \"WAITING\" -> switch to the specified keyword, but only if it
  11371. really is a member of `org-todo-keywords'."
  11372. (interactive "P")
  11373. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11374. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11375. 'region-start-level 'region))
  11376. org-loop-over-headlines-in-active-region)
  11377. (org-map-entries
  11378. `(org-todo ,arg)
  11379. org-loop-over-headlines-in-active-region
  11380. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11381. (when (equal arg '(16)) (setq arg 'nextset))
  11382. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11383. (let ((org-blocker-hook org-blocker-hook)
  11384. commentp
  11385. case-fold-search)
  11386. (when (equal arg '(64))
  11387. (setq arg nil org-blocker-hook nil))
  11388. (when (and org-blocker-hook
  11389. (or org-inhibit-blocking
  11390. (org-entry-get nil "NOBLOCKING")))
  11391. (setq org-blocker-hook nil))
  11392. (save-excursion
  11393. (catch 'exit
  11394. (org-back-to-heading t)
  11395. (when (org-in-commented-heading-p t)
  11396. (org-toggle-comment)
  11397. (setq commentp t))
  11398. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11399. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11400. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11401. (let* ((match-data (match-data))
  11402. (startpos (point-at-bol))
  11403. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11404. (org-log-done org-log-done)
  11405. (org-log-repeat org-log-repeat)
  11406. (org-todo-log-states org-todo-log-states)
  11407. (org-inhibit-logging
  11408. (if (equal arg 0)
  11409. (progn (setq arg nil) 'note) org-inhibit-logging))
  11410. (this (match-string 1))
  11411. (hl-pos (match-beginning 0))
  11412. (head (org-get-todo-sequence-head this))
  11413. (ass (assoc head org-todo-kwd-alist))
  11414. (interpret (nth 1 ass))
  11415. (done-word (nth 3 ass))
  11416. (final-done-word (nth 4 ass))
  11417. (org-last-state (or this ""))
  11418. (completion-ignore-case t)
  11419. (member (member this org-todo-keywords-1))
  11420. (tail (cdr member))
  11421. (org-state (cond
  11422. ((and org-todo-key-trigger
  11423. (or (and (equal arg '(4))
  11424. (eq org-use-fast-todo-selection 'prefix))
  11425. (and (not arg) org-use-fast-todo-selection
  11426. (not (eq org-use-fast-todo-selection
  11427. 'prefix)))))
  11428. ;; Use fast selection
  11429. (org-fast-todo-selection))
  11430. ((and (equal arg '(4))
  11431. (or (not org-use-fast-todo-selection)
  11432. (not org-todo-key-trigger)))
  11433. ;; Read a state with completion
  11434. (completing-read
  11435. "State: " (mapcar #'list org-todo-keywords-1)
  11436. nil t))
  11437. ((eq arg 'right)
  11438. (if this
  11439. (if tail (car tail) nil)
  11440. (car org-todo-keywords-1)))
  11441. ((eq arg 'left)
  11442. (unless (equal member org-todo-keywords-1)
  11443. (if this
  11444. (nth (- (length org-todo-keywords-1)
  11445. (length tail) 2)
  11446. org-todo-keywords-1)
  11447. (org-last org-todo-keywords-1))))
  11448. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11449. (setq arg nil))) ; hack to fall back to cycling
  11450. (arg
  11451. ;; user or caller requests a specific state
  11452. (cond
  11453. ((equal arg "") nil)
  11454. ((eq arg 'none) nil)
  11455. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11456. ((eq arg 'nextset)
  11457. (or (car (cdr (member head org-todo-heads)))
  11458. (car org-todo-heads)))
  11459. ((eq arg 'previousset)
  11460. (let ((org-todo-heads (reverse org-todo-heads)))
  11461. (or (car (cdr (member head org-todo-heads)))
  11462. (car org-todo-heads))))
  11463. ((car (member arg org-todo-keywords-1)))
  11464. ((stringp arg)
  11465. (user-error "State `%s' not valid in this file" arg))
  11466. ((nth (1- (prefix-numeric-value arg))
  11467. org-todo-keywords-1))))
  11468. ((null member) (or head (car org-todo-keywords-1)))
  11469. ((equal this final-done-word) nil) ;; -> make empty
  11470. ((null tail) nil) ;; -> first entry
  11471. ((memq interpret '(type priority))
  11472. (if (eq this-command last-command)
  11473. (car tail)
  11474. (if (> (length tail) 0)
  11475. (or done-word (car org-done-keywords))
  11476. nil)))
  11477. (t
  11478. (car tail))))
  11479. (org-state (or
  11480. (run-hook-with-args-until-success
  11481. 'org-todo-get-default-hook org-state org-last-state)
  11482. org-state))
  11483. (next (if org-state (concat " " org-state " ") " "))
  11484. (change-plist (list :type 'todo-state-change :from this :to org-state
  11485. :position startpos))
  11486. dolog now-done-p)
  11487. (when org-blocker-hook
  11488. (setq org-last-todo-state-is-todo
  11489. (not (member this org-done-keywords)))
  11490. (unless (save-excursion
  11491. (save-match-data
  11492. (org-with-wide-buffer
  11493. (run-hook-with-args-until-failure
  11494. 'org-blocker-hook change-plist))))
  11495. (if (called-interactively-p 'interactive)
  11496. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11497. this org-state org-block-entry-blocking)
  11498. ;; fail silently
  11499. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11500. this org-state org-block-entry-blocking)
  11501. (throw 'exit nil))))
  11502. (store-match-data match-data)
  11503. (replace-match next t t)
  11504. (cond ((equal this org-state)
  11505. (message "TODO state was already %s" (org-trim next)))
  11506. ((pos-visible-in-window-p hl-pos)
  11507. (message "TODO state changed to %s" (org-trim next))))
  11508. (unless head
  11509. (setq head (org-get-todo-sequence-head org-state)
  11510. ass (assoc head org-todo-kwd-alist)
  11511. interpret (nth 1 ass)
  11512. done-word (nth 3 ass)
  11513. final-done-word (nth 4 ass)))
  11514. (when (memq arg '(nextset previousset))
  11515. (message "Keyword-Set %d/%d: %s"
  11516. (- (length org-todo-sets) -1
  11517. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11518. (length org-todo-sets)
  11519. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11520. (setq org-last-todo-state-is-todo
  11521. (not (member org-state org-done-keywords)))
  11522. (setq now-done-p (and (member org-state org-done-keywords)
  11523. (not (member this org-done-keywords))))
  11524. (and logging (org-local-logging logging))
  11525. (when (and (or org-todo-log-states org-log-done)
  11526. (not (eq org-inhibit-logging t))
  11527. (not (memq arg '(nextset previousset))))
  11528. ;; we need to look at recording a time and note
  11529. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11530. (nth 2 (assoc this org-todo-log-states))))
  11531. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11532. (setq dolog 'time))
  11533. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11534. (and org-state
  11535. (member org-state org-not-done-keywords)
  11536. (not (member this org-not-done-keywords))))
  11537. ;; This is now a todo state and was not one before
  11538. ;; If there was a CLOSED time stamp, get rid of it.
  11539. (org-add-planning-info nil nil 'closed))
  11540. (when (and now-done-p org-log-done)
  11541. ;; It is now done, and it was not done before
  11542. (org-add-planning-info 'closed (org-current-effective-time))
  11543. (when (and (not dolog) (eq 'note org-log-done))
  11544. (org-add-log-setup 'done org-state this 'note)))
  11545. (when (and org-state dolog)
  11546. ;; This is a non-nil state, and we need to log it
  11547. (org-add-log-setup 'state org-state this dolog)))
  11548. ;; Fixup tag positioning
  11549. (org-todo-trigger-tag-changes org-state)
  11550. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11551. (when org-provide-todo-statistics
  11552. (org-update-parent-todo-statistics))
  11553. (run-hooks 'org-after-todo-state-change-hook)
  11554. (when (and arg (not (member org-state org-done-keywords)))
  11555. (setq head (org-get-todo-sequence-head org-state)))
  11556. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11557. ;; Do we need to trigger a repeat?
  11558. (when now-done-p
  11559. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11560. ;; This is for the agenda, take a snapshot of the headline.
  11561. (save-match-data
  11562. (setq org-agenda-headline-snapshot-before-repeat
  11563. (org-get-heading))))
  11564. (org-auto-repeat-maybe org-state))
  11565. ;; Fixup cursor location if close to the keyword
  11566. (when (and (outline-on-heading-p)
  11567. (not (bolp))
  11568. (save-excursion (beginning-of-line 1)
  11569. (looking-at org-todo-line-regexp))
  11570. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11571. (goto-char (or (match-end 2) (match-end 1)))
  11572. (and (looking-at " ") (just-one-space)))
  11573. (when org-trigger-hook
  11574. (save-excursion
  11575. (run-hook-with-args 'org-trigger-hook change-plist)))
  11576. (when commentp (org-toggle-comment))))))))
  11577. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11578. "Block turning an entry into a TODO, using the hierarchy.
  11579. This checks whether the current task should be blocked from state
  11580. changes. Such blocking occurs when:
  11581. 1. The task has children which are not all in a completed state.
  11582. 2. A task has a parent with the property :ORDERED:, and there
  11583. are siblings prior to the current task with incomplete
  11584. status.
  11585. 3. The parent of the task is blocked because it has siblings that should
  11586. be done first, or is child of a block grandparent TODO entry."
  11587. (if (not org-enforce-todo-dependencies)
  11588. t ; if locally turned off don't block
  11589. (catch 'dont-block
  11590. ;; If this is not a todo state change, or if this entry is already DONE,
  11591. ;; do not block
  11592. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11593. (member (plist-get change-plist :from)
  11594. (cons 'done org-done-keywords))
  11595. (member (plist-get change-plist :to)
  11596. (cons 'todo org-not-done-keywords))
  11597. (not (plist-get change-plist :to)))
  11598. (throw 'dont-block t))
  11599. ;; If this task has children, and any are undone, it's blocked
  11600. (save-excursion
  11601. (org-back-to-heading t)
  11602. (let ((this-level (funcall outline-level)))
  11603. (outline-next-heading)
  11604. (let ((child-level (funcall outline-level)))
  11605. (while (and (not (eobp))
  11606. (> child-level this-level))
  11607. ;; this todo has children, check whether they are all
  11608. ;; completed
  11609. (when (and (not (org-entry-is-done-p))
  11610. (org-entry-is-todo-p))
  11611. (setq org-block-entry-blocking (org-get-heading))
  11612. (throw 'dont-block nil))
  11613. (outline-next-heading)
  11614. (setq child-level (funcall outline-level))))))
  11615. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11616. ;; any previous siblings are undone, it's blocked
  11617. (save-excursion
  11618. (org-back-to-heading t)
  11619. (let* ((pos (point))
  11620. (parent-pos (and (org-up-heading-safe) (point))))
  11621. (unless parent-pos (throw 'dont-block t)) ; no parent
  11622. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11623. (forward-line 1)
  11624. (re-search-forward org-not-done-heading-regexp pos t))
  11625. (setq org-block-entry-blocking (match-string 0))
  11626. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11627. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11628. (while t
  11629. (goto-char parent-pos)
  11630. (unless (looking-at org-not-done-heading-regexp)
  11631. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11632. (setq pos (point))
  11633. (setq parent-pos (and (org-up-heading-safe) (point)))
  11634. (unless parent-pos (throw 'dont-block t)) ; no parent
  11635. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11636. (forward-line 1)
  11637. (re-search-forward org-not-done-heading-regexp pos t)
  11638. (setq org-block-entry-blocking (org-get-heading)))
  11639. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11640. (defcustom org-track-ordered-property-with-tag nil
  11641. "Should the ORDERED property also be shown as a tag?
  11642. The ORDERED property decides if an entry should require subtasks to be
  11643. completed in sequence. Since a property is not very visible, setting
  11644. this option means that toggling the ORDERED property with the command
  11645. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11646. not relevant for the behavior, but it makes things more visible.
  11647. Note that toggling the tag with tags commands will not change the property
  11648. and therefore not influence behavior!
  11649. This can be t, meaning the tag ORDERED should be used, It can also be a
  11650. string to select a different tag for this task."
  11651. :group 'org-todo
  11652. :type '(choice
  11653. (const :tag "No tracking" nil)
  11654. (const :tag "Track with ORDERED tag" t)
  11655. (string :tag "Use other tag")))
  11656. (defun org-toggle-ordered-property ()
  11657. "Toggle the ORDERED property of the current entry.
  11658. For better visibility, you can track the value of this property with a tag.
  11659. See variable `org-track-ordered-property-with-tag'."
  11660. (interactive)
  11661. (let* ((t1 org-track-ordered-property-with-tag)
  11662. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11663. (save-excursion
  11664. (org-back-to-heading)
  11665. (if (org-entry-get nil "ORDERED")
  11666. (progn
  11667. (org-delete-property "ORDERED")
  11668. (and tag (org-toggle-tag tag 'off))
  11669. (message "Subtasks can be completed in arbitrary order"))
  11670. (org-entry-put nil "ORDERED" "t")
  11671. (and tag (org-toggle-tag tag 'on))
  11672. (message "Subtasks must be completed in sequence")))))
  11673. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11674. (defun org-block-todo-from-checkboxes (change-plist)
  11675. "Block turning an entry into a TODO, using checkboxes.
  11676. This checks whether the current task should be blocked from state
  11677. changes because there are unchecked boxes in this entry."
  11678. (if (not org-enforce-todo-checkbox-dependencies)
  11679. t ; if locally turned off don't block
  11680. (catch 'dont-block
  11681. ;; If this is not a todo state change, or if this entry is already DONE,
  11682. ;; do not block
  11683. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11684. (member (plist-get change-plist :from)
  11685. (cons 'done org-done-keywords))
  11686. (member (plist-get change-plist :to)
  11687. (cons 'todo org-not-done-keywords))
  11688. (not (plist-get change-plist :to)))
  11689. (throw 'dont-block t))
  11690. ;; If this task has checkboxes that are not checked, it's blocked
  11691. (save-excursion
  11692. (org-back-to-heading t)
  11693. (let ((beg (point)) end)
  11694. (outline-next-heading)
  11695. (setq end (point))
  11696. (goto-char beg)
  11697. (when (org-list-search-forward
  11698. (concat (org-item-beginning-re)
  11699. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11700. "\\[[- ]\\]")
  11701. end t)
  11702. (when (boundp 'org-blocked-by-checkboxes)
  11703. (setq org-blocked-by-checkboxes t))
  11704. (throw 'dont-block nil))))
  11705. t))) ; do not block
  11706. (defun org-entry-blocked-p ()
  11707. "Non-nil if entry at point is blocked."
  11708. (and (not (org-entry-get nil "NOBLOCKING"))
  11709. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11710. (not (run-hook-with-args-until-failure
  11711. 'org-blocker-hook
  11712. (list :type 'todo-state-change
  11713. :position (point)
  11714. :from 'todo
  11715. :to 'done)))))
  11716. (defun org-update-statistics-cookies (all)
  11717. "Update the statistics cookie, either from TODO or from checkboxes.
  11718. This should be called with the cursor in a line with a statistics cookie."
  11719. (interactive "P")
  11720. (if all
  11721. (progn
  11722. (org-update-checkbox-count 'all)
  11723. (org-map-entries 'org-update-parent-todo-statistics))
  11724. (if (not (org-at-heading-p))
  11725. (org-update-checkbox-count)
  11726. (let ((pos (point-marker))
  11727. end l1 l2)
  11728. (ignore-errors (org-back-to-heading t))
  11729. (if (not (org-at-heading-p))
  11730. (org-update-checkbox-count)
  11731. (setq l1 (org-outline-level))
  11732. (setq end (save-excursion
  11733. (outline-next-heading)
  11734. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11735. (point)))
  11736. (if (and (save-excursion
  11737. (re-search-forward
  11738. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11739. (not (save-excursion (re-search-forward
  11740. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11741. (org-update-checkbox-count)
  11742. (if (and l2 (> l2 l1))
  11743. (progn
  11744. (goto-char end)
  11745. (org-update-parent-todo-statistics))
  11746. (goto-char pos)
  11747. (beginning-of-line 1)
  11748. (while (re-search-forward
  11749. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11750. (point-at-eol) t)
  11751. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11752. (goto-char pos)
  11753. (move-marker pos nil)))))
  11754. (defvar org-entry-property-inherited-from) ;; defined below
  11755. (defun org-update-parent-todo-statistics ()
  11756. "Update any statistics cookie in the parent of the current headline.
  11757. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11758. the entire subtree and this will travel up the hierarchy and update
  11759. statistics everywhere."
  11760. (let* ((prop (save-excursion (org-up-heading-safe)
  11761. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11762. (recursive (or (not org-hierarchical-todo-statistics)
  11763. (and prop (string-match "\\<recursive\\>" prop))))
  11764. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11765. 0))
  11766. (first t)
  11767. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11768. level ltoggle l1 new ndel
  11769. (cnt-all 0) (cnt-done 0) is-percent kwd
  11770. checkbox-beg ov ovs ove cookie-present)
  11771. (catch 'exit
  11772. (save-excursion
  11773. (beginning-of-line 1)
  11774. (setq ltoggle (funcall outline-level))
  11775. ;; Three situations are to consider:
  11776. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11777. ;; to the top-level ancestor on the headline;
  11778. ;; 2. If parent has "recursive" property, repeat up to the
  11779. ;; headline setting that property, taking inheritance into
  11780. ;; account;
  11781. ;; 3. Else, move up to direct parent and proceed only once.
  11782. (while (and (setq level (org-up-heading-safe))
  11783. (or recursive first)
  11784. (>= (point) lim))
  11785. (setq first nil cookie-present nil)
  11786. (unless (and level
  11787. (not (string-match
  11788. "\\<checkbox\\>"
  11789. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11790. "")))))
  11791. (throw 'exit nil))
  11792. (while (re-search-forward box-re (point-at-eol) t)
  11793. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11794. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11795. (save-match-data
  11796. (unless (outline-next-heading) (throw 'exit nil))
  11797. (while (and (looking-at org-complex-heading-regexp)
  11798. (> (setq l1 (length (match-string 1))) level))
  11799. (setq kwd (and (or recursive (= l1 ltoggle))
  11800. (match-string 2)))
  11801. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11802. (and (eq org-provide-todo-statistics t)
  11803. (or (member kwd org-done-keywords)))
  11804. (and (listp org-provide-todo-statistics)
  11805. (stringp (car org-provide-todo-statistics))
  11806. (or (member kwd org-provide-todo-statistics)
  11807. (member kwd org-done-keywords)))
  11808. (and (listp org-provide-todo-statistics)
  11809. (listp (car org-provide-todo-statistics))
  11810. (or (member kwd (car org-provide-todo-statistics))
  11811. (and (member kwd org-done-keywords)
  11812. (member kwd (cadr org-provide-todo-statistics))))))
  11813. (setq cnt-all (1+ cnt-all))
  11814. (and (eq org-provide-todo-statistics t)
  11815. kwd
  11816. (setq cnt-all (1+ cnt-all))))
  11817. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11818. (member kwd org-done-keywords))
  11819. (and (listp org-provide-todo-statistics)
  11820. (listp (car org-provide-todo-statistics))
  11821. (member kwd org-done-keywords)
  11822. (member kwd (cadr org-provide-todo-statistics)))
  11823. (and (listp org-provide-todo-statistics)
  11824. (stringp (car org-provide-todo-statistics))
  11825. (member kwd org-done-keywords)))
  11826. (setq cnt-done (1+ cnt-done)))
  11827. (outline-next-heading)))
  11828. (setq new
  11829. (if is-percent
  11830. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11831. (max 1 cnt-all)))
  11832. (format "[%d/%d]" cnt-done cnt-all))
  11833. ndel (- (match-end 0) checkbox-beg))
  11834. ;; handle overlays when updating cookie from column view
  11835. (when (setq ov (car (overlays-at checkbox-beg)))
  11836. (setq ovs (overlay-start ov) ove (overlay-end ov))
  11837. (delete-overlay ov))
  11838. (goto-char checkbox-beg)
  11839. (insert new)
  11840. (delete-region (point) (+ (point) ndel))
  11841. (when org-auto-align-tags (org-fix-tags-on-the-fly))
  11842. (when ov (move-overlay ov ovs ove)))
  11843. (when cookie-present
  11844. (run-hook-with-args 'org-after-todo-statistics-hook
  11845. cnt-done (- cnt-all cnt-done))))))
  11846. (run-hooks 'org-todo-statistics-hook)))
  11847. (defvar org-after-todo-statistics-hook nil
  11848. "Hook that is called after a TODO statistics cookie has been updated.
  11849. Each function is called with two arguments: the number of not-done entries
  11850. and the number of done entries.
  11851. For example, the following function, when added to this hook, will switch
  11852. an entry to DONE when all children are done, and back to TODO when new
  11853. entries are set to a TODO status. Note that this hook is only called
  11854. when there is a statistics cookie in the headline!
  11855. \(defun org-summary-todo (n-done n-not-done)
  11856. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11857. \(let (org-log-done org-log-states) ; turn off logging
  11858. \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11859. ")
  11860. (defvar org-todo-statistics-hook nil
  11861. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11862. This hook runs even if there is no statistics cookie present, in which case
  11863. `org-after-todo-statistics-hook' would not run.")
  11864. (defun org-todo-trigger-tag-changes (state)
  11865. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11866. (let ((l org-todo-state-tags-triggers)
  11867. changes)
  11868. (when (or (not state) (equal state ""))
  11869. (setq changes (append changes (cdr (assoc "" l)))))
  11870. (when (and (stringp state) (> (length state) 0))
  11871. (setq changes (append changes (cdr (assoc state l)))))
  11872. (when (member state org-not-done-keywords)
  11873. (setq changes (append changes (cdr (assoc 'todo l)))))
  11874. (when (member state org-done-keywords)
  11875. (setq changes (append changes (cdr (assoc 'done l)))))
  11876. (dolist (c changes)
  11877. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11878. (defun org-local-logging (value)
  11879. "Get logging settings from a property VALUE."
  11880. ;; Directly set the variables, they are already local.
  11881. (setq org-log-done nil
  11882. org-log-repeat nil
  11883. org-todo-log-states nil)
  11884. (dolist (w (org-split-string value))
  11885. (let (a)
  11886. (cond
  11887. ((setq a (assoc w org-startup-options))
  11888. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11889. (set (nth 1 a) (nth 2 a))))
  11890. ((setq a (org-extract-log-state-settings w))
  11891. (and (member (car a) org-todo-keywords-1)
  11892. (push a org-todo-log-states)))))))
  11893. (defun org-get-todo-sequence-head (kwd)
  11894. "Return the head of the TODO sequence to which KWD belongs.
  11895. If KWD is not set, check if there is a text property remembering the
  11896. right sequence."
  11897. (let (p)
  11898. (cond
  11899. ((not kwd)
  11900. (or (get-text-property (point-at-bol) 'org-todo-head)
  11901. (progn
  11902. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11903. nil (point-at-eol)))
  11904. (get-text-property p 'org-todo-head))))
  11905. ((not (member kwd org-todo-keywords-1))
  11906. (car org-todo-keywords-1))
  11907. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11908. (defun org-fast-todo-selection ()
  11909. "Fast TODO keyword selection with single keys.
  11910. Returns the new TODO keyword, or nil if no state change should occur."
  11911. (let* ((fulltable org-todo-key-alist)
  11912. (done-keywords org-done-keywords) ;; needed for the faces.
  11913. (maxlen (apply 'max (mapcar
  11914. (lambda (x)
  11915. (if (stringp (car x)) (string-width (car x)) 0))
  11916. fulltable)))
  11917. (expert nil)
  11918. (fwidth (+ maxlen 3 1 3))
  11919. (ncol (/ (- (window-width) 4) fwidth))
  11920. tg cnt e c tbl
  11921. groups ingroup)
  11922. (save-excursion
  11923. (save-window-excursion
  11924. (if expert
  11925. (set-buffer (get-buffer-create " *Org todo*"))
  11926. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11927. (erase-buffer)
  11928. (setq-local org-done-keywords done-keywords)
  11929. (setq tbl fulltable cnt 0)
  11930. (while (setq e (pop tbl))
  11931. (cond
  11932. ((equal e '(:startgroup))
  11933. (push '() groups) (setq ingroup t)
  11934. (unless (= cnt 0)
  11935. (setq cnt 0)
  11936. (insert "\n"))
  11937. (insert "{ "))
  11938. ((equal e '(:endgroup))
  11939. (setq ingroup nil cnt 0)
  11940. (insert "}\n"))
  11941. ((equal e '(:newline))
  11942. (unless (= cnt 0)
  11943. (setq cnt 0)
  11944. (insert "\n")
  11945. (setq e (car tbl))
  11946. (while (equal (car tbl) '(:newline))
  11947. (insert "\n")
  11948. (setq tbl (cdr tbl)))))
  11949. (t
  11950. (setq tg (car e) c (cdr e))
  11951. (when ingroup (push tg (car groups)))
  11952. (setq tg (org-add-props tg nil 'face
  11953. (org-get-todo-face tg)))
  11954. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11955. (insert "[" c "] " tg (make-string
  11956. (- fwidth 4 (length tg)) ?\ ))
  11957. (when (= (setq cnt (1+ cnt)) ncol)
  11958. (insert "\n")
  11959. (when ingroup (insert " "))
  11960. (setq cnt 0)))))
  11961. (insert "\n")
  11962. (goto-char (point-min))
  11963. (unless expert (org-fit-window-to-buffer))
  11964. (message "[a-z..]:Set [SPC]:clear")
  11965. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11966. (cond
  11967. ((or (= c ?\C-g)
  11968. (and (= c ?q) (not (rassoc c fulltable))))
  11969. (setq quit-flag t))
  11970. ((= c ?\ ) nil)
  11971. ((setq e (rassoc c fulltable) tg (car e))
  11972. tg)
  11973. (t (setq quit-flag t)))))))
  11974. (defun org-entry-is-todo-p ()
  11975. (member (org-get-todo-state) org-not-done-keywords))
  11976. (defun org-entry-is-done-p ()
  11977. (member (org-get-todo-state) org-done-keywords))
  11978. (defun org-get-todo-state ()
  11979. "Return the TODO keyword of the current subtree."
  11980. (save-excursion
  11981. (org-back-to-heading t)
  11982. (and (looking-at org-todo-line-regexp)
  11983. (match-end 2)
  11984. (match-string 2))))
  11985. (defun org-at-date-range-p (&optional inactive-ok)
  11986. "Non-nil if point is inside a date range.
  11987. When optional argument INACTIVE-OK is non-nil, also consider
  11988. inactive time ranges.
  11989. When this function returns a non-nil value, match data is set
  11990. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11991. on INACTIVE-OK."
  11992. (interactive)
  11993. (save-excursion
  11994. (catch 'exit
  11995. (let ((pos (point)))
  11996. (skip-chars-backward "^[<\r\n")
  11997. (skip-chars-backward "<[")
  11998. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11999. (>= (match-end 0) pos)
  12000. (throw 'exit t))
  12001. (skip-chars-backward "^<[\r\n")
  12002. (skip-chars-backward "<[")
  12003. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  12004. (>= (match-end 0) pos)
  12005. (throw 'exit t)))
  12006. nil)))
  12007. (defun org-get-repeat (&optional tagline)
  12008. "Check if there is a deadline/schedule with repeater in this entry."
  12009. (save-match-data
  12010. (save-excursion
  12011. (org-back-to-heading t)
  12012. (and (re-search-forward (if tagline
  12013. (concat tagline "\\s-*" org-repeat-re)
  12014. org-repeat-re)
  12015. (org-entry-end-position) t)
  12016. (match-string-no-properties 1)))))
  12017. (defvar org-last-changed-timestamp)
  12018. (defvar org-last-inserted-timestamp)
  12019. (defvar org-log-post-message)
  12020. (defvar org-log-note-purpose)
  12021. (defvar org-log-note-how nil)
  12022. (defvar org-log-note-extra)
  12023. (defun org-auto-repeat-maybe (done-word)
  12024. "Check if the current headline contains a repeated time-stamp.
  12025. If yes, set TODO state back to what it was and change the base date
  12026. of repeating deadline/scheduled time stamps to new date.
  12027. This function is run automatically after each state change to a DONE state."
  12028. (let* ((repeat (org-get-repeat))
  12029. (aa (assoc org-last-state org-todo-kwd-alist))
  12030. (interpret (nth 1 aa))
  12031. (head (nth 2 aa))
  12032. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  12033. (msg "Entry repeats: ")
  12034. (org-log-done nil)
  12035. (org-todo-log-states nil))
  12036. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  12037. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  12038. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  12039. org-todo-repeat-to-state)))
  12040. (unless (and to-state (member to-state org-todo-keywords-1))
  12041. (setq to-state (if (eq interpret 'type) org-last-state head)))
  12042. (org-todo to-state))
  12043. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  12044. (org-entry-put nil "LAST_REPEAT" (format-time-string
  12045. (org-time-stamp-format t t))))
  12046. (when org-log-repeat
  12047. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  12048. (memq 'org-add-log-note post-command-hook))
  12049. ;; We are already setup for some record.
  12050. (when (eq org-log-repeat 'note)
  12051. ;; Make sure we take a note, not only a time stamp.
  12052. (setq org-log-note-how 'note))
  12053. ;; Set up for taking a record.
  12054. (org-add-log-setup 'state
  12055. (or done-word (car org-done-keywords))
  12056. org-last-state
  12057. org-log-repeat)))
  12058. (org-back-to-heading t)
  12059. (org-add-planning-info nil nil 'closed)
  12060. (let ((end (save-excursion (outline-next-heading) (point))))
  12061. (while (re-search-forward org-ts-regexp end t)
  12062. (when (save-match-data
  12063. (or (org-at-planning-p)
  12064. (org-at-property-p)
  12065. (eq (org-element-type (save-excursion
  12066. (backward-char)
  12067. (org-element-context)))
  12068. 'timestamp)))
  12069. (let ((type (cond ((match-end 1) org-scheduled-string)
  12070. ((match-end 3) org-deadline-string)
  12071. (t "Plain:")))
  12072. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  12073. (cond
  12074. ((not
  12075. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12076. ;; Time-stamps without a repeater are usually skipped.
  12077. ;; However, a SCHEDULED time-stamp without one is
  12078. ;; removed, as it is considered as no longer relevant.
  12079. (when (equal type org-scheduled-string)
  12080. (org-remove-timestamp-with-keyword type)))
  12081. (t
  12082. (let ((n (string-to-number (match-string 2 ts)))
  12083. (what (match-string 3 ts)))
  12084. (when (equal what "w") (setq n (* n 7) what "d"))
  12085. (when (and (equal what "h")
  12086. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12087. ts)))
  12088. (user-error
  12089. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12090. has been set"
  12091. n))
  12092. ;; Preparation, see if we need to modify the start
  12093. ;; date for the change.
  12094. (when (match-end 1)
  12095. (let ((time (save-match-data (org-time-string-to-time ts))))
  12096. (cond
  12097. ((equal (match-string 1 ts) ".")
  12098. ;; Shift starting date to today
  12099. (org-timestamp-change
  12100. (- (org-today) (time-to-days time))
  12101. 'day))
  12102. ((equal (match-string 1 ts) "+")
  12103. (let ((nshiftmax 10)
  12104. (nshift 0))
  12105. (while (or (= nshift 0)
  12106. (not (time-less-p (current-time) time)))
  12107. (when (= (cl-incf nshift) nshiftmax)
  12108. (or (y-or-n-p
  12109. (format "%d repeater intervals were not \
  12110. enough to shift date past today. Continue? "
  12111. nshift))
  12112. (user-error "Abort")))
  12113. (org-timestamp-change n (cdr (assoc what whata)))
  12114. (org-at-timestamp-p t)
  12115. (setq ts (match-string 1))
  12116. (setq time
  12117. (save-match-data
  12118. (org-time-string-to-time ts)))))
  12119. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12120. ;; Rematch, so that we have everything in
  12121. ;; place for the real shift.
  12122. (org-at-timestamp-p t)
  12123. (setq ts (match-string 1))
  12124. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12125. ts)))))
  12126. (save-excursion
  12127. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12128. (setq msg
  12129. (concat
  12130. msg type " " org-last-changed-timestamp " ")))))))))
  12131. (setq org-log-post-message msg)
  12132. (message "%s" msg))))
  12133. (defun org-show-todo-tree (arg)
  12134. "Make a compact tree which shows all headlines marked with TODO.
  12135. The tree will show the lines where the regexp matches, and all higher
  12136. headlines above the match.
  12137. With a \\[universal-argument] prefix, prompt for a regexp to match.
  12138. With a numeric prefix N, construct a sparse tree for the Nth element
  12139. of `org-todo-keywords-1'."
  12140. (interactive "P")
  12141. (let ((case-fold-search nil)
  12142. (kwd-re
  12143. (cond ((null arg) org-not-done-regexp)
  12144. ((equal arg '(4))
  12145. (let ((kwd
  12146. (completing-read "Keyword (or KWD1|KWD2|...): "
  12147. (mapcar #'list org-todo-keywords-1))))
  12148. (concat "\\("
  12149. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12150. "\\)\\>")))
  12151. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12152. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12153. org-todo-keywords-1)))
  12154. (t (user-error "Invalid prefix argument: %s" arg)))))
  12155. (message "%d TODO entries found"
  12156. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12157. (defun org-deadline (arg &optional time)
  12158. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12159. With one universal prefix argument, remove any deadline from the item.
  12160. With two universal prefix arguments, prompt for a warning delay.
  12161. With argument TIME, set the deadline at the corresponding date. TIME
  12162. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12163. (interactive "P")
  12164. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12165. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12166. 'region-start-level 'region))
  12167. org-loop-over-headlines-in-active-region)
  12168. (org-map-entries
  12169. `(org-deadline ',arg ,time)
  12170. org-loop-over-headlines-in-active-region
  12171. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12172. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12173. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12174. (repeater (and old-date
  12175. (string-match
  12176. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12177. old-date)
  12178. (match-string 1 old-date))))
  12179. (cond
  12180. ((equal arg '(4))
  12181. (when (and old-date org-log-redeadline)
  12182. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12183. (org-remove-timestamp-with-keyword org-deadline-string)
  12184. (message "Item no longer has a deadline."))
  12185. ((equal arg '(16))
  12186. (save-excursion
  12187. (org-back-to-heading t)
  12188. (if (re-search-forward
  12189. org-deadline-time-regexp
  12190. (save-excursion (outline-next-heading) (point)) t)
  12191. (let* ((rpl0 (match-string 1))
  12192. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12193. (replace-match
  12194. (concat org-deadline-string
  12195. " <" rpl
  12196. (format " -%dd"
  12197. (abs
  12198. (- (time-to-days
  12199. (save-match-data
  12200. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12201. (time-to-days old-date-time))))
  12202. ">") t t))
  12203. (user-error "No deadline information to update"))))
  12204. (t
  12205. (org-add-planning-info 'deadline time 'closed)
  12206. (when (and old-date
  12207. org-log-redeadline
  12208. (not (equal old-date org-last-inserted-timestamp)))
  12209. (org-add-log-setup
  12210. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12211. (when repeater
  12212. (save-excursion
  12213. (org-back-to-heading t)
  12214. (when (re-search-forward (concat org-deadline-string " "
  12215. org-last-inserted-timestamp)
  12216. (save-excursion
  12217. (outline-next-heading) (point)) t)
  12218. (goto-char (1- (match-end 0)))
  12219. (insert " " repeater)
  12220. (setq org-last-inserted-timestamp
  12221. (concat (substring org-last-inserted-timestamp 0 -1)
  12222. " " repeater
  12223. (substring org-last-inserted-timestamp -1))))))
  12224. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12225. (defun org-schedule (arg &optional time)
  12226. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12227. With one universal prefix argument, remove any scheduling date from the item.
  12228. With two universal prefix arguments, prompt for a delay cookie.
  12229. With argument TIME, scheduled at the corresponding date. TIME can
  12230. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12231. (interactive "P")
  12232. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12233. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12234. 'region-start-level 'region))
  12235. org-loop-over-headlines-in-active-region)
  12236. (org-map-entries
  12237. `(org-schedule ',arg ,time)
  12238. org-loop-over-headlines-in-active-region
  12239. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12240. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12241. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12242. (repeater (and old-date
  12243. (string-match
  12244. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12245. old-date)
  12246. (match-string 1 old-date))))
  12247. (cond
  12248. ((equal arg '(4))
  12249. (progn
  12250. (when (and old-date org-log-reschedule)
  12251. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12252. (org-remove-timestamp-with-keyword org-scheduled-string)
  12253. (message "Item is no longer scheduled.")))
  12254. ((equal arg '(16))
  12255. (save-excursion
  12256. (org-back-to-heading t)
  12257. (if (re-search-forward
  12258. org-scheduled-time-regexp
  12259. (save-excursion (outline-next-heading) (point)) t)
  12260. (let* ((rpl0 (match-string 1))
  12261. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12262. (replace-match
  12263. (concat org-scheduled-string
  12264. " <" rpl
  12265. (format " -%dd"
  12266. (abs
  12267. (- (time-to-days
  12268. (save-match-data
  12269. (org-read-date nil t nil "Delay until" old-date-time)))
  12270. (time-to-days old-date-time))))
  12271. ">") t t))
  12272. (user-error "No scheduled information to update"))))
  12273. (t
  12274. (org-add-planning-info 'scheduled time 'closed)
  12275. (when (and old-date
  12276. org-log-reschedule
  12277. (not (equal old-date org-last-inserted-timestamp)))
  12278. (org-add-log-setup
  12279. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12280. (when repeater
  12281. (save-excursion
  12282. (org-back-to-heading t)
  12283. (when (re-search-forward (concat org-scheduled-string " "
  12284. org-last-inserted-timestamp)
  12285. (save-excursion
  12286. (outline-next-heading) (point)) t)
  12287. (goto-char (1- (match-end 0)))
  12288. (insert " " repeater)
  12289. (setq org-last-inserted-timestamp
  12290. (concat (substring org-last-inserted-timestamp 0 -1)
  12291. " " repeater
  12292. (substring org-last-inserted-timestamp -1))))))
  12293. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12294. (defun org-get-scheduled-time (pom &optional inherit)
  12295. "Get the scheduled time as a time tuple, of a format suitable
  12296. for calling org-schedule with, or if there is no scheduling,
  12297. returns nil."
  12298. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12299. (when time
  12300. (apply 'encode-time (org-parse-time-string time)))))
  12301. (defun org-get-deadline-time (pom &optional inherit)
  12302. "Get the deadline as a time tuple, of a format suitable for
  12303. calling org-deadline with, or if there is no scheduling, returns
  12304. nil."
  12305. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12306. (when time
  12307. (apply 'encode-time (org-parse-time-string time)))))
  12308. (defun org-remove-timestamp-with-keyword (keyword)
  12309. "Remove all time stamps with KEYWORD in the current entry."
  12310. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12311. beg)
  12312. (save-excursion
  12313. (org-back-to-heading t)
  12314. (setq beg (point))
  12315. (outline-next-heading)
  12316. (while (re-search-backward re beg t)
  12317. (replace-match "")
  12318. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12319. (equal (char-before) ?\ ))
  12320. (backward-delete-char 1)
  12321. (when (string-match "^[ \t]*$" (buffer-substring
  12322. (point-at-bol) (point-at-eol)))
  12323. (delete-region (point-at-bol)
  12324. (min (point-max) (1+ (point-at-eol))))))))))
  12325. (defvar org-time-was-given) ; dynamically scoped parameter
  12326. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12327. (defun org-at-planning-p ()
  12328. "Non-nil when point is on a planning info line."
  12329. ;; This is as accurate and faster than `org-element-at-point' since
  12330. ;; planning info location is fixed in the section.
  12331. (org-with-wide-buffer
  12332. (beginning-of-line)
  12333. (and (looking-at-p org-planning-line-re)
  12334. (eq (point)
  12335. (ignore-errors
  12336. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12337. (org-back-to-heading t)
  12338. (org-with-limited-levels (org-back-to-heading t)))
  12339. (line-beginning-position 2))))))
  12340. (defun org-add-planning-info (what &optional time &rest remove)
  12341. "Insert new timestamp with keyword in the planning line.
  12342. WHAT indicates what kind of time stamp to add. It is a symbol
  12343. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12344. the time to use. If none is given, the user is prompted for
  12345. a date. REMOVE indicates what kind of entries to remove. An old
  12346. WHAT entry will also be removed."
  12347. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12348. (catch 'exit
  12349. (when (and (memq what '(scheduled deadline))
  12350. (or (not time)
  12351. (and (stringp time)
  12352. (string-match "^[-+]+[0-9]" time))))
  12353. ;; Try to get a default date/time from existing timestamp
  12354. (save-excursion
  12355. (org-back-to-heading t)
  12356. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12357. (when (re-search-forward (if (eq what 'scheduled)
  12358. org-scheduled-time-regexp
  12359. org-deadline-time-regexp)
  12360. end t)
  12361. (setq ts (match-string 1)
  12362. default-time (apply 'encode-time (org-parse-time-string ts))
  12363. default-input (and ts (org-get-compact-tod ts)))))))
  12364. (when what
  12365. (setq time
  12366. (if (stringp time)
  12367. ;; This is a string (relative or absolute), set
  12368. ;; proper date.
  12369. (apply #'encode-time
  12370. (org-read-date-analyze
  12371. time default-time (decode-time default-time)))
  12372. ;; If necessary, get the time from the user
  12373. (or time (org-read-date nil 'to-time nil nil
  12374. default-time default-input)))))
  12375. (org-with-wide-buffer
  12376. (org-back-to-heading t)
  12377. (forward-line)
  12378. (unless (bolp) (insert "\n"))
  12379. (cond ((looking-at-p org-planning-line-re)
  12380. ;; Move to current indentation.
  12381. (skip-chars-forward " \t")
  12382. ;; Check if we have to remove something.
  12383. (dolist (type (if what (cons what remove) remove))
  12384. (save-excursion
  12385. (when (re-search-forward
  12386. (cl-case type
  12387. (closed org-closed-time-regexp)
  12388. (deadline org-deadline-time-regexp)
  12389. (scheduled org-scheduled-time-regexp)
  12390. (otherwise
  12391. (error "Invalid planning type: %s" type)))
  12392. (line-end-position) t)
  12393. ;; Delete until next keyword or end of line.
  12394. (delete-region
  12395. (match-beginning 0)
  12396. (if (re-search-forward org-keyword-time-not-clock-regexp
  12397. (line-end-position)
  12398. t)
  12399. (match-beginning 0)
  12400. (line-end-position))))))
  12401. ;; If there is nothing more to add and no more keyword
  12402. ;; is left, remove the line completely.
  12403. (if (and (looking-at-p "[ \t]*$") (not what))
  12404. (delete-region (line-beginning-position)
  12405. (line-beginning-position 2))
  12406. ;; If we removed last keyword, do not leave trailing
  12407. ;; white space at the end of line.
  12408. (let ((p (point)))
  12409. (save-excursion
  12410. (end-of-line)
  12411. (unless (= (skip-chars-backward " \t" p) 0)
  12412. (delete-region (point) (line-end-position)))))))
  12413. ((not what) (throw 'exit nil)) ; Nothing to do.
  12414. (t (insert-before-markers "\n")
  12415. (backward-char 1)
  12416. (when org-adapt-indentation
  12417. (indent-to-column (1+ (org-outline-level))))))
  12418. (when what
  12419. ;; Insert planning keyword.
  12420. (insert (cl-case what
  12421. (closed org-closed-string)
  12422. (deadline org-deadline-string)
  12423. (scheduled org-scheduled-string)
  12424. (otherwise (error "Invalid planning type: %s" what)))
  12425. " ")
  12426. ;; Insert associated timestamp.
  12427. (let ((ts (org-insert-time-stamp
  12428. time
  12429. (or org-time-was-given
  12430. (and (eq what 'closed) org-log-done-with-time))
  12431. (eq what 'closed)
  12432. nil nil (list org-end-time-was-given))))
  12433. (unless (eolp) (insert " "))
  12434. ts))))))
  12435. (defvar org-log-note-marker (make-marker)
  12436. "Marker pointing at the entry where the note is to be inserted.")
  12437. (defvar org-log-note-purpose nil)
  12438. (defvar org-log-note-state nil)
  12439. (defvar org-log-note-previous-state nil)
  12440. (defvar org-log-note-extra nil)
  12441. (defvar org-log-note-window-configuration nil)
  12442. (defvar org-log-note-return-to (make-marker))
  12443. (defvar org-log-note-effective-time nil
  12444. "Remembered current time so that dynamically scoped
  12445. `org-extend-today-until' affects timestamps in state change log")
  12446. (defvar org-log-post-message nil
  12447. "Message to be displayed after a log note has been stored.
  12448. The auto-repeater uses this.")
  12449. (defun org-add-note ()
  12450. "Add a note to the current entry.
  12451. This is done in the same way as adding a state change note."
  12452. (interactive)
  12453. (org-add-log-setup 'note))
  12454. (defun org-log-beginning (&optional create)
  12455. "Return expected start of log notes in current entry.
  12456. When optional argument CREATE is non-nil, the function creates
  12457. a drawer to store notes, if necessary. Returned position ignores
  12458. narrowing."
  12459. (org-with-wide-buffer
  12460. (let ((drawer (org-log-into-drawer)))
  12461. (cond
  12462. (drawer
  12463. (org-end-of-meta-data)
  12464. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12465. (end (if (org-at-heading-p) (point)
  12466. (save-excursion (outline-next-heading) (point))))
  12467. (case-fold-search t))
  12468. (catch 'exit
  12469. ;; Try to find existing drawer.
  12470. (while (re-search-forward regexp end t)
  12471. (let ((element (org-element-at-point)))
  12472. (when (eq (org-element-type element) 'drawer)
  12473. (let ((cend (org-element-property :contents-end element)))
  12474. (when (and (not org-log-states-order-reversed) cend)
  12475. (goto-char cend)))
  12476. (throw 'exit nil))))
  12477. ;; No drawer found. Create one, if permitted.
  12478. (when create
  12479. (unless (bolp) (insert "\n"))
  12480. (let ((beg (point)))
  12481. (insert ":" drawer ":\n:END:\n")
  12482. (org-indent-region beg (point)))
  12483. (end-of-line -1)))))
  12484. (t
  12485. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12486. (skip-chars-forward " \t\n")
  12487. (beginning-of-line)
  12488. (unless org-log-states-order-reversed
  12489. (org-skip-over-state-notes)
  12490. (skip-chars-backward " \t\n")
  12491. (forward-line)))))
  12492. (if (bolp) (point) (line-beginning-position 2))))
  12493. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12494. "Set up the post command hook to take a note.
  12495. If this is about to TODO state change, the new state is expected in STATE.
  12496. HOW is an indicator what kind of note should be created.
  12497. EXTRA is additional text that will be inserted into the notes buffer."
  12498. (move-marker org-log-note-marker (point))
  12499. (setq org-log-note-purpose purpose
  12500. org-log-note-state state
  12501. org-log-note-previous-state prev-state
  12502. org-log-note-how how
  12503. org-log-note-extra extra
  12504. org-log-note-effective-time (org-current-effective-time))
  12505. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12506. (defun org-skip-over-state-notes ()
  12507. "Skip past the list of State notes in an entry."
  12508. (when (ignore-errors (goto-char (org-in-item-p)))
  12509. (let* ((struct (org-list-struct))
  12510. (prevs (org-list-prevs-alist struct))
  12511. (regexp
  12512. (concat "[ \t]*- +"
  12513. (replace-regexp-in-string
  12514. " +" " +"
  12515. (org-replace-escapes
  12516. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12517. `(("%d" . ,org-ts-regexp-inactive)
  12518. ("%D" . ,org-ts-regexp)
  12519. ("%s" . "\"\\S-+\"")
  12520. ("%S" . "\"\\S-+\"")
  12521. ("%t" . ,org-ts-regexp-inactive)
  12522. ("%T" . ,org-ts-regexp)
  12523. ("%u" . ".*?")
  12524. ("%U" . ".*?")))))))
  12525. (while (looking-at-p regexp)
  12526. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12527. (org-list-get-item-end (point) struct)))))))
  12528. (defun org-add-log-note (&optional _purpose)
  12529. "Pop up a window for taking a note, and add this note later."
  12530. (remove-hook 'post-command-hook 'org-add-log-note)
  12531. (setq org-log-note-window-configuration (current-window-configuration))
  12532. (delete-other-windows)
  12533. (move-marker org-log-note-return-to (point))
  12534. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12535. (goto-char org-log-note-marker)
  12536. (org-switch-to-buffer-other-window "*Org Note*")
  12537. (erase-buffer)
  12538. (if (memq org-log-note-how '(time state))
  12539. (let (current-prefix-arg) (org-store-log-note))
  12540. (let ((org-inhibit-startup t)) (org-mode))
  12541. (insert (format "# Insert note for %s.
  12542. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12543. (cond
  12544. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12545. ((eq org-log-note-purpose 'done) "closed todo item")
  12546. ((eq org-log-note-purpose 'state)
  12547. (format "state change from \"%s\" to \"%s\""
  12548. (or org-log-note-previous-state "")
  12549. (or org-log-note-state "")))
  12550. ((eq org-log-note-purpose 'reschedule)
  12551. "rescheduling")
  12552. ((eq org-log-note-purpose 'delschedule)
  12553. "no longer scheduled")
  12554. ((eq org-log-note-purpose 'redeadline)
  12555. "changing deadline")
  12556. ((eq org-log-note-purpose 'deldeadline)
  12557. "removing deadline")
  12558. ((eq org-log-note-purpose 'refile)
  12559. "refiling")
  12560. ((eq org-log-note-purpose 'note)
  12561. "this entry")
  12562. (t (error "This should not happen")))))
  12563. (when org-log-note-extra (insert org-log-note-extra))
  12564. (setq-local org-finish-function 'org-store-log-note)
  12565. (run-hooks 'org-log-buffer-setup-hook)))
  12566. (defvar org-note-abort nil) ; dynamically scoped
  12567. (defun org-store-log-note ()
  12568. "Finish taking a log note, and insert it to where it belongs."
  12569. (let ((txt (prog1 (buffer-string)
  12570. (kill-buffer)))
  12571. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12572. lines)
  12573. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12574. (setq txt (replace-match "" t t txt)))
  12575. (when (string-match "\\s-+\\'" txt)
  12576. (setq txt (replace-match "" t t txt)))
  12577. (setq lines (org-split-string txt "\n"))
  12578. (when (org-string-nw-p note)
  12579. (setq note
  12580. (org-replace-escapes
  12581. note
  12582. (list (cons "%u" (user-login-name))
  12583. (cons "%U" user-full-name)
  12584. (cons "%t" (format-time-string
  12585. (org-time-stamp-format 'long 'inactive)
  12586. org-log-note-effective-time))
  12587. (cons "%T" (format-time-string
  12588. (org-time-stamp-format 'long nil)
  12589. org-log-note-effective-time))
  12590. (cons "%d" (format-time-string
  12591. (org-time-stamp-format nil 'inactive)
  12592. org-log-note-effective-time))
  12593. (cons "%D" (format-time-string
  12594. (org-time-stamp-format nil nil)
  12595. org-log-note-effective-time))
  12596. (cons "%s" (cond
  12597. ((not org-log-note-state) "")
  12598. ((org-string-match-p org-ts-regexp
  12599. org-log-note-state)
  12600. (format "\"[%s]\""
  12601. (substring org-log-note-state 1 -1)))
  12602. (t (format "\"%s\"" org-log-note-state))))
  12603. (cons "%S"
  12604. (cond
  12605. ((not org-log-note-previous-state) "")
  12606. ((org-string-match-p org-ts-regexp
  12607. org-log-note-previous-state)
  12608. (format "\"[%s]\""
  12609. (substring
  12610. org-log-note-previous-state 1 -1)))
  12611. (t (format "\"%s\""
  12612. org-log-note-previous-state)))))))
  12613. (when lines (setq note (concat note " \\\\")))
  12614. (push note lines))
  12615. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12616. (with-current-buffer (marker-buffer org-log-note-marker)
  12617. (org-with-wide-buffer
  12618. ;; Find location for the new note.
  12619. (goto-char org-log-note-marker)
  12620. (set-marker org-log-note-marker nil)
  12621. (goto-char (org-log-beginning t))
  12622. ;; Make sure point is at the beginning of an empty line.
  12623. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12624. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12625. ;; In an existing list, add a new item at the top level.
  12626. ;; Otherwise, indent line like a regular one.
  12627. (let ((itemp (org-in-item-p)))
  12628. (if itemp
  12629. (indent-line-to
  12630. (let ((struct (save-excursion
  12631. (goto-char itemp) (org-list-struct))))
  12632. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12633. (org-indent-line)))
  12634. (insert (org-list-bullet-string "-") (pop lines))
  12635. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12636. (dolist (line lines)
  12637. (insert "\n")
  12638. (indent-line-to ind)
  12639. (insert line)))
  12640. (message "Note stored")
  12641. (org-back-to-heading t)
  12642. (org-cycle-hide-drawers 'children))
  12643. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12644. ;; from within `org-add-log-note' because `buffer-undo-list'
  12645. ;; is then modified outside of `org-with-remote-undo'.
  12646. (when (eq this-command 'org-agenda-todo)
  12647. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12648. ;; Don't add undo information when called from `org-agenda-todo'.
  12649. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12650. (set-window-configuration org-log-note-window-configuration)
  12651. (with-current-buffer (marker-buffer org-log-note-return-to)
  12652. (goto-char org-log-note-return-to))
  12653. (move-marker org-log-note-return-to nil)
  12654. (when org-log-post-message (message "%s" org-log-post-message))))
  12655. (defun org-remove-empty-drawer-at (pos)
  12656. "Remove an empty drawer at position POS.
  12657. POS may also be a marker."
  12658. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12659. (org-with-wide-buffer
  12660. (goto-char pos)
  12661. (let ((drawer (org-element-at-point)))
  12662. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12663. (not (org-element-property :contents-begin drawer)))
  12664. (delete-region (org-element-property :begin drawer)
  12665. (progn (goto-char (org-element-property :end drawer))
  12666. (skip-chars-backward " \r\t\n")
  12667. (forward-line)
  12668. (point))))))))
  12669. (defvar org-ts-type nil)
  12670. (defun org-sparse-tree (&optional arg type)
  12671. "Create a sparse tree, prompt for the details.
  12672. This command can create sparse trees. You first need to select the type
  12673. of match used to create the tree:
  12674. t Show all TODO entries.
  12675. T Show entries with a specific TODO keyword.
  12676. m Show entries selected by a tags/property match.
  12677. p Enter a property name and its value (both with completion on existing
  12678. names/values) and show entries with that property.
  12679. r Show entries matching a regular expression (`/' can be used as well).
  12680. b Show deadlines and scheduled items before a date.
  12681. a Show deadlines and scheduled items after a date.
  12682. d Show deadlines due within `org-deadline-warning-days'.
  12683. D Show deadlines and scheduled items between a date range."
  12684. (interactive "P")
  12685. (setq type (or type org-sparse-tree-default-date-type))
  12686. (setq org-ts-type type)
  12687. (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12688. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12689. \[c]ycle through date types: %s"
  12690. (cl-case type
  12691. (all "all timestamps")
  12692. (scheduled "only scheduled")
  12693. (deadline "only deadline")
  12694. (active "only active timestamps")
  12695. (inactive "only inactive timestamps")
  12696. (closed "with a closed time-stamp")
  12697. (otherwise "scheduled/deadline")))
  12698. (let ((answer (read-char-exclusive)))
  12699. (cl-case answer
  12700. (?c
  12701. (org-sparse-tree
  12702. arg
  12703. (cadr
  12704. (memq type '(nil all scheduled deadline active inactive closed)))))
  12705. (?d (call-interactively 'org-check-deadlines))
  12706. (?b (call-interactively 'org-check-before-date))
  12707. (?a (call-interactively 'org-check-after-date))
  12708. (?D (call-interactively 'org-check-dates-range))
  12709. (?t (call-interactively 'org-show-todo-tree))
  12710. (?T (org-show-todo-tree '(4)))
  12711. (?m (call-interactively 'org-match-sparse-tree))
  12712. ((?p ?P)
  12713. (let* ((kwd (completing-read
  12714. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12715. (value (completing-read
  12716. "Value: " (mapcar #'list (org-property-values kwd)))))
  12717. (unless (string-match "\\`{.*}\\'" value)
  12718. (setq value (concat "\"" value "\"")))
  12719. (org-match-sparse-tree arg (concat kwd "=" value))))
  12720. ((?r ?R ?/) (call-interactively 'org-occur))
  12721. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12722. (defvar-local org-occur-highlights nil
  12723. "List of overlays used for occur matches.")
  12724. (defvar-local org-occur-parameters nil
  12725. "Parameters of the active org-occur calls.
  12726. This is a list, each call to org-occur pushes as cons cell,
  12727. containing the regular expression and the callback, onto the list.
  12728. The list can contain several entries if `org-occur' has been called
  12729. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12730. will only contain one set of parameters. When the highlights are
  12731. removed (for example with `C-c C-c', or with the next edit (depending
  12732. on `org-remove-highlights-with-change'), this variable is emptied
  12733. as well.")
  12734. (defun org-occur (regexp &optional keep-previous callback)
  12735. "Make a compact tree which shows all matches of REGEXP.
  12736. The tree will show the lines where the regexp matches, and any other context
  12737. defined in `org-show-context-detail', which see.
  12738. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12739. done by a previous call to `org-occur' will be kept, to allow stacking of
  12740. calls to this command.
  12741. Optional argument CALLBACK can be a function of no argument. In this case,
  12742. it is called with point at the end of the match, match data being set
  12743. accordingly. Current match is shown only if the return value is non-nil.
  12744. The function must neither move point nor alter narrowing."
  12745. (interactive "sRegexp: \nP")
  12746. (when (equal regexp "")
  12747. (user-error "Regexp cannot be empty"))
  12748. (unless keep-previous
  12749. (org-remove-occur-highlights nil nil t))
  12750. (push (cons regexp callback) org-occur-parameters)
  12751. (let ((cnt 0))
  12752. (save-excursion
  12753. (goto-char (point-min))
  12754. (when (or (not keep-previous) ; do not want to keep
  12755. (not org-occur-highlights)) ; no previous matches
  12756. ;; hide everything
  12757. (org-overview))
  12758. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12759. (isearch-no-upper-case-p regexp t)
  12760. org-occur-case-fold-search)))
  12761. (while (re-search-forward regexp nil t)
  12762. (when (or (not callback)
  12763. (save-match-data (funcall callback)))
  12764. (setq cnt (1+ cnt))
  12765. (when org-highlight-sparse-tree-matches
  12766. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12767. (org-show-context 'occur-tree)))))
  12768. (when org-remove-highlights-with-change
  12769. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12770. nil 'local))
  12771. (unless org-sparse-tree-open-archived-trees
  12772. (org-hide-archived-subtrees (point-min) (point-max)))
  12773. (run-hooks 'org-occur-hook)
  12774. (when (called-interactively-p 'interactive)
  12775. (message "%d match(es) for regexp %s" cnt regexp))
  12776. cnt))
  12777. (defun org-occur-next-match (&optional n _reset)
  12778. "Function for `next-error-function' to find sparse tree matches.
  12779. N is the number of matches to move, when negative move backwards.
  12780. This function always goes back to the starting point when no
  12781. match is found."
  12782. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12783. (search-func (if (< n 0)
  12784. 'previous-single-char-property-change
  12785. 'next-single-char-property-change))
  12786. (n (abs n))
  12787. (pos (point))
  12788. p1)
  12789. (catch 'exit
  12790. (while (setq p1 (funcall search-func (point) 'org-type))
  12791. (when (equal p1 limit)
  12792. (goto-char pos)
  12793. (user-error "No more matches"))
  12794. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12795. (setq n (1- n))
  12796. (when (= n 0)
  12797. (goto-char p1)
  12798. (throw 'exit (point))))
  12799. (goto-char p1))
  12800. (goto-char p1)
  12801. (user-error "No more matches"))))
  12802. (defun org-show-context (&optional key)
  12803. "Make sure point and context are visible.
  12804. Optional argument KEY, when non-nil, is a symbol. See
  12805. `org-show-context-detail' for allowed values and how much is to
  12806. be shown."
  12807. (org-show-set-visibility
  12808. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12809. ((cdr (assq key org-show-context-detail)))
  12810. (t (cdr (assq 'default org-show-context-detail))))))
  12811. (defun org-show-set-visibility (detail)
  12812. "Set visibility around point according to DETAIL.
  12813. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12814. `tree', `canonical' or t. See `org-show-context-detail' for more
  12815. information."
  12816. ;; Show current heading and possibly its entry, following headline
  12817. ;; or all children.
  12818. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12819. (org-flag-heading nil)
  12820. (org-show-entry)
  12821. ;; If point is hidden within a drawer or a block, make sure to
  12822. ;; expose it.
  12823. (dolist (o (overlays-at (point)))
  12824. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12825. (delete-overlay o)))
  12826. (unless (org-before-first-heading-p)
  12827. (org-with-limited-levels
  12828. (cl-case detail
  12829. ((tree canonical t) (org-show-children))
  12830. ((nil minimal ancestors))
  12831. (t (save-excursion
  12832. (outline-next-heading)
  12833. (org-flag-heading nil)))))))
  12834. ;; Show all siblings.
  12835. (when (eq detail 'lineage) (org-show-siblings))
  12836. ;; Show ancestors, possibly with their children.
  12837. (when (memq detail '(ancestors lineage tree canonical t))
  12838. (save-excursion
  12839. (while (org-up-heading-safe)
  12840. (org-flag-heading nil)
  12841. (when (memq detail '(canonical t)) (org-show-entry))
  12842. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12843. (defvar org-reveal-start-hook nil
  12844. "Hook run before revealing a location.")
  12845. (defun org-reveal (&optional siblings)
  12846. "Show current entry, hierarchy above it, and the following headline.
  12847. This can be used to show a consistent set of context around
  12848. locations exposed with `org-show-context'.
  12849. With optional argument SIBLINGS, on each level of the hierarchy all
  12850. siblings are shown. This repairs the tree structure to what it would
  12851. look like when opened with hierarchical calls to `org-cycle'.
  12852. With double optional argument \\[universal-argument] \\[universal-argument], \
  12853. go to the parent and show the
  12854. entire tree."
  12855. (interactive "P")
  12856. (run-hooks 'org-reveal-start-hook)
  12857. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12858. ((equal siblings '(16))
  12859. (save-excursion
  12860. (when (org-up-heading-safe)
  12861. (org-show-subtree)
  12862. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12863. (t (org-show-set-visibility 'lineage))))
  12864. (defun org-highlight-new-match (beg end)
  12865. "Highlight from BEG to END and mark the highlight is an occur headline."
  12866. (let ((ov (make-overlay beg end)))
  12867. (overlay-put ov 'face 'secondary-selection)
  12868. (overlay-put ov 'org-type 'org-occur)
  12869. (push ov org-occur-highlights)))
  12870. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12871. "Remove the occur highlights from the buffer.
  12872. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12873. from the `before-change-functions' in the current buffer."
  12874. (interactive)
  12875. (unless org-inhibit-highlight-removal
  12876. (mapc #'delete-overlay org-occur-highlights)
  12877. (setq org-occur-highlights nil)
  12878. (setq org-occur-parameters nil)
  12879. (unless noremove
  12880. (remove-hook 'before-change-functions
  12881. 'org-remove-occur-highlights 'local))))
  12882. ;;;; Priorities
  12883. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12884. "Regular expression matching the priority indicator.")
  12885. (defvar org-remove-priority-next-time nil)
  12886. (defun org-priority-up ()
  12887. "Increase the priority of the current item."
  12888. (interactive)
  12889. (org-priority 'up))
  12890. (defun org-priority-down ()
  12891. "Decrease the priority of the current item."
  12892. (interactive)
  12893. (org-priority 'down))
  12894. (defun org-priority (&optional action _show)
  12895. "Change the priority of an item.
  12896. ACTION can be `set', `up', `down', or a character."
  12897. (interactive "P")
  12898. (if (equal action '(4))
  12899. (org-show-priority)
  12900. (unless org-enable-priority-commands
  12901. (user-error "Priority commands are disabled"))
  12902. (setq action (or action 'set))
  12903. (let (current new news have remove)
  12904. (save-excursion
  12905. (org-back-to-heading t)
  12906. (when (looking-at org-priority-regexp)
  12907. (setq current (string-to-char (match-string 2))
  12908. have t))
  12909. (cond
  12910. ((eq action 'remove)
  12911. (setq remove t new ?\ ))
  12912. ((or (eq action 'set)
  12913. (integerp action))
  12914. (if (not (eq action 'set))
  12915. (setq new action)
  12916. (message "Priority %c-%c, SPC to remove: "
  12917. org-highest-priority org-lowest-priority)
  12918. (save-match-data
  12919. (setq new (read-char-exclusive))))
  12920. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12921. (= (upcase org-lowest-priority) org-lowest-priority))
  12922. (setq new (upcase new)))
  12923. (cond ((equal new ?\ ) (setq remove t))
  12924. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12925. (user-error "Priority must be between `%c' and `%c'"
  12926. org-highest-priority org-lowest-priority))))
  12927. ((eq action 'up)
  12928. (setq new (if have
  12929. (1- current) ; normal cycling
  12930. ;; last priority was empty
  12931. (if (eq last-command this-command)
  12932. org-lowest-priority ; wrap around empty to lowest
  12933. ;; default
  12934. (if org-priority-start-cycle-with-default
  12935. org-default-priority
  12936. (1- org-default-priority))))))
  12937. ((eq action 'down)
  12938. (setq new (if have
  12939. (1+ current) ; normal cycling
  12940. ;; last priority was empty
  12941. (if (eq last-command this-command)
  12942. org-highest-priority ; wrap around empty to highest
  12943. ;; default
  12944. (if org-priority-start-cycle-with-default
  12945. org-default-priority
  12946. (1+ org-default-priority))))))
  12947. (t (user-error "Invalid action")))
  12948. (when (or (< (upcase new) org-highest-priority)
  12949. (> (upcase new) org-lowest-priority))
  12950. (if (and (memq action '(up down))
  12951. (not have) (not (eq last-command this-command)))
  12952. ;; `new' is from default priority
  12953. (error
  12954. "The default can not be set, see `org-default-priority' why")
  12955. ;; normal cycling: `new' is beyond highest/lowest priority
  12956. ;; and is wrapped around to the empty priority
  12957. (setq remove t)))
  12958. (setq news (format "%c" new))
  12959. (if have
  12960. (if remove
  12961. (replace-match "" t t nil 1)
  12962. (replace-match news t t nil 2))
  12963. (if remove
  12964. (user-error "No priority cookie found in line")
  12965. (let ((case-fold-search nil))
  12966. (looking-at org-todo-line-regexp))
  12967. (if (match-end 2)
  12968. (progn
  12969. (goto-char (match-end 2))
  12970. (insert " [#" news "]"))
  12971. (goto-char (match-beginning 3))
  12972. (insert "[#" news "] "))))
  12973. (org-set-tags nil 'align))
  12974. (if remove
  12975. (message "Priority removed")
  12976. (message "Priority of current item set to %s" news)))))
  12977. (defun org-show-priority ()
  12978. "Show the priority of the current item.
  12979. This priority is composed of the main priority given with the [#A] cookies,
  12980. and by additional input from the age of a schedules or deadline entry."
  12981. (interactive)
  12982. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12983. (org-get-at-bol 'priority)
  12984. (save-excursion
  12985. (save-match-data
  12986. (beginning-of-line)
  12987. (and (looking-at org-heading-regexp)
  12988. (org-get-priority (match-string 0))))))))
  12989. (message "Priority is %d" (if pri pri -1000))))
  12990. (defun org-get-priority (s)
  12991. "Find priority cookie and return priority."
  12992. (save-match-data
  12993. (if (functionp org-get-priority-function)
  12994. (funcall org-get-priority-function)
  12995. (if (not (string-match org-priority-regexp s))
  12996. (* 1000 (- org-lowest-priority org-default-priority))
  12997. (* 1000 (- org-lowest-priority
  12998. (string-to-char (match-string 2 s))))))))
  12999. ;;;; Tags
  13000. (defvar org-agenda-archives-mode)
  13001. (defvar org-map-continue-from nil
  13002. "Position from where mapping should continue.
  13003. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  13004. (defvar org-scanner-tags nil
  13005. "The current tag list while the tags scanner is running.")
  13006. (defvar org-trust-scanner-tags nil
  13007. "Should `org-get-tags-at' use the tags for the scanner.
  13008. This is for internal dynamical scoping only.
  13009. When this is non-nil, the function `org-get-tags-at' will return the value
  13010. of `org-scanner-tags' instead of building the list by itself. This
  13011. can lead to large speed-ups when the tags scanner is used in a file with
  13012. many entries, and when the list of tags is retrieved, for example to
  13013. obtain a list of properties. Building the tags list for each entry in such
  13014. a file becomes an N^2 operation - but with this variable set, it scales
  13015. as N.")
  13016. (defvar org--matcher-tags-todo-only nil)
  13017. (defun org-scan-tags (action matcher todo-only &optional start-level)
  13018. "Scan headline tags with inheritance and produce output ACTION.
  13019. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  13020. or `agenda' to produce an entry list for an agenda view. It can also be
  13021. a Lisp form or a function that should be called at each matched headline, in
  13022. this case the return value is a list of all return values from these calls.
  13023. MATCHER is a function accepting three arguments, returning
  13024. a non-nil value whenever a given set of tags qualifies a headline
  13025. for inclusion. See `org-make-tags-matcher' for more information.
  13026. As a special case, it can also be set to t (respectively nil) in
  13027. order to match all (respectively none) headline.
  13028. When TODO-ONLY is non-nil, only lines with a not-done TODO
  13029. keyword are included in the output.
  13030. START-LEVEL can be a string with asterisks, reducing the scope to
  13031. headlines matching this string."
  13032. (require 'org-agenda)
  13033. (let* ((re (concat "^"
  13034. (if start-level
  13035. ;; Get the correct level to match
  13036. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  13037. org-outline-regexp)
  13038. " *\\(\\<\\("
  13039. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  13040. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  13041. (props (list 'face 'default
  13042. 'done-face 'org-agenda-done
  13043. 'undone-face 'default
  13044. 'mouse-face 'highlight
  13045. 'org-not-done-regexp org-not-done-regexp
  13046. 'org-todo-regexp org-todo-regexp
  13047. 'org-complex-heading-regexp org-complex-heading-regexp
  13048. 'help-echo
  13049. (format "mouse-2 or RET jump to org file %s"
  13050. (abbreviate-file-name
  13051. (or (buffer-file-name (buffer-base-buffer))
  13052. (buffer-name (buffer-base-buffer)))))))
  13053. (org-map-continue-from nil)
  13054. lspos tags tags-list
  13055. (tags-alist (list (cons 0 org-file-tags)))
  13056. (llast 0) rtn rtn1 level category i txt
  13057. todo marker entry priority
  13058. ts-date ts-date-type ts-date-pair)
  13059. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  13060. (setq action (list 'lambda nil action)))
  13061. (save-excursion
  13062. (goto-char (point-min))
  13063. (when (eq action 'sparse-tree)
  13064. (org-overview)
  13065. (org-remove-occur-highlights))
  13066. (while (let (case-fold-search)
  13067. (re-search-forward re nil t))
  13068. (setq org-map-continue-from nil)
  13069. (catch :skip
  13070. (setq todo
  13071. ;; TODO: is the 1-2 difference a bug?
  13072. (when (match-end 1) (match-string-no-properties 2))
  13073. tags (when (match-end 4) (match-string-no-properties 4)))
  13074. (goto-char (setq lspos (match-beginning 0)))
  13075. (setq level (org-reduced-level (org-outline-level))
  13076. category (org-get-category))
  13077. (when (eq action 'agenda)
  13078. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13079. ts-date (car ts-date-pair)
  13080. ts-date-type (cdr ts-date-pair)))
  13081. (setq i llast llast level)
  13082. ;; remove tag lists from same and sublevels
  13083. (while (>= i level)
  13084. (when (setq entry (assoc i tags-alist))
  13085. (setq tags-alist (delete entry tags-alist)))
  13086. (setq i (1- i)))
  13087. ;; add the next tags
  13088. (when tags
  13089. (setq tags (org-split-string tags ":")
  13090. tags-alist
  13091. (cons (cons level tags) tags-alist)))
  13092. ;; compile tags for current headline
  13093. (setq tags-list
  13094. (if org-use-tag-inheritance
  13095. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13096. tags)
  13097. org-scanner-tags tags-list)
  13098. (when org-use-tag-inheritance
  13099. (setcdr (car tags-alist)
  13100. (mapcar (lambda (x)
  13101. (setq x (copy-sequence x))
  13102. (org-add-prop-inherited x))
  13103. (cdar tags-alist))))
  13104. (when (and tags org-use-tag-inheritance
  13105. (or (not (eq t org-use-tag-inheritance))
  13106. org-tags-exclude-from-inheritance))
  13107. ;; Selective inheritance, remove uninherited ones.
  13108. (setcdr (car tags-alist)
  13109. (org-remove-uninherited-tags (cdar tags-alist))))
  13110. (when (and
  13111. ;; eval matcher only when the todo condition is OK
  13112. (and (or (not todo-only) (member todo org-not-done-keywords))
  13113. (if (functionp matcher)
  13114. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13115. (funcall matcher todo tags-list level))
  13116. matcher))
  13117. ;; Call the skipper, but return t if it does not
  13118. ;; skip, so that the `and' form continues evaluating.
  13119. (progn
  13120. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13121. t)
  13122. ;; Check if timestamps are deselecting this entry
  13123. (or (not todo-only)
  13124. (and (member todo org-not-done-keywords)
  13125. (or (not org-agenda-tags-todo-honor-ignore-options)
  13126. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13127. ;; select this headline
  13128. (cond
  13129. ((eq action 'sparse-tree)
  13130. (and org-highlight-sparse-tree-matches
  13131. (org-get-heading) (match-end 0)
  13132. (org-highlight-new-match
  13133. (match-beginning 1) (match-end 1)))
  13134. (org-show-context 'tags-tree))
  13135. ((eq action 'agenda)
  13136. (setq txt (org-agenda-format-item
  13137. ""
  13138. (concat
  13139. (if (eq org-tags-match-list-sublevels 'indented)
  13140. (make-string (1- level) ?.) "")
  13141. (org-get-heading))
  13142. (make-string level ?\s)
  13143. category
  13144. tags-list)
  13145. priority (org-get-priority txt))
  13146. (goto-char lspos)
  13147. (setq marker (org-agenda-new-marker))
  13148. (org-add-props txt props
  13149. 'org-marker marker 'org-hd-marker marker 'org-category category
  13150. 'todo-state todo
  13151. 'ts-date ts-date
  13152. 'priority priority
  13153. 'type (concat "tagsmatch" ts-date-type))
  13154. (push txt rtn))
  13155. ((functionp action)
  13156. (setq org-map-continue-from nil)
  13157. (save-excursion
  13158. (setq rtn1 (funcall action))
  13159. (push rtn1 rtn)))
  13160. (t (user-error "Invalid action")))
  13161. ;; if we are to skip sublevels, jump to end of subtree
  13162. (unless org-tags-match-list-sublevels
  13163. (org-end-of-subtree t)
  13164. (backward-char 1))))
  13165. ;; Get the correct position from where to continue
  13166. (if org-map-continue-from
  13167. (goto-char org-map-continue-from)
  13168. (and (= (point) lspos) (end-of-line 1)))))
  13169. (when (and (eq action 'sparse-tree)
  13170. (not org-sparse-tree-open-archived-trees))
  13171. (org-hide-archived-subtrees (point-min) (point-max)))
  13172. (nreverse rtn)))
  13173. (defun org-remove-uninherited-tags (tags)
  13174. "Remove all tags that are not inherited from the list TAGS."
  13175. (cond
  13176. ((eq org-use-tag-inheritance t)
  13177. (if org-tags-exclude-from-inheritance
  13178. (org-delete-all org-tags-exclude-from-inheritance tags)
  13179. tags))
  13180. ((not org-use-tag-inheritance) nil)
  13181. ((stringp org-use-tag-inheritance)
  13182. (delq nil (mapcar
  13183. (lambda (x)
  13184. (if (and (string-match org-use-tag-inheritance x)
  13185. (not (member x org-tags-exclude-from-inheritance)))
  13186. x nil))
  13187. tags)))
  13188. ((listp org-use-tag-inheritance)
  13189. (delq nil (mapcar
  13190. (lambda (x)
  13191. (if (member x org-use-tag-inheritance) x nil))
  13192. tags)))))
  13193. (defun org-match-sparse-tree (&optional todo-only match)
  13194. "Create a sparse tree according to tags string MATCH.
  13195. MATCH can contain positive and negative selection of tags, like
  13196. \"+WORK+URGENT-WITHBOSS\".
  13197. If optional argument TODO-ONLY is non-nil, only select lines that are
  13198. also TODO lines."
  13199. (interactive "P")
  13200. (org-agenda-prepare-buffers (list (current-buffer)))
  13201. (let ((org--matcher-tags-todo-only todo-only))
  13202. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13203. org--matcher-tags-todo-only)))
  13204. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13205. (defvar org-cached-props nil)
  13206. (defun org-cached-entry-get (pom property)
  13207. (if (or (eq t org-use-property-inheritance)
  13208. (and (stringp org-use-property-inheritance)
  13209. (let ((case-fold-search t))
  13210. (org-string-match-p org-use-property-inheritance property)))
  13211. (and (listp org-use-property-inheritance)
  13212. (member-ignore-case property org-use-property-inheritance)))
  13213. ;; Caching is not possible, check it directly.
  13214. (org-entry-get pom property 'inherit)
  13215. ;; Get all properties, so we can do complicated checks easily.
  13216. (cdr (assoc-string property
  13217. (or org-cached-props
  13218. (setq org-cached-props (org-entry-properties pom)))
  13219. t))))
  13220. (defun org-global-tags-completion-table (&optional files)
  13221. "Return the list of all tags in all agenda buffer/files.
  13222. Optional FILES argument is a list of files which can be used
  13223. instead of the agenda files."
  13224. (save-excursion
  13225. (org-uniquify
  13226. (delq nil
  13227. (apply #'append
  13228. (mapcar
  13229. (lambda (file)
  13230. (set-buffer (find-file-noselect file))
  13231. (mapcar (lambda (x)
  13232. (and (stringp (car-safe x))
  13233. (list (car-safe x))))
  13234. (or org-current-tag-alist (org-get-buffer-tags))))
  13235. (if (car-safe files) files
  13236. (org-agenda-files))))))))
  13237. (defun org-make-tags-matcher (match)
  13238. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13239. Returns a cons of the selection string MATCH and a function
  13240. implementing the matcher.
  13241. The matcher is to be called at an Org entry, with point on the
  13242. headline, and returns non-nil if the entry matches the selection
  13243. string MATCH. It must be called with three arguments: the TODO
  13244. keyword at the entry (or nil if none), the list of all tags at
  13245. the entry including inherited ones and the reduced level of the
  13246. headline. Additionally, the category of the entry, if any, must
  13247. be specified as the text property `org-category' on the headline.
  13248. This function sets the variable `org--matcher-tags-todo-only' to
  13249. a non-nil value if the matcher restricts matching to TODO
  13250. entries, otherwise it is not touched.
  13251. See also `org-scan-tags'."
  13252. (unless match
  13253. ;; Get a new match request, with completion against the global
  13254. ;; tags table and the local tags in current buffer.
  13255. (let ((org-last-tags-completion-table
  13256. (org-uniquify
  13257. (delq nil (append (org-get-buffer-tags)
  13258. (org-global-tags-completion-table))))))
  13259. (setq match
  13260. (completing-read
  13261. "Match: "
  13262. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13263. (let ((match0 match)
  13264. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13265. (start 0)
  13266. tagsmatch todomatch tagsmatcher todomatcher)
  13267. ;; Expand group tags.
  13268. (setq match (org-tags-expand match))
  13269. ;; Check if there is a TODO part of this match, which would be the
  13270. ;; part after a "/". To make sure that this slash is not part of
  13271. ;; a property value to be matched against, we also check that
  13272. ;; there is no / after that slash. First, find the last slash.
  13273. (let ((s 0))
  13274. (while (string-match "/+" match s)
  13275. (setq start (match-beginning 0))
  13276. (setq s (match-end 0))))
  13277. (if (and (string-match "/+" match start)
  13278. (not (string-match-p "\"" match start)))
  13279. ;; Match contains also a TODO-matching request.
  13280. (progn
  13281. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13282. (setq todomatch (substring match (match-end 0)))
  13283. (when (string-match "\\`!" todomatch)
  13284. (setq org--matcher-tags-todo-only t)
  13285. (setq todomatch (substring todomatch 1)))
  13286. (when (string-match "\\`\\s-*\\'" todomatch)
  13287. (setq todomatch nil)))
  13288. ;; Only matching tags.
  13289. (setq tagsmatch match)
  13290. (setq todomatch nil))
  13291. ;; Make the tags matcher.
  13292. (when (org-string-nw-p tagsmatch)
  13293. (let ((orlist nil)
  13294. (orterms (org-split-string tagsmatch "|"))
  13295. term)
  13296. (while (setq term (pop orterms))
  13297. (while (and (equal (substring term -1) "\\") orterms)
  13298. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13299. (while (string-match re term)
  13300. (let* ((rest (substring term (match-end 0)))
  13301. (minus (and (match-end 1)
  13302. (equal (match-string 1 term) "-")))
  13303. (tag (save-match-data
  13304. (replace-regexp-in-string
  13305. "\\\\-" "-" (match-string 2 term))))
  13306. (regexp (eq (string-to-char tag) ?{))
  13307. (levelp (match-end 4))
  13308. (propp (match-end 5))
  13309. (mm
  13310. (cond
  13311. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13312. (levelp
  13313. `(,(org-op-to-function (match-string 3 term))
  13314. level
  13315. ,(string-to-number (match-string 4 term))))
  13316. (propp
  13317. (let* ((gv (pcase (upcase (match-string 5 term))
  13318. ("CATEGORY"
  13319. '(get-text-property (point) 'org-category))
  13320. ("TODO" 'todo)
  13321. (p `(org-cached-entry-get nil ,p))))
  13322. (pv (match-string 7 term))
  13323. (regexp (eq (string-to-char pv) ?{))
  13324. (strp (eq (string-to-char pv) ?\"))
  13325. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13326. (po (org-op-to-function (match-string 6 term)
  13327. (if timep 'time strp))))
  13328. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13329. (when timep (setq pv (org-matcher-time pv)))
  13330. (cond ((and regexp (eq po 'org<>))
  13331. `(not (string-match ,pv (or ,gv ""))))
  13332. (regexp `(string-match ,pv (or ,gv "")))
  13333. (strp `(,po (or ,gv "") ,pv))
  13334. (t
  13335. `(,po
  13336. (string-to-number (or ,gv ""))
  13337. ,(string-to-number pv))))))
  13338. (t `(member ,tag tags-list)))))
  13339. (push (if minus `(not ,mm) mm) tagsmatcher)
  13340. (setq term rest)))
  13341. (push `(and ,@tagsmatcher) orlist)
  13342. (setq tagsmatcher nil))
  13343. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13344. ;; Make the TODO matcher.
  13345. (when (org-string-nw-p todomatch)
  13346. (let ((orlist nil))
  13347. (dolist (term (org-split-string todomatch "|"))
  13348. (while (string-match re term)
  13349. (let* ((minus (and (match-end 1)
  13350. (equal (match-string 1 term) "-")))
  13351. (kwd (match-string 2 term))
  13352. (regexp (eq (string-to-char kwd) ?{))
  13353. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13354. `(equal todo ,kwd))))
  13355. (push (if minus `(not ,mm) mm) todomatcher))
  13356. (setq term (substring term (match-end 0))))
  13357. (push (if (> (length todomatcher) 1)
  13358. (cons 'and todomatcher)
  13359. (car todomatcher))
  13360. orlist)
  13361. (setq todomatcher nil))
  13362. (setq todomatcher (cons 'or orlist))))
  13363. ;; Return the string and function of the matcher. If no
  13364. ;; tags-specific or todo-specific matcher exists, match
  13365. ;; everything.
  13366. (let ((matcher (if (and tagsmatcher todomatcher)
  13367. `(and ,tagsmatcher ,todomatcher)
  13368. (or tagsmatcher todomatcher t))))
  13369. (when org--matcher-tags-todo-only
  13370. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13371. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13372. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13373. "Expand group tags in MATCH.
  13374. This replaces every group tag in MATCH with a regexp tag search.
  13375. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13376. will be replaced like this:
  13377. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13378. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13379. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13380. Replacing by a regexp preserves the structure of the match.
  13381. E.g., this expansion
  13382. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13383. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13384. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13385. A group tag in MATCH can contain regular expressions of its own.
  13386. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13387. will be replaced like this:
  13388. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13389. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13390. assumed to be a single group tag, and the function will return
  13391. the list of tags in this group.
  13392. When DOWNCASE is non-nil, expand downcased TAGS."
  13393. (if org-group-tags
  13394. (let* ((case-fold-search t)
  13395. (stable org-mode-syntax-table)
  13396. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13397. (taggroups (if downcased
  13398. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13399. taggroups)
  13400. taggroups))
  13401. (taggroups-keys (mapcar #'car taggroups))
  13402. (return-match (if downcased (downcase match) match))
  13403. (count 0)
  13404. (work-already-expanded tags-already-expanded)
  13405. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13406. ;; @ and _ are allowed as word-components in tags.
  13407. (modify-syntax-entry ?@ "w" stable)
  13408. (modify-syntax-entry ?_ "w" stable)
  13409. ;; Temporarily replace regexp-expressions in the match-expression.
  13410. (while (string-match "{.+?}" return-match)
  13411. (cl-incf count)
  13412. (push (match-string 0 return-match) regexps-in-match)
  13413. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13414. (while (and taggroups-keys
  13415. (with-syntax-table stable
  13416. (string-match
  13417. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13418. (regexp-opt taggroups-keys) "\\>\\)")
  13419. return-match)))
  13420. (let* ((dir (match-string 1 return-match))
  13421. (tag (match-string 2 return-match))
  13422. (tag (if downcased (downcase tag) tag)))
  13423. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13424. (member tag work-already-expanded))
  13425. (setq tags-in-group (assoc tag taggroups))
  13426. (push tag work-already-expanded)
  13427. ;; Recursively expand each tag in the group, if the tag hasn't
  13428. ;; already been expanded. Restore the match-data after all recursive calls.
  13429. (save-match-data
  13430. (let (tags-expanded)
  13431. (dolist (x (cdr tags-in-group))
  13432. (if (and (member x taggroups-keys)
  13433. (not (member x work-already-expanded)))
  13434. (setq tags-expanded
  13435. (delete-dups
  13436. (append
  13437. (org-tags-expand x t downcased
  13438. work-already-expanded)
  13439. tags-expanded)))
  13440. (setq tags-expanded
  13441. (append (list x) tags-expanded)))
  13442. (setq work-already-expanded
  13443. (delete-dups
  13444. (append tags-expanded
  13445. work-already-expanded))))
  13446. (setq tags-in-group
  13447. (delete-dups (cons (car tags-in-group)
  13448. tags-expanded)))))
  13449. ;; Filter tag-regexps from tags.
  13450. (setq regexp-in-group-escaped
  13451. (delq nil (mapcar (lambda (x)
  13452. (if (stringp x)
  13453. (and (equal "{" (substring x 0 1))
  13454. (equal "}" (substring x -1))
  13455. x)
  13456. x))
  13457. tags-in-group))
  13458. regexp-in-group
  13459. (mapcar (lambda (x)
  13460. (substring x 1 -1))
  13461. regexp-in-group-escaped)
  13462. tags-in-group
  13463. (delq nil (mapcar (lambda (x)
  13464. (if (stringp x)
  13465. (and (not (equal "{" (substring x 0 1)))
  13466. (not (equal "}" (substring x -1)))
  13467. x)
  13468. x))
  13469. tags-in-group)))
  13470. ;; If single-as-list, do no more in the while-loop.
  13471. (if (not single-as-list)
  13472. (progn
  13473. (when regexp-in-group
  13474. (setq regexp-in-group
  13475. (concat "\\|"
  13476. (mapconcat 'identity regexp-in-group
  13477. "\\|"))))
  13478. (setq tags-in-group
  13479. (concat dir
  13480. "{\\<"
  13481. (regexp-opt tags-in-group)
  13482. "\\>"
  13483. regexp-in-group
  13484. "}"))
  13485. (when (stringp tags-in-group)
  13486. (org-add-props tags-in-group '(grouptag t)))
  13487. (setq return-match
  13488. (replace-match tags-in-group t t return-match)))
  13489. (setq tags-in-group
  13490. (append regexp-in-group-escaped tags-in-group))))
  13491. (setq taggroups-keys (delete tag taggroups-keys))))
  13492. ;; Add the regular expressions back into the match-expression again.
  13493. (while regexps-in-match
  13494. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13495. (pop regexps-in-match)
  13496. return-match t t))
  13497. (cl-decf count))
  13498. (if single-as-list
  13499. (if tags-in-group tags-in-group (list return-match))
  13500. return-match))
  13501. (if single-as-list
  13502. (list (if downcased (downcase match) match))
  13503. match)))
  13504. (defun org-op-to-function (op &optional stringp)
  13505. "Turn an operator into the appropriate function."
  13506. (setq op
  13507. (cond
  13508. ((equal op "<" ) '(< string< org-time<))
  13509. ((equal op ">" ) '(> org-string> org-time>))
  13510. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13511. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13512. ((member op '("=" "==")) '(= string= org-time=))
  13513. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13514. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13515. (defun org<> (a b) (not (= a b)))
  13516. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13517. (defun org-string>= (a b) (not (string< a b)))
  13518. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13519. (defun org-string<> (a b) (not (string= a b)))
  13520. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13521. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13522. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13523. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13524. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13525. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13526. (defun org-2ft (s)
  13527. "Convert S to a floating point time.
  13528. If S is already a number, just return it. If it is a string, parse
  13529. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13530. (cond
  13531. ((numberp s) s)
  13532. ((stringp s)
  13533. (condition-case nil
  13534. (float-time (apply 'encode-time (org-parse-time-string s)))
  13535. (error 0.)))
  13536. (t 0.)))
  13537. (defun org-time-today ()
  13538. "Time in seconds today at 0:00.
  13539. Returns the float number of seconds since the beginning of the
  13540. epoch to the beginning of today (00:00)."
  13541. (float-time (apply 'encode-time
  13542. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13543. (defun org-matcher-time (s)
  13544. "Interpret a time comparison value."
  13545. (save-match-data
  13546. (cond
  13547. ((string= s "<now>") (float-time))
  13548. ((string= s "<today>") (org-time-today))
  13549. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13550. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13551. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13552. (+ (org-time-today)
  13553. (* (string-to-number (match-string 1 s))
  13554. (cdr (assoc (match-string 2 s)
  13555. '(("d" . 86400.0) ("w" . 604800.0)
  13556. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13557. (t (org-2ft s)))))
  13558. (defun org-match-any-p (re list)
  13559. "Does re match any element of list?"
  13560. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13561. (delq nil list))
  13562. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13563. (defvar org-tags-overlay (make-overlay 1 1))
  13564. (delete-overlay org-tags-overlay)
  13565. (defun org-get-local-tags-at (&optional pos)
  13566. "Get a list of tags defined in the current headline."
  13567. (org-get-tags-at pos 'local))
  13568. (defun org-get-local-tags ()
  13569. "Get a list of tags defined in the current headline."
  13570. (org-get-tags-at nil 'local))
  13571. (defun org-get-tags-at (&optional pos local)
  13572. "Get a list of all headline tags applicable at POS.
  13573. POS defaults to point. If tags are inherited, the list contains
  13574. the targets in the same sequence as the headlines appear, i.e.
  13575. the tags of the current headline come last.
  13576. When LOCAL is non-nil, only return tags from the current headline,
  13577. ignore inherited ones."
  13578. (interactive)
  13579. (if (and org-trust-scanner-tags
  13580. (or (not pos) (equal pos (point)))
  13581. (not local))
  13582. org-scanner-tags
  13583. (let (tags ltags lastpos parent)
  13584. (save-excursion
  13585. (save-restriction
  13586. (widen)
  13587. (goto-char (or pos (point)))
  13588. (save-match-data
  13589. (catch 'done
  13590. (condition-case nil
  13591. (progn
  13592. (org-back-to-heading t)
  13593. (while (not (equal lastpos (point)))
  13594. (setq lastpos (point))
  13595. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13596. (setq ltags (org-split-string
  13597. (match-string-no-properties 1) ":"))
  13598. (when parent
  13599. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13600. (setq tags (append
  13601. (if parent
  13602. (org-remove-uninherited-tags ltags)
  13603. ltags)
  13604. tags)))
  13605. (or org-use-tag-inheritance (throw 'done t))
  13606. (when local (throw 'done t))
  13607. (or (org-up-heading-safe) (error nil))
  13608. (setq parent t)))
  13609. (error nil)))))
  13610. (if local
  13611. tags
  13612. (reverse (delete-dups
  13613. (reverse (append
  13614. (org-remove-uninherited-tags
  13615. org-file-tags)
  13616. tags)))))))))
  13617. (defun org-add-prop-inherited (s)
  13618. (add-text-properties 0 (length s) '(inherited t) s)
  13619. s)
  13620. (defun org-toggle-tag (tag &optional onoff)
  13621. "Toggle the tag TAG for the current line.
  13622. If ONOFF is `on' or `off', don't toggle but set to this state."
  13623. (let (res current)
  13624. (save-excursion
  13625. (org-back-to-heading t)
  13626. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13627. (point-at-eol) t)
  13628. (progn
  13629. (setq current (match-string 1))
  13630. (replace-match ""))
  13631. (setq current ""))
  13632. (setq current (nreverse (org-split-string current ":")))
  13633. (cond
  13634. ((eq onoff 'on)
  13635. (setq res t)
  13636. (or (member tag current) (push tag current)))
  13637. ((eq onoff 'off)
  13638. (or (not (member tag current)) (setq current (delete tag current))))
  13639. (t (if (member tag current)
  13640. (setq current (delete tag current))
  13641. (setq res t)
  13642. (push tag current))))
  13643. (end-of-line 1)
  13644. (if current
  13645. (progn
  13646. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13647. (org-set-tags nil t))
  13648. (delete-horizontal-space))
  13649. (run-hooks 'org-after-tags-change-hook))
  13650. res))
  13651. (defun org-align-tags-here (to-col)
  13652. ;; Assumes that this is a headline
  13653. "Align tags on the current headline to TO-COL."
  13654. (let ((pos (point)) (col (current-column)) ncol tags-l p)
  13655. (beginning-of-line 1)
  13656. (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13657. (< pos (match-beginning 2)))
  13658. (progn
  13659. (setq tags-l (string-width (match-string 2)))
  13660. (goto-char (match-beginning 1))
  13661. (insert " ")
  13662. (delete-region (point) (1+ (match-beginning 2)))
  13663. (setq ncol (max (current-column)
  13664. (1+ col)
  13665. (if (> to-col 0)
  13666. to-col
  13667. (- (abs to-col) tags-l))))
  13668. (setq p (point))
  13669. (insert (make-string (- ncol (current-column)) ?\ ))
  13670. (setq ncol (current-column))
  13671. (when indent-tabs-mode (tabify p (point-at-eol)))
  13672. (org-move-to-column (min ncol col)))
  13673. (goto-char pos))))
  13674. (defun org-set-tags-command (&optional arg just-align)
  13675. "Call the set-tags command for the current entry."
  13676. (interactive "P")
  13677. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13678. (org-set-tags arg just-align)
  13679. (save-excursion
  13680. (unless (and (org-region-active-p)
  13681. org-loop-over-headlines-in-active-region)
  13682. (org-back-to-heading t))
  13683. (org-set-tags arg just-align))))
  13684. (defun org-set-tags-to (data)
  13685. "Set the tags of the current entry to DATA, replacing the current tags.
  13686. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13687. If DATA is nil or the empty string, any tags will be removed."
  13688. (interactive "sTags: ")
  13689. (setq data
  13690. (cond
  13691. ((eq data nil) "")
  13692. ((equal data "") "")
  13693. ((stringp data)
  13694. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13695. ":"))
  13696. ((listp data)
  13697. (concat ":" (mapconcat 'identity data ":") ":"))))
  13698. (when data
  13699. (save-excursion
  13700. (org-back-to-heading t)
  13701. (when (looking-at org-complex-heading-regexp)
  13702. (if (match-end 5)
  13703. (progn
  13704. (goto-char (match-beginning 5))
  13705. (insert data)
  13706. (delete-region (point) (point-at-eol))
  13707. (org-set-tags nil 'align))
  13708. (goto-char (point-at-eol))
  13709. (insert " " data)
  13710. (org-set-tags nil 'align)))
  13711. (beginning-of-line 1)
  13712. (when (looking-at ".*?\\([ \t]+\\)$")
  13713. (delete-region (match-beginning 1) (match-end 1))))))
  13714. (defun org-align-all-tags ()
  13715. "Align the tags in all headings."
  13716. (interactive)
  13717. (save-excursion
  13718. (or (ignore-errors (org-back-to-heading t))
  13719. (outline-next-heading))
  13720. (if (org-at-heading-p)
  13721. (org-set-tags t)
  13722. (message "No headings"))))
  13723. (defvar org-indent-indentation-per-level)
  13724. (defun org-set-tags (&optional arg just-align)
  13725. "Set the tags for the current headline.
  13726. With prefix ARG, realign all tags in headings in the current buffer.
  13727. When JUST-ALIGN is non-nil, only align tags."
  13728. (interactive "P")
  13729. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13730. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13731. 'region-start-level
  13732. 'region))
  13733. org-loop-over-headlines-in-active-region)
  13734. (org-map-entries
  13735. ;; We don't use ARG and JUST-ALIGN here because these args
  13736. ;; are not useful when looping over headlines.
  13737. #'org-set-tags
  13738. org-loop-over-headlines-in-active-region
  13739. cl
  13740. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13741. (let ((org-setting-tags t))
  13742. (if arg
  13743. (save-excursion
  13744. (goto-char (point-min))
  13745. (while (re-search-forward org-outline-regexp-bol nil t)
  13746. (org-set-tags nil t)
  13747. (end-of-line))
  13748. (message "All tags realigned to column %d" org-tags-column))
  13749. (let* ((current (org-get-tags-string))
  13750. (col (current-column))
  13751. (tags
  13752. (if just-align current
  13753. ;; Get a new set of tags from the user.
  13754. (save-excursion
  13755. (let* ((seen)
  13756. (table
  13757. (setq
  13758. org-last-tags-completion-table
  13759. ;; Uniquify tags in alists, yet preserve
  13760. ;; structure (i.e., keywords).
  13761. (delq nil
  13762. (mapcar
  13763. (lambda (pair)
  13764. (let ((head (car pair)))
  13765. (cond ((symbolp head) pair)
  13766. ((member head seen) nil)
  13767. (t (push head seen)
  13768. pair))))
  13769. (append
  13770. (or org-current-tag-alist
  13771. (org-get-buffer-tags))
  13772. (and
  13773. org-complete-tags-always-offer-all-agenda-tags
  13774. (org-global-tags-completion-table
  13775. (org-agenda-files))))))))
  13776. (current-tags (org-split-string current ":"))
  13777. (inherited-tags
  13778. (nreverse (nthcdr (length current-tags)
  13779. (nreverse (org-get-tags-at))))))
  13780. (replace-regexp-in-string
  13781. "\\([-+&]+\\|,\\)"
  13782. ":"
  13783. (if (or (eq t org-use-fast-tag-selection)
  13784. (and org-use-fast-tag-selection
  13785. (delq nil (mapcar #'cdr table))))
  13786. (org-fast-tag-selection
  13787. current-tags inherited-tags table
  13788. (and org-fast-tag-selection-include-todo
  13789. org-todo-key-alist))
  13790. (let ((org-add-colon-after-tag-completion
  13791. (< 1 (length table))))
  13792. (org-trim
  13793. (completing-read
  13794. "Tags: "
  13795. #'org-tags-completion-function
  13796. nil nil current 'org-tags-history))))))))))
  13797. (when org-tags-sort-function
  13798. (setq tags
  13799. (mapconcat
  13800. #'identity
  13801. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13802. org-tags-sort-function)
  13803. ":")))
  13804. (if (not (org-string-nw-p tags)) (setq tags "")
  13805. (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
  13806. (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
  13807. ;; Insert new tags at the correct column
  13808. (beginning-of-line)
  13809. (let ((level (if (looking-at org-outline-regexp)
  13810. (- (match-end 0) (point) 1)
  13811. 1)))
  13812. (cond
  13813. ((and (equal current "") (equal tags "")))
  13814. ((re-search-forward
  13815. (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
  13816. (line-end-position)
  13817. t)
  13818. (if (equal tags "") (replace-match "" t t)
  13819. (goto-char (match-beginning 0))
  13820. (let* ((c0 (current-column))
  13821. ;; Compute offset for the case of org-indent-mode
  13822. ;; active.
  13823. (di (if (bound-and-true-p org-indent-mode)
  13824. (* (1- org-indent-indentation-per-level)
  13825. (1- level))
  13826. 0))
  13827. (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
  13828. (tc (+ org-tags-column
  13829. (if (> org-tags-column 0) (- di) di)))
  13830. (c1 (max (1+ c0)
  13831. (if (> tc 0) tc
  13832. (- (- tc) (string-width tags)))))
  13833. (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
  13834. (replace-match rpl t t)
  13835. (when indent-tabs-mode (tabify p0 (point))))))
  13836. (t (error "Tags alignment failed"))))
  13837. (org-move-to-column col))
  13838. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13839. (defun org-change-tag-in-region (beg end tag off)
  13840. "Add or remove TAG for each entry in the region.
  13841. This works in the agenda, and also in an org-mode buffer."
  13842. (interactive
  13843. (list (region-beginning) (region-end)
  13844. (let ((org-last-tags-completion-table
  13845. (if (derived-mode-p 'org-mode)
  13846. (org-uniquify
  13847. (delq nil (append (org-get-buffer-tags)
  13848. (org-global-tags-completion-table))))
  13849. (org-global-tags-completion-table))))
  13850. (completing-read
  13851. "Tag: " 'org-tags-completion-function nil nil nil
  13852. 'org-tags-history))
  13853. (progn
  13854. (message "[s]et or [r]emove? ")
  13855. (equal (read-char-exclusive) ?r))))
  13856. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13857. (let ((agendap (equal major-mode 'org-agenda-mode))
  13858. l1 l2 m buf pos newhead (cnt 0))
  13859. (goto-char end)
  13860. (setq l2 (1- (org-current-line)))
  13861. (goto-char beg)
  13862. (setq l1 (org-current-line))
  13863. (cl-loop for l from l1 to l2 do
  13864. (org-goto-line l)
  13865. (setq m (get-text-property (point) 'org-hd-marker))
  13866. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13867. (and agendap m))
  13868. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13869. pos (if agendap m (point)))
  13870. (with-current-buffer buf
  13871. (save-excursion
  13872. (save-restriction
  13873. (goto-char pos)
  13874. (setq cnt (1+ cnt))
  13875. (org-toggle-tag tag (if off 'off 'on))
  13876. (setq newhead (org-get-heading)))))
  13877. (and agendap (org-agenda-change-all-lines newhead m))))
  13878. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13879. (defun org-tags-completion-function (string _predicate &optional flag)
  13880. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13881. (confirm (lambda (x) (stringp (car x)))))
  13882. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13883. (setq s1 (match-string 1 string)
  13884. s2 (match-string 2 string))
  13885. (setq s1 "" s2 string))
  13886. (cond
  13887. ((eq flag nil)
  13888. ;; try completion
  13889. (setq rtn (try-completion s2 ctable confirm))
  13890. (when (stringp rtn)
  13891. (setq rtn
  13892. (concat s1 s2 (substring rtn (length s2))
  13893. (if (and org-add-colon-after-tag-completion
  13894. (assoc rtn ctable))
  13895. ":" ""))))
  13896. rtn)
  13897. ((eq flag t)
  13898. ;; all-completions
  13899. (all-completions s2 ctable confirm))
  13900. ((eq flag 'lambda)
  13901. ;; exact match?
  13902. (assoc s2 ctable)))))
  13903. (defun org-fast-tag-insert (kwd tags face &optional end)
  13904. "Insert KDW, and the TAGS, the latter with face FACE.
  13905. Also insert END."
  13906. (insert (format "%-12s" (concat kwd ":"))
  13907. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13908. (or end "")))
  13909. (defun org-fast-tag-show-exit (flag)
  13910. (save-excursion
  13911. (org-goto-line 3)
  13912. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13913. (replace-match ""))
  13914. (when flag
  13915. (end-of-line 1)
  13916. (org-move-to-column (- (window-width) 19) t)
  13917. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13918. (defun org-set-current-tags-overlay (current prefix)
  13919. "Add an overlay to CURRENT tag with PREFIX."
  13920. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13921. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13922. (org-overlay-display org-tags-overlay (concat prefix s))))
  13923. (defvar org-last-tag-selection-key nil)
  13924. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13925. "Fast tag selection with single keys.
  13926. CURRENT is the current list of tags in the headline, INHERITED is the
  13927. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13928. possibly with grouping information. TODO-TABLE is a similar table with
  13929. TODO keywords, should these have keys assigned to them.
  13930. If the keys are nil, a-z are automatically assigned.
  13931. Returns the new tags string, or nil to not change the current settings."
  13932. (let* ((fulltable (append table todo-table))
  13933. (maxlen (apply 'max (mapcar
  13934. (lambda (x)
  13935. (if (stringp (car x)) (string-width (car x)) 0))
  13936. fulltable)))
  13937. (buf (current-buffer))
  13938. (expert (eq org-fast-tag-selection-single-key 'expert))
  13939. (buffer-tags nil)
  13940. (fwidth (+ maxlen 3 1 3))
  13941. (ncol (/ (- (window-width) 4) fwidth))
  13942. (i-face 'org-done)
  13943. (c-face 'org-todo)
  13944. tg cnt e c char c1 c2 ntable tbl rtn
  13945. ov-start ov-end ov-prefix
  13946. (exit-after-next org-fast-tag-selection-single-key)
  13947. (done-keywords org-done-keywords)
  13948. groups ingroup intaggroup)
  13949. (save-excursion
  13950. (beginning-of-line 1)
  13951. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13952. (setq ov-start (match-beginning 1)
  13953. ov-end (match-end 1)
  13954. ov-prefix "")
  13955. (setq ov-start (1- (point-at-eol))
  13956. ov-end (1+ ov-start))
  13957. (skip-chars-forward "^\n\r")
  13958. (setq ov-prefix
  13959. (concat
  13960. (buffer-substring (1- (point)) (point))
  13961. (if (> (current-column) org-tags-column)
  13962. " "
  13963. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13964. (move-overlay org-tags-overlay ov-start ov-end)
  13965. (save-window-excursion
  13966. (if expert
  13967. (set-buffer (get-buffer-create " *Org tags*"))
  13968. (delete-other-windows)
  13969. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13970. (org-switch-to-buffer-other-window " *Org tags*"))
  13971. (erase-buffer)
  13972. (setq-local org-done-keywords done-keywords)
  13973. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13974. (org-fast-tag-insert "Current" current c-face "\n\n")
  13975. (org-fast-tag-show-exit exit-after-next)
  13976. (org-set-current-tags-overlay current ov-prefix)
  13977. (setq tbl fulltable char ?a cnt 0)
  13978. (while (setq e (pop tbl))
  13979. (cond
  13980. ((eq (car e) :startgroup)
  13981. (push '() groups) (setq ingroup t)
  13982. (unless (zerop cnt)
  13983. (setq cnt 0)
  13984. (insert "\n"))
  13985. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13986. ((eq (car e) :endgroup)
  13987. (setq ingroup nil cnt 0)
  13988. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13989. ((eq (car e) :startgrouptag)
  13990. (setq intaggroup t)
  13991. (unless (zerop cnt)
  13992. (setq cnt 0)
  13993. (insert "\n"))
  13994. (insert "[ "))
  13995. ((eq (car e) :endgrouptag)
  13996. (setq intaggroup nil cnt 0)
  13997. (insert "]\n"))
  13998. ((equal e '(:newline))
  13999. (unless (zerop cnt)
  14000. (setq cnt 0)
  14001. (insert "\n")
  14002. (setq e (car tbl))
  14003. (while (equal (car tbl) '(:newline))
  14004. (insert "\n")
  14005. (setq tbl (cdr tbl)))))
  14006. ((equal e '(:grouptags)) (insert " : "))
  14007. (t
  14008. (setq tg (copy-sequence (car e)) c2 nil)
  14009. (if (cdr e)
  14010. (setq c (cdr e))
  14011. ;; automatically assign a character.
  14012. (setq c1 (string-to-char
  14013. (downcase (substring
  14014. tg (if (= (string-to-char tg) ?@) 1 0)))))
  14015. (if (or (rassoc c1 ntable) (rassoc c1 table))
  14016. (while (or (rassoc char ntable) (rassoc char table))
  14017. (setq char (1+ char)))
  14018. (setq c2 c1))
  14019. (setq c (or c2 char)))
  14020. (when ingroup (push tg (car groups)))
  14021. (setq tg (org-add-props tg nil 'face
  14022. (cond
  14023. ((not (assoc tg table))
  14024. (org-get-todo-face tg))
  14025. ((member tg current) c-face)
  14026. ((member tg inherited) i-face))))
  14027. (when (equal (caar tbl) :grouptags)
  14028. (org-add-props tg nil 'face 'org-tag-group))
  14029. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  14030. (insert "[" c "] " tg (make-string
  14031. (- fwidth 4 (length tg)) ?\ ))
  14032. (push (cons tg c) ntable)
  14033. (when (= (cl-incf cnt) ncol)
  14034. (insert "\n")
  14035. (when (or ingroup intaggroup) (insert " "))
  14036. (setq cnt 0)))))
  14037. (setq ntable (nreverse ntable))
  14038. (insert "\n")
  14039. (goto-char (point-min))
  14040. (unless expert (org-fit-window-to-buffer))
  14041. (setq rtn
  14042. (catch 'exit
  14043. (while t
  14044. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  14045. (if (not groups) "no " "")
  14046. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  14047. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  14048. (setq org-last-tag-selection-key c)
  14049. (cond
  14050. ((= c ?\r) (throw 'exit t))
  14051. ((= c ?!)
  14052. (setq groups (not groups))
  14053. (goto-char (point-min))
  14054. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  14055. ((= c ?\C-c)
  14056. (if (not expert)
  14057. (org-fast-tag-show-exit
  14058. (setq exit-after-next (not exit-after-next)))
  14059. (setq expert nil)
  14060. (delete-other-windows)
  14061. (set-window-buffer (split-window-vertically) " *Org tags*")
  14062. (org-switch-to-buffer-other-window " *Org tags*")
  14063. (org-fit-window-to-buffer)))
  14064. ((or (= c ?\C-g)
  14065. (and (= c ?q) (not (rassoc c ntable))))
  14066. (delete-overlay org-tags-overlay)
  14067. (setq quit-flag t))
  14068. ((= c ?\ )
  14069. (setq current nil)
  14070. (when exit-after-next (setq exit-after-next 'now)))
  14071. ((= c ?\t)
  14072. (condition-case nil
  14073. (setq tg (completing-read
  14074. "Tag: "
  14075. (or buffer-tags
  14076. (with-current-buffer buf
  14077. (setq buffer-tags
  14078. (org-get-buffer-tags))))))
  14079. (quit (setq tg "")))
  14080. (when (string-match "\\S-" tg)
  14081. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14082. (if (member tg current)
  14083. (setq current (delete tg current))
  14084. (push tg current)))
  14085. (when exit-after-next (setq exit-after-next 'now)))
  14086. ((setq e (rassoc c todo-table) tg (car e))
  14087. (with-current-buffer buf
  14088. (save-excursion (org-todo tg)))
  14089. (when exit-after-next (setq exit-after-next 'now)))
  14090. ((setq e (rassoc c ntable) tg (car e))
  14091. (if (member tg current)
  14092. (setq current (delete tg current))
  14093. (cl-loop for g in groups do
  14094. (when (member tg g)
  14095. (dolist (x g) (setq current (delete x current)))))
  14096. (push tg current))
  14097. (when exit-after-next (setq exit-after-next 'now))))
  14098. ;; Create a sorted list
  14099. (setq current
  14100. (sort current
  14101. (lambda (a b)
  14102. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14103. (when (eq exit-after-next 'now) (throw 'exit t))
  14104. (goto-char (point-min))
  14105. (beginning-of-line 2)
  14106. (delete-region (point) (point-at-eol))
  14107. (org-fast-tag-insert "Current" current c-face)
  14108. (org-set-current-tags-overlay current ov-prefix)
  14109. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14110. (setq tg (match-string 1))
  14111. (add-text-properties
  14112. (match-beginning 1) (match-end 1)
  14113. (list 'face
  14114. (cond
  14115. ((member tg current) c-face)
  14116. ((member tg inherited) i-face)
  14117. (t (get-text-property (match-beginning 1) 'face))))))
  14118. (goto-char (point-min)))))
  14119. (delete-overlay org-tags-overlay)
  14120. (if rtn
  14121. (mapconcat 'identity current ":")
  14122. nil))))
  14123. (defun org-get-tags-string ()
  14124. "Get the TAGS string in the current headline."
  14125. (unless (org-at-heading-p t)
  14126. (user-error "Not on a heading"))
  14127. (save-excursion
  14128. (beginning-of-line 1)
  14129. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14130. (match-string-no-properties 1)
  14131. "")))
  14132. (defun org-get-tags ()
  14133. "Get the list of tags specified in the current headline."
  14134. (org-split-string (org-get-tags-string) ":"))
  14135. (defun org-get-buffer-tags ()
  14136. "Get a table of all tags used in the buffer, for completion."
  14137. (org-with-wide-buffer
  14138. (goto-char (point-min))
  14139. (let ((tag-re (concat org-outline-regexp-bol
  14140. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14141. tags)
  14142. (while (re-search-forward tag-re nil t)
  14143. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14144. (push tag tags)))
  14145. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14146. ;;;; The mapping API
  14147. (defvar org-agenda-skip-comment-trees)
  14148. (defvar org-agenda-skip-function)
  14149. (defun org-map-entries (func &optional match scope &rest skip)
  14150. "Call FUNC at each headline selected by MATCH in SCOPE.
  14151. FUNC is a function or a lisp form. The function will be called without
  14152. arguments, with the cursor positioned at the beginning of the headline.
  14153. The return values of all calls to the function will be collected and
  14154. returned as a list.
  14155. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14156. does not need to preserve point. After evaluation, the cursor will be
  14157. moved to the end of the line (presumably of the headline of the
  14158. processed entry) and search continues from there. Under some
  14159. circumstances, this may not produce the wanted results. For example,
  14160. if you have removed (e.g. archived) the current (sub)tree it could
  14161. mean that the next entry will be skipped entirely. In such cases, you
  14162. can specify the position from where search should continue by making
  14163. FUNC set the variable `org-map-continue-from' to the desired buffer
  14164. position.
  14165. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14166. Only headlines that are matched by this query will be considered during
  14167. the iteration. When MATCH is nil or t, all headlines will be
  14168. visited by the iteration.
  14169. SCOPE determines the scope of this command. It can be any of:
  14170. nil The current buffer, respecting the restriction if any
  14171. tree The subtree started with the entry at point
  14172. region The entries within the active region, if any
  14173. region-start-level
  14174. The entries within the active region, but only those at
  14175. the same level than the first one.
  14176. file The current buffer, without restriction
  14177. file-with-archives
  14178. The current buffer, and any archives associated with it
  14179. agenda All agenda files
  14180. agenda-with-archives
  14181. All agenda files with any archive files associated with them
  14182. \(file1 file2 ...)
  14183. If this is a list, all files in the list will be scanned
  14184. The remaining args are treated as settings for the skipping facilities of
  14185. the scanner. The following items can be given here:
  14186. archive skip trees with the archive tag
  14187. comment skip trees with the COMMENT keyword
  14188. function or Emacs Lisp form:
  14189. will be used as value for `org-agenda-skip-function', so
  14190. whenever the function returns a position, FUNC will not be
  14191. called for that entry and search will continue from the
  14192. position returned
  14193. If your function needs to retrieve the tags including inherited tags
  14194. at the *current* entry, you can use the value of the variable
  14195. `org-scanner-tags' which will be much faster than getting the value
  14196. with `org-get-tags-at'. If your function gets properties with
  14197. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14198. to t around the call to `org-entry-properties' to get the same speedup.
  14199. Note that if your function moves around to retrieve tags and properties at
  14200. a *different* entry, you cannot use these techniques."
  14201. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14202. (not (org-region-active-p)))
  14203. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14204. (org-agenda-skip-archived-trees (memq 'archive skip))
  14205. (org-agenda-skip-comment-trees (memq 'comment skip))
  14206. (org-agenda-skip-function
  14207. (car (org-delete-all '(comment archive) skip)))
  14208. (org-tags-match-list-sublevels t)
  14209. (start-level (eq scope 'region-start-level))
  14210. matcher res
  14211. org-todo-keywords-for-agenda
  14212. org-done-keywords-for-agenda
  14213. org-todo-keyword-alist-for-agenda
  14214. org-tag-alist-for-agenda
  14215. org--matcher-tags-todo-only)
  14216. (cond
  14217. ((eq match t) (setq matcher t))
  14218. ((eq match nil) (setq matcher t))
  14219. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14220. (save-excursion
  14221. (save-restriction
  14222. (cond ((eq scope 'tree)
  14223. (org-back-to-heading t)
  14224. (org-narrow-to-subtree)
  14225. (setq scope nil))
  14226. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14227. (org-region-active-p))
  14228. ;; If needed, set start-level to a string like "2"
  14229. (when start-level
  14230. (save-excursion
  14231. (goto-char (region-beginning))
  14232. (unless (org-at-heading-p) (outline-next-heading))
  14233. (setq start-level (org-current-level))))
  14234. (narrow-to-region (region-beginning)
  14235. (save-excursion
  14236. (goto-char (region-end))
  14237. (unless (and (bolp) (org-at-heading-p))
  14238. (outline-next-heading))
  14239. (point)))
  14240. (setq scope nil)))
  14241. (if (not scope)
  14242. (progn
  14243. (org-agenda-prepare-buffers
  14244. (and buffer-file-name (list buffer-file-name)))
  14245. (setq res
  14246. (org-scan-tags
  14247. func matcher org--matcher-tags-todo-only start-level)))
  14248. ;; Get the right scope
  14249. (cond
  14250. ((and scope (listp scope) (symbolp (car scope)))
  14251. (setq scope (eval scope)))
  14252. ((eq scope 'agenda)
  14253. (setq scope (org-agenda-files t)))
  14254. ((eq scope 'agenda-with-archives)
  14255. (setq scope (org-agenda-files t))
  14256. (setq scope (org-add-archive-files scope)))
  14257. ((eq scope 'file)
  14258. (setq scope (and buffer-file-name (list buffer-file-name))))
  14259. ((eq scope 'file-with-archives)
  14260. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14261. (org-agenda-prepare-buffers scope)
  14262. (dolist (file scope)
  14263. (with-current-buffer (org-find-base-buffer-visiting file)
  14264. (save-excursion
  14265. (save-restriction
  14266. (widen)
  14267. (goto-char (point-min))
  14268. (setq res
  14269. (append
  14270. res
  14271. (org-scan-tags
  14272. func matcher org--matcher-tags-todo-only))))))))))
  14273. res)))
  14274. ;;; Properties API
  14275. (defconst org-special-properties
  14276. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14277. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14278. "The special properties valid in Org mode.
  14279. These are properties that are not defined in the property drawer,
  14280. but in some other way.")
  14281. (defconst org-default-properties
  14282. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14283. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14284. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14285. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14286. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14287. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14288. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14289. "Some properties that are used by Org mode for various purposes.
  14290. Being in this list makes sure that they are offered for completion.")
  14291. (defun org--valid-property-p (property)
  14292. "Non nil when string PROPERTY is a valid property name."
  14293. (not
  14294. (or (equal property "")
  14295. (org-string-match-p "\\s-" property))))
  14296. (defun org--update-property-plist (key val props)
  14297. "Associate KEY to VAL in alist PROPS.
  14298. Modifications are made by side-effect. Return new alist."
  14299. (let* ((appending (string= (substring key -1) "+"))
  14300. (key (if appending (substring key 0 -1) key))
  14301. (old (assoc-string key props t)))
  14302. (if (not old) (cons (cons key val) props)
  14303. (setcdr old (if appending (concat (cdr old) " " val) val))
  14304. props)))
  14305. (defun org-get-property-block (&optional beg force)
  14306. "Return the (beg . end) range of the body of the property drawer.
  14307. BEG is the beginning of the current subtree, or of the part
  14308. before the first headline. If it is not given, it will be found.
  14309. If the drawer does not exist, create it if FORCE is non-nil, or
  14310. return nil."
  14311. (org-with-wide-buffer
  14312. (when beg (goto-char beg))
  14313. (unless (org-before-first-heading-p)
  14314. (let ((beg (cond (beg)
  14315. ((or (not (featurep 'org-inlinetask))
  14316. (org-inlinetask-in-task-p))
  14317. (org-back-to-heading t))
  14318. (t (org-with-limited-levels (org-back-to-heading t))))))
  14319. (forward-line)
  14320. (when (looking-at-p org-planning-line-re) (forward-line))
  14321. (cond ((looking-at org-property-drawer-re)
  14322. (forward-line)
  14323. (cons (point) (progn (goto-char (match-end 0))
  14324. (line-beginning-position))))
  14325. (force
  14326. (goto-char beg)
  14327. (org-insert-property-drawer)
  14328. (let ((pos (save-excursion (search-forward ":END:")
  14329. (line-beginning-position))))
  14330. (cons pos pos))))))))
  14331. (defun org-at-property-p ()
  14332. "Non-nil when point is inside a property drawer.
  14333. See `org-property-re' for match data, if applicable."
  14334. (save-excursion
  14335. (beginning-of-line)
  14336. (and (looking-at org-property-re)
  14337. (let ((property-drawer (save-match-data (org-get-property-block))))
  14338. (and property-drawer
  14339. (>= (point) (car property-drawer))
  14340. (< (point) (cdr property-drawer)))))))
  14341. (defun org-property-action ()
  14342. "Do an action on properties."
  14343. (interactive)
  14344. (unless (org-at-property-p) (user-error "Not at a property"))
  14345. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14346. (let ((c (read-char-exclusive)))
  14347. (cl-case c
  14348. (?s (call-interactively #'org-set-property))
  14349. (?d (call-interactively #'org-delete-property))
  14350. (?D (call-interactively #'org-delete-property-globally))
  14351. (?c (call-interactively #'org-compute-property-at-point))
  14352. (otherwise (user-error "No such property action %c" c)))))
  14353. (defun org-inc-effort ()
  14354. "Increment the value of the effort property in the current entry."
  14355. (interactive)
  14356. (org-set-effort nil t))
  14357. (defvar org-clock-effort) ; Defined in org-clock.el.
  14358. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14359. (defun org-set-effort (&optional value increment)
  14360. "Set the effort property of the current entry.
  14361. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14362. 10th allowed value.
  14363. When INCREMENT is non-nil, set the property to the next allowed value."
  14364. (interactive "P")
  14365. (when (equal value 0) (setq value 10))
  14366. (let* ((completion-ignore-case t)
  14367. (prop org-effort-property)
  14368. (cur (org-entry-get nil prop))
  14369. (allowed (org-property-get-allowed-values nil prop 'table))
  14370. (existing (mapcar 'list (org-property-values prop)))
  14371. (heading (nth 4 (org-heading-components)))
  14372. rpl
  14373. (val (cond
  14374. ((stringp value) value)
  14375. ((and allowed (integerp value))
  14376. (or (car (nth (1- value) allowed))
  14377. (car (org-last allowed))))
  14378. ((and allowed increment)
  14379. (or (cl-caadr (member (list cur) allowed))
  14380. (user-error "Allowed effort values are not set")))
  14381. (allowed
  14382. (message "Select 1-9,0, [RET%s]: %s"
  14383. (if cur (concat "=" cur) "")
  14384. (mapconcat 'car allowed " "))
  14385. (setq rpl (read-char-exclusive))
  14386. (if (equal rpl ?\r)
  14387. cur
  14388. (setq rpl (- rpl ?0))
  14389. (when (equal rpl 0) (setq rpl 10))
  14390. (if (and (> rpl 0) (<= rpl (length allowed)))
  14391. (car (nth (1- rpl) allowed))
  14392. (org-completing-read "Effort: " allowed nil))))
  14393. (t
  14394. (org-completing-read
  14395. (concat "Effort" (and cur (string-match "\\S-" cur)
  14396. (concat " [" cur "]"))
  14397. ": ")
  14398. existing nil nil "" nil cur)))))
  14399. (unless (equal (org-entry-get nil prop) val)
  14400. (org-entry-put nil prop val))
  14401. (org-refresh-property
  14402. '((effort . identity)
  14403. (effort-minutes . org-duration-string-to-minutes))
  14404. val)
  14405. (when (equal heading (bound-and-true-p org-clock-current-task))
  14406. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14407. (org-clock-update-mode-line))
  14408. (message "%s is now %s" prop val)))
  14409. (defun org-entry-properties (&optional pom which)
  14410. "Get all properties of the current entry.
  14411. When POM is a buffer position, get all properties from the entry
  14412. there instead.
  14413. This includes the TODO keyword, the tags, time strings for
  14414. deadline, scheduled, and clocking, and any additional properties
  14415. defined in the entry.
  14416. If WHICH is nil or `all', get all properties. If WHICH is
  14417. `special' or `standard', only get that subclass. If WHICH is
  14418. a string, only get that property.
  14419. Return value is an alist. Keys are properties, as upcased
  14420. strings."
  14421. (org-with-point-at pom
  14422. (when (and (derived-mode-p 'org-mode)
  14423. (ignore-errors (org-back-to-heading t)))
  14424. (catch 'exit
  14425. (let* ((beg (point))
  14426. (specific (and (stringp which) (upcase which)))
  14427. (which (cond ((not specific) which)
  14428. ((member specific org-special-properties) 'special)
  14429. (t 'standard)))
  14430. props)
  14431. ;; Get the special properties, like TODO and TAGS.
  14432. (when (memq which '(nil all special))
  14433. (when (or (not specific) (string= specific "CLOCKSUM"))
  14434. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14435. (when clocksum
  14436. (push (cons "CLOCKSUM"
  14437. (org-minutes-to-clocksum-string clocksum))
  14438. props)))
  14439. (when specific (throw 'exit props)))
  14440. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14441. (let ((clocksumt (get-text-property (point)
  14442. :org-clock-minutes-today)))
  14443. (when clocksumt
  14444. (push (cons "CLOCKSUM_T"
  14445. (org-minutes-to-clocksum-string clocksumt))
  14446. props)))
  14447. (when specific (throw 'exit props)))
  14448. (when (or (not specific) (string= specific "ITEM"))
  14449. (when (looking-at org-complex-heading-regexp)
  14450. (push (cons "ITEM"
  14451. (let ((title (match-string-no-properties 4)))
  14452. (if (org-string-nw-p title)
  14453. (org-remove-tabs title)
  14454. "")))
  14455. props))
  14456. (when specific (throw 'exit props)))
  14457. (when (or (not specific) (string= specific "TODO"))
  14458. (let ((case-fold-search nil))
  14459. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14460. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14461. (when specific (throw 'exit props)))
  14462. (when (or (not specific) (string= specific "PRIORITY"))
  14463. (push (cons "PRIORITY"
  14464. (if (looking-at org-priority-regexp)
  14465. (match-string-no-properties 2)
  14466. (char-to-string org-default-priority)))
  14467. props)
  14468. (when specific (throw 'exit props)))
  14469. (when (or (not specific) (string= specific "FILE"))
  14470. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14471. props)
  14472. (when specific (throw 'exit props)))
  14473. (when (or (not specific) (string= specific "TAGS"))
  14474. (let ((value (org-string-nw-p (org-get-tags-string))))
  14475. (when value (push (cons "TAGS" value) props)))
  14476. (when specific (throw 'exit props)))
  14477. (when (or (not specific) (string= specific "ALLTAGS"))
  14478. (let ((value (org-get-tags-at)))
  14479. (when value
  14480. (push (cons "ALLTAGS"
  14481. (format ":%s:" (mapconcat #'identity value ":")))
  14482. props)))
  14483. (when specific (throw 'exit props)))
  14484. (when (or (not specific) (string= specific "BLOCKED"))
  14485. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14486. (when specific (throw 'exit props)))
  14487. (when (or (not specific)
  14488. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14489. (forward-line)
  14490. (when (looking-at-p org-planning-line-re)
  14491. (end-of-line)
  14492. (let ((bol (line-beginning-position))
  14493. ;; Backward compatibility: time keywords used to
  14494. ;; be configurable (before 8.3). Make sure we
  14495. ;; get the correct keyword.
  14496. (key-assoc `(("CLOSED" . ,org-closed-string)
  14497. ("DEADLINE" . ,org-deadline-string)
  14498. ("SCHEDULED" . ,org-scheduled-string))))
  14499. (dolist (pair (if specific (list (assoc specific key-assoc))
  14500. key-assoc))
  14501. (save-excursion
  14502. (when (search-backward (cdr pair) bol t)
  14503. (goto-char (match-end 0))
  14504. (skip-chars-forward " \t")
  14505. (and (looking-at org-ts-regexp-both)
  14506. (push (cons (car pair)
  14507. (match-string-no-properties 0))
  14508. props)))))))
  14509. (when specific (throw 'exit props)))
  14510. (when (or (not specific)
  14511. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14512. (let ((find-ts
  14513. (lambda (end ts)
  14514. ;; Fix next time-stamp before END. TS is the
  14515. ;; list of time-stamps found so far.
  14516. (let ((ts ts)
  14517. (regexp (cond
  14518. ((string= specific "TIMESTAMP")
  14519. org-ts-regexp)
  14520. ((string= specific "TIMESTAMP_IA")
  14521. org-ts-regexp-inactive)
  14522. ((assoc "TIMESTAMP_IA" ts)
  14523. org-ts-regexp)
  14524. ((assoc "TIMESTAMP" ts)
  14525. org-ts-regexp-inactive)
  14526. (t org-ts-regexp-both))))
  14527. (catch 'next
  14528. (while (re-search-forward regexp end t)
  14529. (backward-char)
  14530. (let ((object (org-element-context)))
  14531. ;; Accept to match timestamps in node
  14532. ;; properties, too.
  14533. (when (memq (org-element-type object)
  14534. '(node-property timestamp))
  14535. (let ((type
  14536. (org-element-property :type object)))
  14537. (cond
  14538. ((and (memq type '(active active-range))
  14539. (not (equal specific "TIMESTAMP_IA")))
  14540. (unless (assoc "TIMESTAMP" ts)
  14541. (push (cons "TIMESTAMP"
  14542. (org-element-property
  14543. :raw-value object))
  14544. ts)
  14545. (when specific (throw 'exit ts))))
  14546. ((and (memq type '(inactive inactive-range))
  14547. (not (string= specific "TIMESTAMP")))
  14548. (unless (assoc "TIMESTAMP_IA" ts)
  14549. (push (cons "TIMESTAMP_IA"
  14550. (org-element-property
  14551. :raw-value object))
  14552. ts)
  14553. (when specific (throw 'exit ts))))))
  14554. ;; Both timestamp types are found,
  14555. ;; move to next part.
  14556. (when (= (length ts) 2) (throw 'next ts)))))
  14557. ts)))))
  14558. (goto-char beg)
  14559. ;; First look for timestamps within headline.
  14560. (let ((ts (funcall find-ts (line-end-position) nil)))
  14561. (if (= (length ts) 2) (setq props (nconc ts props))
  14562. (forward-line)
  14563. ;; Then find timestamps in the section, skipping
  14564. ;; planning line.
  14565. (when (looking-at-p org-planning-line-re)
  14566. (forward-line))
  14567. (let ((end (save-excursion (outline-next-heading))))
  14568. (setq props (nconc (funcall find-ts end ts) props))))))))
  14569. ;; Get the standard properties, like :PROP:.
  14570. (when (memq which '(nil all standard))
  14571. ;; If we are looking after a specific property, delegate
  14572. ;; to `org-entry-get', which is faster. However, make an
  14573. ;; exception for "CATEGORY", since it can be also set
  14574. ;; through keywords (i.e. #+CATEGORY).
  14575. (if (and specific (not (equal specific "CATEGORY")))
  14576. (let ((value (org-entry-get beg specific nil t)))
  14577. (throw 'exit (and value (list (cons specific value)))))
  14578. (let ((range (org-get-property-block beg)))
  14579. (when range
  14580. (let ((end (cdr range)) seen-base)
  14581. (goto-char (car range))
  14582. ;; Unlike to `org--update-property-plist', we
  14583. ;; handle the case where base values is found
  14584. ;; after its extension. We also forbid standard
  14585. ;; properties to be named as special properties.
  14586. (while (re-search-forward org-property-re end t)
  14587. (let* ((key (upcase (match-string-no-properties 2)))
  14588. (extendp (org-string-match-p "\\+\\'" key))
  14589. (key-base (if extendp (substring key 0 -1) key))
  14590. (value (match-string-no-properties 3)))
  14591. (cond
  14592. ((member-ignore-case key-base org-special-properties))
  14593. (extendp
  14594. (setq props
  14595. (org--update-property-plist key value props)))
  14596. ((member key seen-base))
  14597. (t (push key seen-base)
  14598. (let ((p (assoc-string key props t)))
  14599. (if p (setcdr p (concat value " " (cdr p)))
  14600. (push (cons key value) props))))))))))))
  14601. (unless (assoc "CATEGORY" props)
  14602. (push (cons "CATEGORY" (org-get-category beg)) props)
  14603. (when (string= specific "CATEGORY") (throw 'exit props)))
  14604. ;; Return value.
  14605. props)))))
  14606. (defun org-property--local-values (property literal-nil)
  14607. "Return value for PROPERTY in current entry.
  14608. Value is a list whose car is the base value for PROPERTY and cdr
  14609. a list of accumulated values. Return nil if neither is found in
  14610. the entry. Also return nil when PROPERTY is set to \"nil\",
  14611. unless LITERAL-NIL is non-nil."
  14612. (let ((range (org-get-property-block)))
  14613. (when range
  14614. (goto-char (car range))
  14615. (let* ((case-fold-search t)
  14616. (end (cdr range))
  14617. (value
  14618. ;; Base value.
  14619. (save-excursion
  14620. (let ((v (and (re-search-forward
  14621. (org-re-property property nil t) end t)
  14622. (match-string-no-properties 3))))
  14623. (list (if literal-nil v (org-not-nil v)))))))
  14624. ;; Find additional values.
  14625. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14626. (while (re-search-forward property+ end t)
  14627. (push (match-string-no-properties 3) value)))
  14628. ;; Return final values.
  14629. (and (not (equal value '(nil))) (nreverse value))))))
  14630. (defun org-entry-get (pom property &optional inherit literal-nil)
  14631. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14632. If INHERIT is non-nil and the entry does not have the property,
  14633. then also check higher levels of the hierarchy. If INHERIT is
  14634. the symbol `selective', use inheritance only if the setting in
  14635. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14636. If the property is present but empty, the return value is the
  14637. empty string. If the property is not present at all, nil is
  14638. returned. In any other case, return the value as a string.
  14639. Search is case-insensitive.
  14640. If LITERAL-NIL is set, return the string value \"nil\" as
  14641. a string, do not interpret it as the list atom nil. This is used
  14642. for inheritance when a \"nil\" value can supersede a non-nil
  14643. value higher up the hierarchy."
  14644. (org-with-point-at pom
  14645. (cond
  14646. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14647. ;; We need a special property. Use `org-entry-properties' to
  14648. ;; retrieve it, but specify the wanted property.
  14649. (cdr (assoc-string property (org-entry-properties nil property))))
  14650. ((and inherit
  14651. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14652. (org-entry-get-with-inheritance property literal-nil))
  14653. (t
  14654. (let* ((local (org-property--local-values property literal-nil))
  14655. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14656. (if literal-nil value (org-not-nil value)))))))
  14657. (defun org-property-or-variable-value (var &optional inherit)
  14658. "Check if there is a property fixing the value of VAR.
  14659. If yes, return this value. If not, return the current value of the variable."
  14660. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14661. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14662. (read prop)
  14663. (symbol-value var))))
  14664. (defun org-entry-delete (pom property)
  14665. "Delete PROPERTY from entry at point-or-marker POM.
  14666. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14667. non-nil when a property was removed."
  14668. (unless (member property org-special-properties)
  14669. (org-with-point-at pom
  14670. (let ((range (org-get-property-block)))
  14671. (when range
  14672. (let* ((begin (car range))
  14673. (origin (cdr range))
  14674. (end (copy-marker origin))
  14675. (re (org-re-property
  14676. (concat (regexp-quote property) "\\+?") t t)))
  14677. (goto-char begin)
  14678. (while (re-search-forward re end t)
  14679. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14680. ;; If drawer is empty, remove it altogether.
  14681. (when (= begin end)
  14682. (delete-region (line-beginning-position 0)
  14683. (line-beginning-position 2)))
  14684. ;; Return non-nil if some property was removed.
  14685. (prog1 (/= end origin) (set-marker end nil))))))))
  14686. ;; Multi-values properties are properties that contain multiple values
  14687. ;; These values are assumed to be single words, separated by whitespace.
  14688. (defun org-entry-add-to-multivalued-property (pom property value)
  14689. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14690. (let* ((old (org-entry-get pom property))
  14691. (values (and old (org-split-string old "[ \t]"))))
  14692. (setq value (org-entry-protect-space value))
  14693. (unless (member value values)
  14694. (setq values (append values (list value)))
  14695. (org-entry-put pom property
  14696. (mapconcat 'identity values " ")))))
  14697. (defun org-entry-remove-from-multivalued-property (pom property value)
  14698. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14699. (let* ((old (org-entry-get pom property))
  14700. (values (and old (org-split-string old "[ \t]"))))
  14701. (setq value (org-entry-protect-space value))
  14702. (when (member value values)
  14703. (setq values (delete value values))
  14704. (org-entry-put pom property
  14705. (mapconcat 'identity values " ")))))
  14706. (defun org-entry-member-in-multivalued-property (pom property value)
  14707. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14708. (let* ((old (org-entry-get pom property))
  14709. (values (and old (org-split-string old "[ \t]"))))
  14710. (setq value (org-entry-protect-space value))
  14711. (member value values)))
  14712. (defun org-entry-get-multivalued-property (pom property)
  14713. "Return a list of values in a multivalued property."
  14714. (let* ((value (org-entry-get pom property))
  14715. (values (and value (org-split-string value "[ \t]"))))
  14716. (mapcar 'org-entry-restore-space values)))
  14717. (defun org-entry-put-multivalued-property (pom property &rest values)
  14718. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14719. VALUES should be a list of strings. Spaces will be protected."
  14720. (org-entry-put pom property
  14721. (mapconcat 'org-entry-protect-space values " "))
  14722. (let* ((value (org-entry-get pom property))
  14723. (values (and value (org-split-string value "[ \t]"))))
  14724. (mapcar 'org-entry-restore-space values)))
  14725. (defun org-entry-protect-space (s)
  14726. "Protect spaces and newline in string S."
  14727. (while (string-match " " s)
  14728. (setq s (replace-match "%20" t t s)))
  14729. (while (string-match "\n" s)
  14730. (setq s (replace-match "%0A" t t s)))
  14731. s)
  14732. (defun org-entry-restore-space (s)
  14733. "Restore spaces and newline in string S."
  14734. (while (string-match "%20" s)
  14735. (setq s (replace-match " " t t s)))
  14736. (while (string-match "%0A" s)
  14737. (setq s (replace-match "\n" t t s)))
  14738. s)
  14739. (defvar org-entry-property-inherited-from (make-marker)
  14740. "Marker pointing to the entry from where a property was inherited.
  14741. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14742. location of the entry where the inheritance search matched. If there was
  14743. no match, the marker will point nowhere.
  14744. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14745. is set.")
  14746. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14747. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14748. The search will stop at the first ancestor which has the property defined.
  14749. If the value found is \"nil\", return nil to show that the property
  14750. should be considered as undefined (this is the meaning of nil here).
  14751. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14752. (move-marker org-entry-property-inherited-from nil)
  14753. (org-with-wide-buffer
  14754. (let (value)
  14755. (catch 'exit
  14756. (while t
  14757. (let ((v (org-property--local-values property literal-nil)))
  14758. (when v
  14759. (setq value
  14760. (concat (mapconcat #'identity (delq nil v) " ")
  14761. (and value " ")
  14762. value)))
  14763. (cond
  14764. ((car v)
  14765. (org-back-to-heading t)
  14766. (move-marker org-entry-property-inherited-from (point))
  14767. (throw 'exit nil))
  14768. ((org-up-heading-safe))
  14769. (t
  14770. (let ((global
  14771. (cdr (or (assoc-string property org-file-properties t)
  14772. (assoc-string property org-global-properties t)
  14773. (assoc-string property org-global-properties-fixed t)))))
  14774. (cond ((not global))
  14775. (value (setq value (concat global " " value)))
  14776. (t (setq value global))))
  14777. (throw 'exit nil))))))
  14778. (if literal-nil value (org-not-nil value)))))
  14779. (defvar org-property-changed-functions nil
  14780. "Hook called when the value of a property has changed.
  14781. Each hook function should accept two arguments, the name of the property
  14782. and the new value.")
  14783. (defun org-entry-put (pom property value)
  14784. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14785. If the value is nil, it is converted to the empty string. If it
  14786. is not a string, an error is raised. Also raise an error on
  14787. invalid property names.
  14788. PROPERTY can be any regular property (see
  14789. `org-special-properties'). It can also be \"TODO\",
  14790. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14791. For the last two properties, VALUE may have any of the special
  14792. values \"earlier\" and \"later\". The function then increases or
  14793. decreases scheduled or deadline date by one day."
  14794. (cond ((null value) (setq value ""))
  14795. ((not (stringp value)) (error "Properties values should be strings"))
  14796. ((not (org--valid-property-p property))
  14797. (user-error "Invalid property name: \"%s\"" property)))
  14798. (org-with-point-at pom
  14799. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14800. (org-back-to-heading t)
  14801. (org-with-limited-levels (org-back-to-heading t)))
  14802. (let ((beg (point)))
  14803. (cond
  14804. ((equal property "TODO")
  14805. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14806. ((not (member value org-todo-keywords-1))
  14807. (user-error "\"%s\" is not a valid TODO state" value)))
  14808. (org-todo value)
  14809. (org-set-tags nil 'align))
  14810. ((equal property "PRIORITY")
  14811. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14812. (org-set-tags nil 'align))
  14813. ((equal property "SCHEDULED")
  14814. (forward-line)
  14815. (if (and (looking-at-p org-planning-line-re)
  14816. (re-search-forward
  14817. org-scheduled-time-regexp (line-end-position) t))
  14818. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14819. ((string= value "later") (org-timestamp-change 1 'day))
  14820. ((string= value "") (org-schedule '(4)))
  14821. (t (org-schedule nil value)))
  14822. (if (member value '("earlier" "later" ""))
  14823. (call-interactively #'org-schedule)
  14824. (org-schedule nil value))))
  14825. ((equal property "DEADLINE")
  14826. (forward-line)
  14827. (if (and (looking-at-p org-planning-line-re)
  14828. (re-search-forward
  14829. org-deadline-time-regexp (line-end-position) t))
  14830. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14831. ((string= value "later") (org-timestamp-change 1 'day))
  14832. ((string= value "") (org-deadline '(4)))
  14833. (t (org-deadline nil value)))
  14834. (if (member value '("earlier" "later" ""))
  14835. (call-interactively #'org-deadline)
  14836. (org-deadline nil value))))
  14837. ((member property org-special-properties)
  14838. (error "The %s property cannot be set with `org-entry-put'" property))
  14839. (t
  14840. (let* ((range (org-get-property-block beg 'force))
  14841. (end (cdr range))
  14842. (case-fold-search t))
  14843. (goto-char (car range))
  14844. (if (re-search-forward (org-re-property property nil t) end t)
  14845. (progn (delete-region (match-beginning 0) (match-end 0))
  14846. (goto-char (match-beginning 0)))
  14847. (goto-char end)
  14848. (insert "\n")
  14849. (backward-char))
  14850. (insert ":" property ":")
  14851. (when value (insert " " value))
  14852. (org-indent-line)))))
  14853. (run-hook-with-args 'org-property-changed-functions property value)))
  14854. (defun org-buffer-property-keys
  14855. (&optional specials defaults columns ignore-malformed)
  14856. "Get all property keys in the current buffer.
  14857. When SPECIALS is non-nil, also list the special properties that
  14858. reflect things like tags and TODO state.
  14859. When DEFAULTS is non-nil, also include properties that has
  14860. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14861. DESCRIPTION, LOCATION, and LOGGING and others.
  14862. When COLUMNS in non-nil, also include property names given in
  14863. COLUMN formats in the current buffer.
  14864. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14865. automatically performed, such drawers will be silently ignored."
  14866. (let ((case-fold-search t)
  14867. (props (append
  14868. (and specials org-special-properties)
  14869. (and defaults (cons org-effort-property org-default-properties))
  14870. nil)))
  14871. (org-with-wide-buffer
  14872. (goto-char (point-min))
  14873. (while (re-search-forward org-property-start-re nil t)
  14874. (let ((range (org-get-property-block)))
  14875. (catch 'skip
  14876. (unless range
  14877. (when (and (not ignore-malformed)
  14878. (not (org-before-first-heading-p))
  14879. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14880. (line-beginning-position))))
  14881. (org-get-property-block nil t))
  14882. (throw 'skip nil))
  14883. (goto-char (car range))
  14884. (let ((begin (car range))
  14885. (end (cdr range)))
  14886. ;; Make sure that found property block is not located
  14887. ;; before current point, as it would generate an infloop.
  14888. ;; It can happen, for example, in the following
  14889. ;; situation:
  14890. ;;
  14891. ;; * Headline
  14892. ;; :PROPERTIES:
  14893. ;; ...
  14894. ;; :END:
  14895. ;; *************** Inlinetask
  14896. ;; #+BEGIN_EXAMPLE
  14897. ;; :PROPERTIES:
  14898. ;; #+END_EXAMPLE
  14899. ;;
  14900. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14901. (while (< (point) end)
  14902. (let ((p (progn (looking-at org-property-re)
  14903. (match-string-no-properties 2))))
  14904. ;; Only add true property name, not extension symbol.
  14905. (push (if (not (org-string-match-p "\\+\\'" p)) p
  14906. (substring p 0 -1))
  14907. props))
  14908. (forward-line))))
  14909. (outline-next-heading)))
  14910. (when columns
  14911. (goto-char (point-min))
  14912. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14913. (let ((element (org-element-at-point)))
  14914. (when (memq (org-element-type element) '(keyword node-property))
  14915. (let ((value (org-element-property :value element))
  14916. (start 0))
  14917. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14918. (setq start (match-end 0))
  14919. (let ((p (match-string-no-properties 1 value)))
  14920. (unless (member-ignore-case p org-special-properties)
  14921. (push p props))))))))))
  14922. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14923. (defun org-property-values (key)
  14924. "List all non-nil values of property KEY in current buffer."
  14925. (org-with-wide-buffer
  14926. (goto-char (point-min))
  14927. (let ((case-fold-search t)
  14928. (re (org-re-property key))
  14929. values)
  14930. (while (re-search-forward re nil t)
  14931. (push (org-entry-get (point) key) values))
  14932. (delete-dups values))))
  14933. (defun org-insert-property-drawer ()
  14934. "Insert a property drawer into the current entry."
  14935. (org-with-wide-buffer
  14936. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14937. (org-back-to-heading t)
  14938. (org-with-limited-levels (org-back-to-heading t)))
  14939. (forward-line)
  14940. (when (looking-at-p org-planning-line-re) (forward-line))
  14941. (unless (looking-at-p org-property-drawer-re)
  14942. ;; Make sure we start editing a line from current entry, not from
  14943. ;; next one. It prevents extending text properties or overlays
  14944. ;; belonging to the latter.
  14945. (when (bolp) (backward-char))
  14946. (let ((begin (1+ (point)))
  14947. (inhibit-read-only t))
  14948. (insert "\n:PROPERTIES:\n:END:")
  14949. (when (eobp) (insert "\n"))
  14950. (org-indent-region begin (point))))))
  14951. (defun org-insert-drawer (&optional arg drawer)
  14952. "Insert a drawer at point.
  14953. When optional argument ARG is non-nil, insert a property drawer.
  14954. Optional argument DRAWER, when non-nil, is a string representing
  14955. drawer's name. Otherwise, the user is prompted for a name.
  14956. If a region is active, insert the drawer around that region
  14957. instead.
  14958. Point is left between drawer's boundaries."
  14959. (interactive "P")
  14960. (let* ((drawer (if arg "PROPERTIES"
  14961. (or drawer (read-from-minibuffer "Drawer: ")))))
  14962. (cond
  14963. ;; With C-u, fall back on `org-insert-property-drawer'
  14964. (arg (org-insert-property-drawer))
  14965. ;; Check validity of suggested drawer's name.
  14966. ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14967. (user-error "Invalid drawer name"))
  14968. ;; With an active region, insert a drawer at point.
  14969. ((not (org-region-active-p))
  14970. (progn
  14971. (unless (bolp) (insert "\n"))
  14972. (insert (format ":%s:\n\n:END:\n" drawer))
  14973. (forward-line -2)))
  14974. ;; Otherwise, insert the drawer at point
  14975. (t
  14976. (let ((rbeg (region-beginning))
  14977. (rend (copy-marker (region-end))))
  14978. (unwind-protect
  14979. (progn
  14980. (goto-char rbeg)
  14981. (beginning-of-line)
  14982. (when (save-excursion
  14983. (re-search-forward org-outline-regexp-bol rend t))
  14984. (user-error "Drawers cannot contain headlines"))
  14985. ;; Position point at the beginning of the first
  14986. ;; non-blank line in region. Insert drawer's opening
  14987. ;; there, then indent it.
  14988. (org-skip-whitespace)
  14989. (beginning-of-line)
  14990. (insert ":" drawer ":\n")
  14991. (forward-line -1)
  14992. (indent-for-tab-command)
  14993. ;; Move point to the beginning of the first blank line
  14994. ;; after the last non-blank line in region. Insert
  14995. ;; drawer's closing, then indent it.
  14996. (goto-char rend)
  14997. (skip-chars-backward " \r\t\n")
  14998. (insert "\n:END:")
  14999. (deactivate-mark t)
  15000. (indent-for-tab-command)
  15001. (unless (eolp) (insert "\n")))
  15002. ;; Clear marker, whatever the outcome of insertion is.
  15003. (set-marker rend nil)))))))
  15004. (defvar org-property-set-functions-alist nil
  15005. "Property set function alist.
  15006. Each entry should have the following format:
  15007. (PROPERTY . READ-FUNCTION)
  15008. The read function will be called with the same argument as
  15009. `org-completing-read'.")
  15010. (defun org-set-property-function (property)
  15011. "Get the function that should be used to set PROPERTY.
  15012. This is computed according to `org-property-set-functions-alist'."
  15013. (or (cdr (assoc property org-property-set-functions-alist))
  15014. 'org-completing-read))
  15015. (defun org-read-property-value (property)
  15016. "Read PROPERTY value from user."
  15017. (let* ((completion-ignore-case t)
  15018. (allowed (org-property-get-allowed-values nil property 'table))
  15019. (cur (org-entry-get nil property))
  15020. (prompt (concat property " value"
  15021. (if (and cur (string-match "\\S-" cur))
  15022. (concat " [" cur "]") "") ": "))
  15023. (set-function (org-set-property-function property))
  15024. (val (if allowed
  15025. (funcall set-function prompt allowed nil
  15026. (not (get-text-property 0 'org-unrestricted
  15027. (caar allowed))))
  15028. (funcall set-function prompt
  15029. (mapcar 'list (org-property-values property))
  15030. nil nil "" nil cur))))
  15031. (org-trim val)))
  15032. (defvar org-last-set-property nil)
  15033. (defvar org-last-set-property-value nil)
  15034. (defun org-read-property-name ()
  15035. "Read a property name."
  15036. (let ((completion-ignore-case t)
  15037. (default-prop (or (and (org-at-property-p)
  15038. (match-string-no-properties 2))
  15039. org-last-set-property)))
  15040. (org-completing-read
  15041. (concat "Property"
  15042. (if default-prop (concat " [" default-prop "]") "")
  15043. ": ")
  15044. (mapcar #'list (org-buffer-property-keys nil t t))
  15045. nil nil nil nil default-prop)))
  15046. (defun org-set-property-and-value (use-last)
  15047. "Allow to set [PROPERTY]: [value] direction from prompt.
  15048. When use-default, don't even ask, just use the last
  15049. \"[PROPERTY]: [value]\" string from the history."
  15050. (interactive "P")
  15051. (let* ((completion-ignore-case t)
  15052. (pv (or (and use-last org-last-set-property-value)
  15053. (org-completing-read
  15054. "Enter a \"[Property]: [value]\" pair: "
  15055. nil nil nil nil nil
  15056. org-last-set-property-value)))
  15057. prop val)
  15058. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  15059. (setq prop (match-string 1 pv)
  15060. val (match-string 2 pv))
  15061. (org-set-property prop val))))
  15062. (defun org-set-property (property value)
  15063. "In the current entry, set PROPERTY to VALUE.
  15064. When called interactively, this will prompt for a property name, offering
  15065. completion on existing and default properties. And then it will prompt
  15066. for a value, offering completion either on allowed values (via an inherited
  15067. xxx_ALL property) or on existing values in other instances of this property
  15068. in the current file.
  15069. Throw an error when trying to set a property with an invalid name."
  15070. (interactive (list nil nil))
  15071. (let ((property (or property (org-read-property-name))))
  15072. ;; `org-entry-put' also makes the following check, but this one
  15073. ;; avoids polluting `org-last-set-property' and
  15074. ;; `org-last-set-property-value' needlessly.
  15075. (unless (org--valid-property-p property)
  15076. (user-error "Invalid property name: \"%s\"" property))
  15077. (let ((value (or value (org-read-property-value property)))
  15078. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15079. (setq org-last-set-property property)
  15080. (setq org-last-set-property-value (concat property ": " value))
  15081. ;; Possibly postprocess the inserted value:
  15082. (when fn (setq value (funcall fn value)))
  15083. (unless (equal (org-entry-get nil property) value)
  15084. (org-entry-put nil property value)))))
  15085. (defun org-find-property (property &optional value)
  15086. "Find first entry in buffer that sets PROPERTY.
  15087. When optional argument VALUE is non-nil, only consider an entry
  15088. if it contains PROPERTY set to this value. If PROPERTY should be
  15089. explicitly set to nil, use string \"nil\" for VALUE.
  15090. Return position where the entry begins, or nil if there is no
  15091. such entry. If narrowing is in effect, only search the visible
  15092. part of the buffer."
  15093. (save-excursion
  15094. (goto-char (point-min))
  15095. (let ((case-fold-search t)
  15096. (re (org-re-property property nil (not value) value)))
  15097. (catch 'exit
  15098. (while (re-search-forward re nil t)
  15099. (when (if value (org-at-property-p)
  15100. (org-entry-get (point) property nil t))
  15101. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15102. (defun org-delete-property (property)
  15103. "In the current entry, delete PROPERTY."
  15104. (interactive
  15105. (let* ((completion-ignore-case t)
  15106. (cat (org-entry-get (point) "CATEGORY"))
  15107. (props0 (org-entry-properties nil 'standard))
  15108. (props (if cat props0
  15109. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15110. (prop (if (< 1 (length props))
  15111. (completing-read "Property: " props nil t)
  15112. (caar props))))
  15113. (list prop)))
  15114. (if (not property)
  15115. (message "No property to delete in this entry")
  15116. (org-entry-delete nil property)
  15117. (message "Property \"%s\" deleted" property)))
  15118. (defun org-delete-property-globally (property)
  15119. "Remove PROPERTY globally, from all entries.
  15120. This function ignores narrowing, if any."
  15121. (interactive
  15122. (let* ((completion-ignore-case t)
  15123. (prop (completing-read
  15124. "Globally remove property: "
  15125. (mapcar #'list (org-buffer-property-keys)))))
  15126. (list prop)))
  15127. (org-with-wide-buffer
  15128. (goto-char (point-min))
  15129. (let ((count 0)
  15130. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15131. (while (re-search-forward re nil t)
  15132. (when (org-entry-delete (point) property) (cl-incf count)))
  15133. (message "Property \"%s\" removed from %d entries" property count))))
  15134. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15135. (defun org-compute-property-at-point ()
  15136. "Compute the property at point.
  15137. This looks for an enclosing column format, extracts the operator and
  15138. then applies it to the property in the column format's scope."
  15139. (interactive)
  15140. (unless (org-at-property-p)
  15141. (user-error "Not at a property"))
  15142. (let ((prop (match-string-no-properties 2)))
  15143. (org-columns-get-format-and-top-level)
  15144. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15145. (user-error "No operator defined for property %s" prop))
  15146. (org-columns-compute prop)))
  15147. (defvar org-property-allowed-value-functions nil
  15148. "Hook for functions supplying allowed values for a specific property.
  15149. The functions must take a single argument, the name of the property, and
  15150. return a flat list of allowed values. If \":ETC\" is one of
  15151. the values, this means that these values are intended as defaults for
  15152. completion, but that other values should be allowed too.
  15153. The functions must return nil if they are not responsible for this
  15154. property.")
  15155. (defun org-property-get-allowed-values (pom property &optional table)
  15156. "Get allowed values for the property PROPERTY.
  15157. When TABLE is non-nil, return an alist that can directly be used for
  15158. completion."
  15159. (let (vals)
  15160. (cond
  15161. ((equal property "TODO")
  15162. (setq vals (org-with-point-at pom
  15163. (append org-todo-keywords-1 '("")))))
  15164. ((equal property "PRIORITY")
  15165. (let ((n org-lowest-priority))
  15166. (while (>= n org-highest-priority)
  15167. (push (char-to-string n) vals)
  15168. (setq n (1- n)))))
  15169. ((equal property "CATEGORY"))
  15170. ((member property org-special-properties))
  15171. ((setq vals (run-hook-with-args-until-success
  15172. 'org-property-allowed-value-functions property)))
  15173. (t
  15174. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15175. (when (and vals (string-match "\\S-" vals))
  15176. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15177. (setq vals (mapcar (lambda (x)
  15178. (cond ((stringp x) x)
  15179. ((numberp x) (number-to-string x))
  15180. ((symbolp x) (symbol-name x))
  15181. (t "???")))
  15182. vals)))))
  15183. (when (member ":ETC" vals)
  15184. (setq vals (remove ":ETC" vals))
  15185. (org-add-props (car vals) '(org-unrestricted t)))
  15186. (if table (mapcar 'list vals) vals)))
  15187. (defun org-property-previous-allowed-value (&optional _previous)
  15188. "Switch to the next allowed value for this property."
  15189. (interactive)
  15190. (org-property-next-allowed-value t))
  15191. (defun org-property-next-allowed-value (&optional previous)
  15192. "Switch to the next allowed value for this property."
  15193. (interactive)
  15194. (unless (org-at-property-p)
  15195. (user-error "Not at a property"))
  15196. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15197. (key (match-string 2))
  15198. (value (match-string 3))
  15199. (allowed (or (org-property-get-allowed-values (point) key)
  15200. (and (member value '("[ ]" "[-]" "[X]"))
  15201. '("[ ]" "[X]"))))
  15202. (heading (save-match-data (nth 4 (org-heading-components))))
  15203. nval)
  15204. (unless allowed
  15205. (user-error "Allowed values for this property have not been defined"))
  15206. (when previous (setq allowed (reverse allowed)))
  15207. (when (member value allowed)
  15208. (setq nval (car (cdr (member value allowed)))))
  15209. (setq nval (or nval (car allowed)))
  15210. (when (equal nval value)
  15211. (user-error "Only one allowed value for this property"))
  15212. (org-at-property-p)
  15213. (replace-match (concat " :" key ": " nval) t t)
  15214. (org-indent-line)
  15215. (beginning-of-line 1)
  15216. (skip-chars-forward " \t")
  15217. (when (equal prop org-effort-property)
  15218. (org-refresh-property
  15219. '((effort . identity)
  15220. (effort-minutes . org-duration-string-to-minutes))
  15221. nval)
  15222. (when (string= org-clock-current-task heading)
  15223. (setq org-clock-effort nval)
  15224. (org-clock-update-mode-line)))
  15225. (run-hook-with-args 'org-property-changed-functions key nval)))
  15226. (defun org-find-olp (path &optional this-buffer)
  15227. "Return a marker pointing to the entry at outline path OLP.
  15228. If anything goes wrong, throw an error.
  15229. You can wrap this call to catch the error like this:
  15230. \(condition-case msg
  15231. \(org-mobile-locate-entry (match-string 4))
  15232. \(error (nth 1 msg)))
  15233. The return value will then be either a string with the error message,
  15234. or a marker if everything is OK.
  15235. If THIS-BUFFER is set, the outline path does not contain a file,
  15236. only headings."
  15237. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15238. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15239. (level 1)
  15240. (lmin 1)
  15241. (lmax 1)
  15242. end found flevel)
  15243. (unless buffer (error "File not found :%s" file))
  15244. (with-current-buffer buffer
  15245. (org-with-wide-buffer
  15246. (goto-char (point-min))
  15247. (dolist (heading path)
  15248. (let ((re (format org-complex-heading-regexp-format
  15249. (regexp-quote heading)))
  15250. (cnt 0))
  15251. (while (re-search-forward re end t)
  15252. (setq level (- (match-end 1) (match-beginning 1)))
  15253. (when (and (>= level lmin) (<= level lmax))
  15254. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15255. (when (= cnt 0)
  15256. (error "Heading not found on level %d: %s" lmax heading))
  15257. (when (> cnt 1)
  15258. (error "Heading not unique on level %d: %s" lmax heading))
  15259. (goto-char found)
  15260. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15261. (setq end (save-excursion (org-end-of-subtree t t)))))
  15262. (when (org-at-heading-p)
  15263. (point-marker))))))
  15264. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15265. "Find node HEADING in BUFFER.
  15266. Return a marker to the heading if it was found, or nil if not.
  15267. If POS-ONLY is set, return just the position instead of a marker.
  15268. The heading text must match exact, but it may have a TODO keyword,
  15269. a priority cookie and tags in the standard locations."
  15270. (with-current-buffer (or buffer (current-buffer))
  15271. (save-excursion
  15272. (save-restriction
  15273. (widen)
  15274. (goto-char (point-min))
  15275. (let (case-fold-search)
  15276. (when (re-search-forward
  15277. (format org-complex-heading-regexp-format
  15278. (regexp-quote heading)) nil t)
  15279. (if pos-only
  15280. (match-beginning 0)
  15281. (move-marker (make-marker) (match-beginning 0)))))))))
  15282. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15283. "Find Org node headline HEADING in all .org files in directory DIR.
  15284. When the target headline is found, return a marker to this location."
  15285. (let ((files (directory-files (or dir default-directory)
  15286. t "\\`[^.#].*\\.org\\'"))
  15287. visiting m buffer)
  15288. (catch 'found
  15289. (dolist (file files)
  15290. (message "trying %s" file)
  15291. (setq visiting (org-find-base-buffer-visiting file))
  15292. (setq buffer (or visiting (find-file-noselect file)))
  15293. (setq m (org-find-exact-headline-in-buffer
  15294. heading buffer))
  15295. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15296. (and m (throw 'found m))))))
  15297. (defun org-find-entry-with-id (ident)
  15298. "Locate the entry that contains the ID property with exact value IDENT.
  15299. IDENT can be a string, a symbol or a number, this function will search for
  15300. the string representation of it.
  15301. Return the position where this entry starts, or nil if there is no such entry."
  15302. (interactive "sID: ")
  15303. (let ((id (cond
  15304. ((stringp ident) ident)
  15305. ((symbolp ident) (symbol-name ident))
  15306. ((numberp ident) (number-to-string ident))
  15307. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15308. (org-with-wide-buffer (org-find-property "ID" id))))
  15309. ;;;; Timestamps
  15310. (defvar org-last-changed-timestamp nil)
  15311. (defvar org-last-inserted-timestamp nil
  15312. "The last time stamp inserted with `org-insert-time-stamp'.")
  15313. (defvar org-ts-what) ; dynamically scoped parameter
  15314. (defun org-time-stamp (arg &optional inactive)
  15315. "Prompt for a date/time and insert a time stamp.
  15316. If the user specifies a time like HH:MM or if this command is
  15317. called with at least one prefix argument, the time stamp contains
  15318. the date and the time. Otherwise, only the date is included.
  15319. All parts of a date not specified by the user are filled in from
  15320. the timestamp at point, if any, or the current date/time
  15321. otherwise.
  15322. If there is already a timestamp at the cursor, it is replaced.
  15323. With two universal prefix arguments, insert an active timestamp
  15324. with the current time without prompting the user.
  15325. When called from lisp, the timestamp is inactive if INACTIVE is
  15326. non-nil."
  15327. (interactive "P")
  15328. (let* ((ts (cond
  15329. ((org-at-date-range-p t)
  15330. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15331. ((org-at-timestamp-p t) (match-string 0))))
  15332. ;; Default time is either the timestamp at point or today.
  15333. ;; When entering a range, only the range start is considered.
  15334. (default-time (if (not ts) (current-time)
  15335. (apply #'encode-time (org-parse-time-string ts))))
  15336. (default-input (and ts (org-get-compact-tod ts)))
  15337. (repeater (and ts
  15338. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15339. (match-string 0 ts)))
  15340. org-time-was-given
  15341. org-end-time-was-given
  15342. (time
  15343. (and (if (equal arg '(16)) (current-time)
  15344. ;; Preserve `this-command' and `last-command'.
  15345. (let ((this-command this-command)
  15346. (last-command last-command))
  15347. (org-read-date
  15348. arg 'totime nil nil default-time default-input
  15349. inactive))))))
  15350. (cond
  15351. ((and ts
  15352. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15353. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15354. (insert "--")
  15355. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15356. (ts
  15357. ;; Make sure we're on a timestamp. When in the middle of a date
  15358. ;; range, move arbitrarily to range end.
  15359. (unless (org-at-timestamp-p t)
  15360. (skip-chars-forward "-")
  15361. (org-at-timestamp-p t))
  15362. (replace-match "")
  15363. (setq org-last-changed-timestamp
  15364. (org-insert-time-stamp
  15365. time (or org-time-was-given arg)
  15366. inactive nil nil (list org-end-time-was-given)))
  15367. (when repeater
  15368. (backward-char)
  15369. (insert " " repeater)
  15370. (setq org-last-changed-timestamp
  15371. (concat (substring org-last-inserted-timestamp 0 -1)
  15372. " " repeater ">")))
  15373. (message "Timestamp updated"))
  15374. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15375. (t (org-insert-time-stamp
  15376. time (or org-time-was-given arg) inactive nil nil
  15377. (list org-end-time-was-given))))))
  15378. ;; FIXME: can we use this for something else, like computing time differences?
  15379. (defun org-get-compact-tod (s)
  15380. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15381. (let* ((t1 (match-string 1 s))
  15382. (h1 (string-to-number (match-string 2 s)))
  15383. (m1 (string-to-number (match-string 3 s)))
  15384. (t2 (and (match-end 4) (match-string 5 s)))
  15385. (h2 (and t2 (string-to-number (match-string 6 s))))
  15386. (m2 (and t2 (string-to-number (match-string 7 s))))
  15387. dh dm)
  15388. (if (not t2)
  15389. t1
  15390. (setq dh (- h2 h1) dm (- m2 m1))
  15391. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15392. (concat t1 "+" (number-to-string dh)
  15393. (and (/= 0 dm) (format ":%02d" dm)))))))
  15394. (defun org-time-stamp-inactive (&optional arg)
  15395. "Insert an inactive time stamp.
  15396. An inactive time stamp is enclosed in square brackets instead of angle
  15397. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15398. does not link to the calendar and cannot be changed with the S-cursor keys.
  15399. So these are more for recording a certain time/date."
  15400. (interactive "P")
  15401. (org-time-stamp arg 'inactive))
  15402. (defvar org-date-ovl (make-overlay 1 1))
  15403. (overlay-put org-date-ovl 'face 'org-date-selected)
  15404. (delete-overlay org-date-ovl)
  15405. (defvar org-ans1) ; dynamically scoped parameter
  15406. (defvar org-ans2) ; dynamically scoped parameter
  15407. (defvar org-plain-time-of-day-regexp) ; defined below
  15408. (defvar org-overriding-default-time nil) ; dynamically scoped
  15409. (defvar org-read-date-overlay nil)
  15410. (defvar org-dcst nil) ; dynamically scoped
  15411. (defvar org-read-date-history nil)
  15412. (defvar org-read-date-final-answer nil)
  15413. (defvar org-read-date-analyze-futurep nil)
  15414. (defvar org-read-date-analyze-forced-year nil)
  15415. (defvar org-read-date-inactive)
  15416. (defvar org-read-date-minibuffer-local-map
  15417. (let* ((map (make-sparse-keymap)))
  15418. (set-keymap-parent map minibuffer-local-map)
  15419. (org-defkey map (kbd ".")
  15420. (lambda () (interactive)
  15421. ;; Are we at the beginning of the prompt?
  15422. (if (looking-back "^[^:]+: "
  15423. (let ((inhibit-field-text-motion t))
  15424. (line-beginning-position)))
  15425. (org-eval-in-calendar '(calendar-goto-today))
  15426. (insert "."))))
  15427. (org-defkey map (kbd "C-.")
  15428. (lambda () (interactive)
  15429. (org-eval-in-calendar '(calendar-goto-today))))
  15430. (org-defkey map [(meta shift left)]
  15431. (lambda () (interactive)
  15432. (org-eval-in-calendar '(calendar-backward-month 1))))
  15433. (org-defkey map [(meta shift right)]
  15434. (lambda () (interactive)
  15435. (org-eval-in-calendar '(calendar-forward-month 1))))
  15436. (org-defkey map [(meta shift up)]
  15437. (lambda () (interactive)
  15438. (org-eval-in-calendar '(calendar-backward-year 1))))
  15439. (org-defkey map [(meta shift down)]
  15440. (lambda () (interactive)
  15441. (org-eval-in-calendar '(calendar-forward-year 1))))
  15442. (org-defkey map [?\e (shift left)]
  15443. (lambda () (interactive)
  15444. (org-eval-in-calendar '(calendar-backward-month 1))))
  15445. (org-defkey map [?\e (shift right)]
  15446. (lambda () (interactive)
  15447. (org-eval-in-calendar '(calendar-forward-month 1))))
  15448. (org-defkey map [?\e (shift up)]
  15449. (lambda () (interactive)
  15450. (org-eval-in-calendar '(calendar-backward-year 1))))
  15451. (org-defkey map [?\e (shift down)]
  15452. (lambda () (interactive)
  15453. (org-eval-in-calendar '(calendar-forward-year 1))))
  15454. (org-defkey map [(shift up)]
  15455. (lambda () (interactive)
  15456. (org-eval-in-calendar '(calendar-backward-week 1))))
  15457. (org-defkey map [(shift down)]
  15458. (lambda () (interactive)
  15459. (org-eval-in-calendar '(calendar-forward-week 1))))
  15460. (org-defkey map [(shift left)]
  15461. (lambda () (interactive)
  15462. (org-eval-in-calendar '(calendar-backward-day 1))))
  15463. (org-defkey map [(shift right)]
  15464. (lambda () (interactive)
  15465. (org-eval-in-calendar '(calendar-forward-day 1))))
  15466. (org-defkey map "!"
  15467. (lambda () (interactive)
  15468. (org-eval-in-calendar '(diary-view-entries))
  15469. (message "")))
  15470. (org-defkey map ">"
  15471. (lambda () (interactive)
  15472. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15473. (org-defkey map "<"
  15474. (lambda () (interactive)
  15475. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15476. (org-defkey map "\C-v"
  15477. (lambda () (interactive)
  15478. (org-eval-in-calendar
  15479. '(calendar-scroll-left-three-months 1))))
  15480. (org-defkey map "\M-v"
  15481. (lambda () (interactive)
  15482. (org-eval-in-calendar
  15483. '(calendar-scroll-right-three-months 1))))
  15484. map)
  15485. "Keymap for minibuffer commands when using `org-read-date'.")
  15486. (defvar org-def)
  15487. (defvar org-defdecode)
  15488. (defvar org-with-time)
  15489. (defvar calendar-setup) ; Dynamically scoped.
  15490. (defun org-read-date (&optional with-time to-time from-string prompt
  15491. default-time default-input inactive)
  15492. "Read a date, possibly a time, and make things smooth for the user.
  15493. The prompt will suggest to enter an ISO date, but you can also enter anything
  15494. which will at least partially be understood by `parse-time-string'.
  15495. Unrecognized parts of the date will default to the current day, month, year,
  15496. hour and minute. If this command is called to replace a timestamp at point,
  15497. or to enter the second timestamp of a range, the default time is taken
  15498. from the existing stamp. Furthermore, the command prefers the future,
  15499. so if you are giving a date where the year is not given, and the day-month
  15500. combination is already past in the current year, it will assume you
  15501. mean next year. For details, see the manual. A few examples:
  15502. 3-2-5 --> 2003-02-05
  15503. feb 15 --> currentyear-02-15
  15504. 2/15 --> currentyear-02-15
  15505. sep 12 9 --> 2009-09-12
  15506. 12:45 --> today 12:45
  15507. 22 sept 0:34 --> currentyear-09-22 0:34
  15508. 12 --> currentyear-currentmonth-12
  15509. Fri --> nearest Friday after today
  15510. -Tue --> last Tuesday
  15511. etc.
  15512. Furthermore you can specify a relative date by giving, as the *first* thing
  15513. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15514. change in days weeks, months, years.
  15515. With a single plus or minus, the date is relative to today. With a double
  15516. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15517. +4d --> four days from today
  15518. +4 --> same as above
  15519. +2w --> two weeks from today
  15520. ++5 --> five days from default date
  15521. The function understands only English month and weekday abbreviations.
  15522. While prompting, a calendar is popped up - you can also select the
  15523. date with the mouse (button 1). The calendar shows a period of three
  15524. months. To scroll it to other months, use the keys `>' and `<'.
  15525. If you don't like the calendar, turn it off with
  15526. (setq org-read-date-popup-calendar nil)
  15527. With optional argument TO-TIME, the date will immediately be converted
  15528. to an internal time.
  15529. With an optional argument WITH-TIME, the prompt will suggest to
  15530. also insert a time. Note that when WITH-TIME is not set, you can
  15531. still enter a time, and this function will inform the calling routine
  15532. about this change. The calling routine may then choose to change the
  15533. format used to insert the time stamp into the buffer to include the time.
  15534. With optional argument FROM-STRING, read from this string instead from
  15535. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15536. the time/date that is used for everything that is not specified by the
  15537. user."
  15538. (require 'parse-time)
  15539. (let* ((org-with-time with-time)
  15540. (org-time-stamp-rounding-minutes
  15541. (if (equal org-with-time '(16))
  15542. '(0 0)
  15543. org-time-stamp-rounding-minutes))
  15544. (org-dcst org-display-custom-times)
  15545. (ct (org-current-time))
  15546. (org-def (or org-overriding-default-time default-time ct))
  15547. (org-defdecode (decode-time org-def))
  15548. (cur-frame (selected-frame))
  15549. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15550. (calendar-setup
  15551. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15552. (calendar-move-hook nil)
  15553. (calendar-view-diary-initially-flag nil)
  15554. (calendar-view-holidays-initially-flag nil)
  15555. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15556. ;; Rationalize `org-def' and `org-defdecode', if required.
  15557. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15558. (setf (nth 2 org-defdecode) -1)
  15559. (setf (nth 1 org-defdecode) 59)
  15560. (setq org-def (apply #'encode-time org-defdecode))
  15561. (setq org-defdecode (decode-time org-def)))
  15562. (let* ((timestr (format-time-string
  15563. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15564. org-def))
  15565. (prompt (concat (if prompt (concat prompt " ") "")
  15566. (format "Date+time [%s]: " timestr))))
  15567. (cond
  15568. (from-string (setq ans from-string))
  15569. (org-read-date-popup-calendar
  15570. (save-excursion
  15571. (save-window-excursion
  15572. (calendar)
  15573. (when (eq calendar-setup 'calendar-only)
  15574. (setq cal-frame
  15575. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15576. (select-frame cal-frame))
  15577. (org-eval-in-calendar '(setq cursor-type nil) t)
  15578. (unwind-protect
  15579. (progn
  15580. (calendar-forward-day (- (time-to-days org-def)
  15581. (calendar-absolute-from-gregorian
  15582. (calendar-current-date))))
  15583. (org-eval-in-calendar nil t)
  15584. (let* ((old-map (current-local-map))
  15585. (map (copy-keymap calendar-mode-map))
  15586. (minibuffer-local-map
  15587. (copy-keymap org-read-date-minibuffer-local-map)))
  15588. (org-defkey map (kbd "RET") 'org-calendar-select)
  15589. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15590. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15591. (unwind-protect
  15592. (progn
  15593. (use-local-map map)
  15594. (setq org-read-date-inactive inactive)
  15595. (add-hook 'post-command-hook 'org-read-date-display)
  15596. (setq org-ans0
  15597. (read-string prompt
  15598. default-input
  15599. 'org-read-date-history
  15600. nil))
  15601. ;; org-ans0: from prompt
  15602. ;; org-ans1: from mouse click
  15603. ;; org-ans2: from calendar motion
  15604. (setq ans
  15605. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15606. (remove-hook 'post-command-hook 'org-read-date-display)
  15607. (use-local-map old-map)
  15608. (when org-read-date-overlay
  15609. (delete-overlay org-read-date-overlay)
  15610. (setq org-read-date-overlay nil)))))
  15611. (bury-buffer "*Calendar*")
  15612. (when cal-frame
  15613. (delete-frame cal-frame)
  15614. (select-frame-set-input-focus cur-frame))))))
  15615. (t ; Naked prompt only
  15616. (unwind-protect
  15617. (setq ans (read-string prompt default-input
  15618. 'org-read-date-history timestr))
  15619. (when org-read-date-overlay
  15620. (delete-overlay org-read-date-overlay)
  15621. (setq org-read-date-overlay nil))))))
  15622. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15623. (when org-read-date-analyze-forced-year
  15624. (message "Year was forced into %s"
  15625. (if org-read-date-force-compatible-dates
  15626. "compatible range (1970-2037)"
  15627. "range representable on this machine"))
  15628. (ding))
  15629. ;; One round trip to get rid of 34th of August and stuff like that....
  15630. (setq final (decode-time (apply 'encode-time final)))
  15631. (setq org-read-date-final-answer ans)
  15632. (if to-time
  15633. (apply 'encode-time final)
  15634. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15635. (format "%04d-%02d-%02d %02d:%02d"
  15636. (nth 5 final) (nth 4 final) (nth 3 final)
  15637. (nth 2 final) (nth 1 final))
  15638. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15639. (defun org-read-date-display ()
  15640. "Display the current date prompt interpretation in the minibuffer."
  15641. (when org-read-date-display-live
  15642. (when org-read-date-overlay
  15643. (delete-overlay org-read-date-overlay))
  15644. (when (minibufferp (current-buffer))
  15645. (save-excursion
  15646. (end-of-line 1)
  15647. (while (not (equal (buffer-substring
  15648. (max (point-min) (- (point) 4)) (point))
  15649. " "))
  15650. (insert " ")))
  15651. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15652. " " (or org-ans1 org-ans2)))
  15653. (org-end-time-was-given nil)
  15654. (f (org-read-date-analyze ans org-def org-defdecode))
  15655. (fmts (if org-dcst
  15656. org-time-stamp-custom-formats
  15657. org-time-stamp-formats))
  15658. (fmt (if (or org-with-time
  15659. (and (boundp 'org-time-was-given) org-time-was-given))
  15660. (cdr fmts)
  15661. (car fmts)))
  15662. (txt (format-time-string fmt (apply 'encode-time f)))
  15663. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15664. (txt (concat "=> " txt)))
  15665. (when (and org-end-time-was-given
  15666. (string-match org-plain-time-of-day-regexp txt))
  15667. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15668. org-end-time-was-given
  15669. (substring txt (match-end 0)))))
  15670. (when org-read-date-analyze-futurep
  15671. (setq txt (concat txt " (=>F)")))
  15672. (setq org-read-date-overlay
  15673. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15674. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15675. (defun org-read-date-analyze (ans def defdecode)
  15676. "Analyze the combined answer of the date prompt."
  15677. ;; FIXME: cleanup and comment
  15678. ;; Pass `current-time' result to `decode-time' (instead of calling
  15679. ;; without arguments) so that only `current-time' has to be
  15680. ;; overriden in tests.
  15681. (let ((org-def def)
  15682. (org-defdecode defdecode)
  15683. (nowdecode (decode-time (current-time)))
  15684. delta deltan deltaw deltadef year month day
  15685. hour minute second wday pm h2 m2 tl wday1
  15686. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15687. (setq org-read-date-analyze-futurep nil
  15688. org-read-date-analyze-forced-year nil)
  15689. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15690. (setq ans "+0"))
  15691. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15692. (setq ans (replace-match "" t t ans)
  15693. deltan (car delta)
  15694. deltaw (nth 1 delta)
  15695. deltadef (nth 2 delta)))
  15696. ;; Check if there is an iso week date in there. If yes, store the
  15697. ;; info and postpone interpreting it until the rest of the parsing
  15698. ;; is done.
  15699. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15700. (setq iso-year (when (match-end 1)
  15701. (org-small-year-to-year
  15702. (string-to-number (match-string 1 ans))))
  15703. iso-weekday (when (match-end 3)
  15704. (string-to-number (match-string 3 ans)))
  15705. iso-week (string-to-number (match-string 2 ans)))
  15706. (setq ans (replace-match "" t t ans)))
  15707. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15708. (when (string-match
  15709. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15710. (setq year (if (match-end 2)
  15711. (string-to-number (match-string 2 ans))
  15712. (progn (setq kill-year t)
  15713. (string-to-number (format-time-string "%Y"))))
  15714. month (string-to-number (match-string 3 ans))
  15715. day (string-to-number (match-string 4 ans)))
  15716. (setq year (org-small-year-to-year year))
  15717. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15718. t nil ans)))
  15719. ;; Help matching dotted european dates
  15720. (when (string-match
  15721. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15722. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15723. (setq kill-year t)
  15724. (string-to-number (format-time-string "%Y")))
  15725. day (string-to-number (match-string 1 ans))
  15726. month (string-to-number (match-string 2 ans))
  15727. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15728. t nil ans)))
  15729. ;; Help matching american dates, like 5/30 or 5/30/7
  15730. (when (string-match
  15731. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15732. (setq year (if (match-end 4)
  15733. (string-to-number (match-string 4 ans))
  15734. (progn (setq kill-year t)
  15735. (string-to-number (format-time-string "%Y"))))
  15736. month (string-to-number (match-string 1 ans))
  15737. day (string-to-number (match-string 2 ans)))
  15738. (setq year (org-small-year-to-year year))
  15739. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15740. t nil ans)))
  15741. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15742. ;; If there is a time with am/pm, and *no* time without it, we convert
  15743. ;; so that matching will be successful.
  15744. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15745. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15746. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15747. (setq hour (string-to-number (match-string 1 ans))
  15748. minute (if (match-end 3)
  15749. (string-to-number (match-string 3 ans))
  15750. 0)
  15751. pm (equal ?p
  15752. (string-to-char (downcase (match-string 4 ans)))))
  15753. (if (and (= hour 12) (not pm))
  15754. (setq hour 0)
  15755. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15756. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15757. t t ans))))
  15758. ;; Check if a time range is given as a duration
  15759. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15760. (setq hour (string-to-number (match-string 1 ans))
  15761. h2 (+ hour (string-to-number (match-string 3 ans)))
  15762. minute (string-to-number (match-string 2 ans))
  15763. m2 (+ minute (if (match-end 5) (string-to-number
  15764. (match-string 5 ans))0)))
  15765. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15766. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15767. t t ans)))
  15768. ;; Check if there is a time range
  15769. (when (boundp 'org-end-time-was-given)
  15770. (setq org-time-was-given nil)
  15771. (when (and (string-match org-plain-time-of-day-regexp ans)
  15772. (match-end 8))
  15773. (setq org-end-time-was-given (match-string 8 ans))
  15774. (setq ans (concat (substring ans 0 (match-beginning 7))
  15775. (substring ans (match-end 7))))))
  15776. (setq tl (parse-time-string ans)
  15777. day (or (nth 3 tl) (nth 3 org-defdecode))
  15778. month
  15779. (cond ((nth 4 tl))
  15780. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15781. ;; Day was specified. Make sure DAY+MONTH
  15782. ;; combination happens in the future.
  15783. ((nth 3 tl)
  15784. (setq futurep t)
  15785. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15786. (nth 4 nowdecode)))
  15787. (t (nth 4 org-defdecode)))
  15788. year
  15789. (cond ((and (not kill-year) (nth 5 tl)))
  15790. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15791. ;; Month was guessed in the future and is at least
  15792. ;; equal to NOWDECODE's. Fix year accordingly.
  15793. (futurep
  15794. (if (or (> month (nth 4 nowdecode))
  15795. (>= day (nth 3 nowdecode)))
  15796. (nth 5 nowdecode)
  15797. (1+ (nth 5 nowdecode))))
  15798. ;; Month was specified. Make sure MONTH+YEAR
  15799. ;; combination happens in the future.
  15800. ((nth 4 tl)
  15801. (setq futurep t)
  15802. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15803. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15804. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15805. (t (nth 5 nowdecode))))
  15806. (t (nth 5 org-defdecode)))
  15807. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15808. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15809. second (or (nth 0 tl) 0)
  15810. wday (nth 6 tl))
  15811. (when (and (eq org-read-date-prefer-future 'time)
  15812. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15813. (equal day (nth 3 nowdecode))
  15814. (equal month (nth 4 nowdecode))
  15815. (equal year (nth 5 nowdecode))
  15816. (nth 2 tl)
  15817. (or (< (nth 2 tl) (nth 2 nowdecode))
  15818. (and (= (nth 2 tl) (nth 2 nowdecode))
  15819. (nth 1 tl)
  15820. (< (nth 1 tl) (nth 1 nowdecode)))))
  15821. (setq day (1+ day)
  15822. futurep t))
  15823. ;; Special date definitions below
  15824. (cond
  15825. (iso-week
  15826. ;; There was an iso week
  15827. (require 'cal-iso)
  15828. (setq futurep nil)
  15829. (setq year (or iso-year year)
  15830. day (or iso-weekday wday 1)
  15831. wday nil ; to make sure that the trigger below does not match
  15832. iso-date (calendar-gregorian-from-absolute
  15833. (calendar-iso-to-absolute
  15834. (list iso-week day year))))
  15835. ; FIXME: Should we also push ISO weeks into the future?
  15836. ; (when (and org-read-date-prefer-future
  15837. ; (not iso-year)
  15838. ; (< (calendar-absolute-from-gregorian iso-date)
  15839. ; (time-to-days (current-time))))
  15840. ; (setq year (1+ year)
  15841. ; iso-date (calendar-gregorian-from-absolute
  15842. ; (calendar-iso-to-absolute
  15843. ; (list iso-week day year)))))
  15844. (setq month (car iso-date)
  15845. year (nth 2 iso-date)
  15846. day (nth 1 iso-date)))
  15847. (deltan
  15848. (setq futurep nil)
  15849. (unless deltadef
  15850. ;; Pass `current-time' result to `decode-time' (instead of
  15851. ;; calling without arguments) so that only `current-time' has
  15852. ;; to be overriden in tests.
  15853. (let ((now (decode-time (current-time))))
  15854. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15855. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15856. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15857. ((equal deltaw "m") (setq month (+ month deltan)))
  15858. ((equal deltaw "y") (setq year (+ year deltan)))))
  15859. ((and wday (not (nth 3 tl)))
  15860. ;; Weekday was given, but no day, so pick that day in the week
  15861. ;; on or after the derived date.
  15862. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15863. (unless (equal wday wday1)
  15864. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15865. (when (and (boundp 'org-time-was-given)
  15866. (nth 2 tl))
  15867. (setq org-time-was-given t))
  15868. (when (< year 100) (setq year (+ 2000 year)))
  15869. ;; Check of the date is representable
  15870. (if org-read-date-force-compatible-dates
  15871. (progn
  15872. (when (< year 1970)
  15873. (setq year 1970 org-read-date-analyze-forced-year t))
  15874. (when (> year 2037)
  15875. (setq year 2037 org-read-date-analyze-forced-year t)))
  15876. (condition-case nil
  15877. (ignore (encode-time second minute hour day month year))
  15878. (error
  15879. (setq year (nth 5 org-defdecode))
  15880. (setq org-read-date-analyze-forced-year t))))
  15881. (setq org-read-date-analyze-futurep futurep)
  15882. (list second minute hour day month year)))
  15883. (defvar parse-time-weekdays)
  15884. (defun org-read-date-get-relative (s today default)
  15885. "Check string S for special relative date string.
  15886. TODAY and DEFAULT are internal times, for today and for a default.
  15887. Return shift list (N what def-flag)
  15888. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15889. N is the number of WHATs to shift.
  15890. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15891. the DEFAULT date rather than TODAY."
  15892. (require 'parse-time)
  15893. (when (and
  15894. (string-match
  15895. (concat
  15896. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15897. "\\([0-9]+\\)?"
  15898. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15899. "\\([ \t]\\|$\\)") s)
  15900. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15901. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15902. (string-to-char (substring (match-string 1 s) -1))
  15903. ?+))
  15904. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15905. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15906. (what (if (match-end 3) (match-string 3 s) "d"))
  15907. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15908. (date (if rel default today))
  15909. (wday (nth 6 (decode-time date)))
  15910. delta)
  15911. (if wday1
  15912. (progn
  15913. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15914. (when (= delta 0) (setq delta 7))
  15915. (when (= dir ?-)
  15916. (setq delta (- delta 7))
  15917. (when (= delta 0) (setq delta -7)))
  15918. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15919. (list delta "d" rel))
  15920. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15921. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15922. "Turn a user-specified date into the internal representation.
  15923. The internal representation needed by the calendar is (month day year).
  15924. This is a wrapper to handle the brain-dead convention in calendar that
  15925. user function argument order change dependent on argument order."
  15926. (pcase calendar-date-style
  15927. (`american (list arg1 arg2 arg3))
  15928. (`european (list arg2 arg1 arg3))
  15929. (`iso (list arg2 arg3 arg1))))
  15930. (defun org-eval-in-calendar (form &optional keepdate)
  15931. "Eval FORM in the calendar window and return to current window.
  15932. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15933. (let ((sf (selected-frame))
  15934. (sw (selected-window)))
  15935. (select-window (get-buffer-window "*Calendar*" t))
  15936. (eval form)
  15937. (when (and (not keepdate) (calendar-cursor-to-date))
  15938. (let* ((date (calendar-cursor-to-date))
  15939. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15940. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15941. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15942. (select-window sw)
  15943. (select-frame-set-input-focus sf)))
  15944. (defun org-calendar-select ()
  15945. "Return to `org-read-date' with the date currently selected.
  15946. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15947. (interactive)
  15948. (when (calendar-cursor-to-date)
  15949. (let* ((date (calendar-cursor-to-date))
  15950. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15951. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15952. (when (active-minibuffer-window) (exit-minibuffer))))
  15953. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15954. "Insert a date stamp for the date given by the internal TIME.
  15955. See `format-time-string' for the format of TIME.
  15956. WITH-HM means use the stamp format that includes the time of the day.
  15957. INACTIVE means use square brackets instead of angular ones, so that the
  15958. stamp will not contribute to the agenda.
  15959. PRE and POST are optional strings to be inserted before and after the
  15960. stamp.
  15961. The command returns the inserted time stamp."
  15962. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15963. stamp)
  15964. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15965. (insert-before-markers (or pre ""))
  15966. (when (listp extra)
  15967. (setq extra (car extra))
  15968. (if (and (stringp extra)
  15969. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15970. (setq extra (format "-%02d:%02d"
  15971. (string-to-number (match-string 1 extra))
  15972. (string-to-number (match-string 2 extra))))
  15973. (setq extra nil)))
  15974. (when extra
  15975. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15976. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15977. (insert-before-markers (or post ""))
  15978. (setq org-last-inserted-timestamp stamp)))
  15979. (defun org-toggle-time-stamp-overlays ()
  15980. "Toggle the use of custom time stamp formats."
  15981. (interactive)
  15982. (setq org-display-custom-times (not org-display-custom-times))
  15983. (unless org-display-custom-times
  15984. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15985. (while (setq p (next-single-property-change p 'display))
  15986. (when (and (get-text-property p 'display)
  15987. (eq (get-text-property p 'face) 'org-date))
  15988. (remove-text-properties
  15989. p (setq p (next-single-property-change p 'display))
  15990. '(display t))))
  15991. (set-buffer-modified-p bmp)))
  15992. (org-restart-font-lock)
  15993. (setq org-table-may-need-update t)
  15994. (if org-display-custom-times
  15995. (message "Time stamps are overlaid with custom format")
  15996. (message "Time stamp overlays removed")))
  15997. (defun org-display-custom-time (beg end)
  15998. "Overlay modified time stamp format over timestamp between BEG and END."
  15999. (let* ((ts (buffer-substring beg end))
  16000. t1 w1 with-hm tf time str w2 (off 0))
  16001. (save-match-data
  16002. (setq t1 (org-parse-time-string ts t))
  16003. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  16004. (setq off (- (match-end 0) (match-beginning 0)))))
  16005. (setq end (- end off))
  16006. (setq w1 (- end beg)
  16007. with-hm (and (nth 1 t1) (nth 2 t1))
  16008. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  16009. time (org-fix-decoded-time t1)
  16010. str (org-add-props
  16011. (format-time-string
  16012. (substring tf 1 -1) (apply 'encode-time time))
  16013. nil 'mouse-face 'highlight)
  16014. w2 (length str))
  16015. (unless (= w2 w1)
  16016. (add-text-properties (1+ beg) (+ 2 beg)
  16017. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  16018. (put-text-property beg end 'display str)))
  16019. (defun org-fix-decoded-time (time)
  16020. "Set 0 instead of nil for the first 6 elements of time.
  16021. Don't touch the rest."
  16022. (let ((n 0))
  16023. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  16024. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  16025. "Difference between TIMESTAMP-STRING and now in days.
  16026. If SECONDS is non-nil, return the difference in seconds."
  16027. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  16028. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  16029. (funcall fdiff (current-time)))))
  16030. (defun org-deadline-close-p (timestamp-string &optional ndays)
  16031. "Is the time in TIMESTAMP-STRING close to the current date?"
  16032. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  16033. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  16034. (not (org-entry-is-done-p))))
  16035. (defun org-get-wdays (ts &optional delay zero-delay)
  16036. "Get the deadline lead time appropriate for timestring TS.
  16037. When DELAY is non-nil, get the delay time for scheduled items
  16038. instead of the deadline lead time. When ZERO-DELAY is non-nil
  16039. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  16040. don't try to find the delay cookie in the scheduled timestamp."
  16041. (let ((tv (if delay org-scheduled-delay-days
  16042. org-deadline-warning-days)))
  16043. (cond
  16044. ((or (and delay (< tv 0))
  16045. (and delay zero-delay (<= tv 0))
  16046. (and (not delay) (<= tv 0)))
  16047. ;; Enforce this value no matter what
  16048. (- tv))
  16049. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  16050. ;; lead time is specified.
  16051. (floor (* (string-to-number (match-string 1 ts))
  16052. (cdr (assoc (match-string 2 ts)
  16053. '(("d" . 1) ("w" . 7)
  16054. ("m" . 30.4) ("y" . 365.25)
  16055. ("h" . 0.041667)))))))
  16056. ;; go for the default.
  16057. (t tv))))
  16058. (defun org-calendar-select-mouse (ev)
  16059. "Return to `org-read-date' with the date currently selected.
  16060. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  16061. (interactive "e")
  16062. (mouse-set-point ev)
  16063. (when (calendar-cursor-to-date)
  16064. (let* ((date (calendar-cursor-to-date))
  16065. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  16066. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  16067. (when (active-minibuffer-window) (exit-minibuffer))))
  16068. (defun org-check-deadlines (ndays)
  16069. "Check if there are any deadlines due or past due.
  16070. A deadline is considered due if it happens within `org-deadline-warning-days'
  16071. days from today's date. If the deadline appears in an entry marked DONE,
  16072. it is not shown. The prefix arg NDAYS can be used to test that many
  16073. days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
  16074. (interactive "P")
  16075. (let* ((org-warn-days
  16076. (cond
  16077. ((equal ndays '(4)) 100000)
  16078. (ndays (prefix-numeric-value ndays))
  16079. (t (abs org-deadline-warning-days))))
  16080. (case-fold-search nil)
  16081. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16082. (callback
  16083. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16084. (message "%d deadlines past-due or due within %d days"
  16085. (org-occur regexp nil callback)
  16086. org-warn-days)))
  16087. (defsubst org-re-timestamp (type)
  16088. "Return a regexp for timestamp TYPE.
  16089. Allowed values for TYPE are:
  16090. all: all timestamps
  16091. active: only active timestamps (<...>)
  16092. inactive: only inactive timestamps ([...])
  16093. scheduled: only scheduled timestamps
  16094. deadline: only deadline timestamps
  16095. closed: only closed time-stamps
  16096. When TYPE is nil, fall back on returning a regexp that matches
  16097. both scheduled and deadline timestamps."
  16098. (cl-case type
  16099. (all org-ts-regexp-both)
  16100. (active org-ts-regexp)
  16101. (inactive org-ts-regexp-inactive)
  16102. (scheduled org-scheduled-time-regexp)
  16103. (deadline org-deadline-time-regexp)
  16104. (closed org-closed-time-regexp)
  16105. (otherwise
  16106. (concat "\\<"
  16107. (regexp-opt (list org-deadline-string org-scheduled-string))
  16108. " *<\\([^>]+\\)>"))))
  16109. (defun org-check-before-date (d)
  16110. "Check if there are deadlines or scheduled entries before date D."
  16111. (interactive (list (org-read-date)))
  16112. (let* ((case-fold-search nil)
  16113. (regexp (org-re-timestamp org-ts-type))
  16114. (ts-type org-ts-type)
  16115. (callback
  16116. (lambda ()
  16117. (let ((match (match-string 1)))
  16118. (and (if (memq ts-type '(active inactive all))
  16119. (eq (org-element-type (save-excursion
  16120. (backward-char)
  16121. (org-element-context)))
  16122. 'timestamp)
  16123. (org-at-planning-p))
  16124. (time-less-p
  16125. (org-time-string-to-time match)
  16126. (org-time-string-to-time d)))))))
  16127. (message "%d entries before %s"
  16128. (org-occur regexp nil callback)
  16129. d)))
  16130. (defun org-check-after-date (d)
  16131. "Check if there are deadlines or scheduled entries after date D."
  16132. (interactive (list (org-read-date)))
  16133. (let* ((case-fold-search nil)
  16134. (regexp (org-re-timestamp org-ts-type))
  16135. (ts-type org-ts-type)
  16136. (callback
  16137. (lambda ()
  16138. (let ((match (match-string 1)))
  16139. (and (if (memq ts-type '(active inactive all))
  16140. (eq (org-element-type (save-excursion
  16141. (backward-char)
  16142. (org-element-context)))
  16143. 'timestamp)
  16144. (org-at-planning-p))
  16145. (not (time-less-p
  16146. (org-time-string-to-time match)
  16147. (org-time-string-to-time d))))))))
  16148. (message "%d entries after %s"
  16149. (org-occur regexp nil callback)
  16150. d)))
  16151. (defun org-check-dates-range (start-date end-date)
  16152. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16153. (interactive (list (org-read-date nil nil nil "Range starts")
  16154. (org-read-date nil nil nil "Range end")))
  16155. (let ((case-fold-search nil)
  16156. (regexp (org-re-timestamp org-ts-type))
  16157. (callback
  16158. (let ((type org-ts-type))
  16159. (lambda ()
  16160. (let ((match (match-string 1)))
  16161. (and
  16162. (if (memq type '(active inactive all))
  16163. (eq (org-element-type (save-excursion
  16164. (backward-char)
  16165. (org-element-context)))
  16166. 'timestamp)
  16167. (org-at-planning-p))
  16168. (not (time-less-p
  16169. (org-time-string-to-time match)
  16170. (org-time-string-to-time start-date)))
  16171. (time-less-p
  16172. (org-time-string-to-time match)
  16173. (org-time-string-to-time end-date))))))))
  16174. (message "%d entries between %s and %s"
  16175. (org-occur regexp nil callback) start-date end-date)))
  16176. (defun org-evaluate-time-range (&optional to-buffer)
  16177. "Evaluate a time range by computing the difference between start and end.
  16178. Normally the result is just printed in the echo area, but with prefix arg
  16179. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16180. If the time range is actually in a table, the result is inserted into the
  16181. next column.
  16182. For time difference computation, a year is assumed to be exactly 365
  16183. days in order to avoid rounding problems."
  16184. (interactive "P")
  16185. (or
  16186. (org-clock-update-time-maybe)
  16187. (save-excursion
  16188. (unless (org-at-date-range-p t)
  16189. (goto-char (point-at-bol))
  16190. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16191. (unless (org-at-date-range-p t)
  16192. (user-error "Not at a time-stamp range, and none found in current line")))
  16193. (let* ((ts1 (match-string 1))
  16194. (ts2 (match-string 2))
  16195. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16196. (match-end (match-end 0))
  16197. (time1 (org-time-string-to-time ts1))
  16198. (time2 (org-time-string-to-time ts2))
  16199. (t1 (float-time time1))
  16200. (t2 (float-time time2))
  16201. (diff (abs (- t2 t1)))
  16202. (negative (< (- t2 t1) 0))
  16203. ;; (ys (floor (* 365 24 60 60)))
  16204. (ds (* 24 60 60))
  16205. (hs (* 60 60))
  16206. (fy "%dy %dd %02d:%02d")
  16207. (fy1 "%dy %dd")
  16208. (fd "%dd %02d:%02d")
  16209. (fd1 "%dd")
  16210. (fh "%02d:%02d")
  16211. y d h m align)
  16212. (if havetime
  16213. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16214. y 0
  16215. d (floor (/ diff ds)) diff (mod diff ds)
  16216. h (floor (/ diff hs)) diff (mod diff hs)
  16217. m (floor (/ diff 60)))
  16218. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16219. y 0
  16220. d (floor (+ (/ diff ds) 0.5))
  16221. h 0 m 0))
  16222. (if (not to-buffer)
  16223. (message "%s" (org-make-tdiff-string y d h m))
  16224. (if (org-at-table-p)
  16225. (progn
  16226. (goto-char match-end)
  16227. (setq align t)
  16228. (and (looking-at " *|") (goto-char (match-end 0))))
  16229. (goto-char match-end))
  16230. (when (looking-at
  16231. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16232. (replace-match ""))
  16233. (when negative (insert " -"))
  16234. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16235. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16236. (insert " " (format fh h m))))
  16237. (when align (org-table-align))
  16238. (message "Time difference inserted")))))
  16239. (defun org-make-tdiff-string (y d h m)
  16240. (let ((fmt "")
  16241. (l nil))
  16242. (when (> y 0)
  16243. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16244. (push y l))
  16245. (when (> d 0)
  16246. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16247. (push d l))
  16248. (when (> h 0)
  16249. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16250. (push h l))
  16251. (when (> m 0)
  16252. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16253. (push m l))
  16254. (apply 'format fmt (nreverse l))))
  16255. (defun org-time-string-to-time (s &optional buffer pos)
  16256. "Convert a timestamp string into internal time."
  16257. (condition-case errdata
  16258. (apply 'encode-time (org-parse-time-string s))
  16259. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16260. s (if (not (and buffer pos))
  16261. ""
  16262. (format-message " at %d in buffer `%s'" pos buffer))
  16263. (cdr errdata)))))
  16264. (defun org-time-string-to-seconds (s)
  16265. "Convert a timestamp string to a number of seconds."
  16266. (float-time (org-time-string-to-time s)))
  16267. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16268. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16269. "Convert time stamp S to an absolute day number.
  16270. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16271. stamp, get the closest date to DAYNR. If PREFER is
  16272. `past' (respectively `future') return a date past (respectively
  16273. after) or equal to DAYNR.
  16274. POS is the location of time stamp S, as a buffer position in
  16275. BUFFER.
  16276. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16277. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16278. signalled."
  16279. (cond
  16280. ((string-match "\\`%%\\((.*)\\)" s)
  16281. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16282. ;; only able to match individual dates. If it fails, raise an
  16283. ;; error.
  16284. (if (and daynr
  16285. (org-diary-sexp-entry
  16286. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16287. daynr
  16288. (signal 'org-diary-sexp-no-match (list s))))
  16289. ((and daynr show-all) (org-closest-date s daynr prefer))
  16290. (t (time-to-days
  16291. (condition-case errdata
  16292. (apply #'encode-time (org-parse-time-string s))
  16293. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16294. s
  16295. (if (not (and buffer pos)) ""
  16296. (format-message " at %d in buffer `%s'" pos buffer))
  16297. (cdr errdata))))))))
  16298. (defun org-days-to-iso-week (days)
  16299. "Return the iso week number."
  16300. (require 'cal-iso)
  16301. (car (calendar-iso-from-absolute days)))
  16302. (defun org-small-year-to-year (year)
  16303. "Convert 2-digit years into 4-digit years.
  16304. YEAR is expanded into one of the 30 next years, if possible, or
  16305. into a past one. Any year larger than 99 is returned unchanged."
  16306. (if (>= year 100) year
  16307. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16308. (century (/ current 100))
  16309. (offset (- year (% current 100))))
  16310. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16311. ((> offset -70) (+ (* century 100) year))
  16312. (t (+ (* (1+ century) 100) year))))))
  16313. (defun org-time-from-absolute (d)
  16314. "Return the time corresponding to date D.
  16315. D may be an absolute day number, or a calendar-type list (month day year)."
  16316. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16317. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16318. (defvar org-agenda-current-date)
  16319. (defun org-calendar-holiday ()
  16320. "List of holidays, for Diary display in Org mode."
  16321. (require 'holidays)
  16322. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16323. (and hl (mapconcat #'identity hl "; "))))
  16324. (defun org-diary-sexp-entry (sexp entry d)
  16325. "Process a SEXP diary ENTRY for date D."
  16326. (require 'diary-lib)
  16327. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16328. ;; dynamically.
  16329. (let* ((sexp `(let ((entry ,entry)
  16330. (date ',d))
  16331. ,(car (read-from-string sexp))))
  16332. (result (if calendar-debug-sexp (eval sexp)
  16333. (condition-case nil
  16334. (eval sexp)
  16335. (error
  16336. (beep)
  16337. (message "Bad sexp at line %d in %s: %s"
  16338. (org-current-line)
  16339. (buffer-file-name) sexp)
  16340. (sleep-for 2))))))
  16341. (cond ((stringp result) (split-string result "; "))
  16342. ((and (consp result)
  16343. (not (consp (cdr result)))
  16344. (stringp (cdr result))) (cdr result))
  16345. ((and (consp result)
  16346. (stringp (car result))) result)
  16347. (result entry))))
  16348. (defun org-diary-to-ical-string (frombuf)
  16349. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16350. This uses the icalendar.el library."
  16351. (let* ((tmpdir temporary-file-directory)
  16352. (tmpfile (make-temp-name
  16353. (expand-file-name "orgics" tmpdir)))
  16354. buf rtn b e)
  16355. (with-current-buffer frombuf
  16356. (icalendar-export-region (point-min) (point-max) tmpfile)
  16357. (setq buf (find-buffer-visiting tmpfile))
  16358. (set-buffer buf)
  16359. (goto-char (point-min))
  16360. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16361. (setq b (match-beginning 0)))
  16362. (goto-char (point-max))
  16363. (when (re-search-backward "^END:VEVENT" nil t)
  16364. (setq e (match-end 0)))
  16365. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16366. (kill-buffer buf)
  16367. (delete-file tmpfile)
  16368. rtn))
  16369. (defun org-closest-date (start current prefer)
  16370. "Return closest date to CURRENT starting from START.
  16371. CURRENT and START are both time stamps.
  16372. When PREFER is `past', return a date that is either CURRENT or
  16373. past. When PREFER is `future', return a date that is either
  16374. CURRENT or future.
  16375. Only time stamps with a repeater are modified. Any other time
  16376. stamp stay unchanged. In any case, return value is an absolute
  16377. day number."
  16378. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16379. ;; No repeater. Do not shift time stamp.
  16380. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16381. (let ((value (string-to-number (match-string 1 start)))
  16382. (type (match-string 2 start)))
  16383. (if (= 0 value)
  16384. ;; Repeater with a 0-value is considered as void.
  16385. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16386. (let* ((base (org-date-to-gregorian start))
  16387. (target (org-date-to-gregorian current))
  16388. (sday (calendar-absolute-from-gregorian base))
  16389. (cday (calendar-absolute-from-gregorian target))
  16390. n1 n2)
  16391. ;; If START is already past CURRENT, just return START.
  16392. (if (<= cday sday) sday
  16393. ;; Compute closest date before (N1) and closest date past
  16394. ;; (N2) CURRENT.
  16395. (pcase type
  16396. ("h"
  16397. (let ((missing-hours
  16398. (mod (+ (- (* 24 (- cday sday))
  16399. (nth 2 (org-parse-time-string start)))
  16400. org-extend-today-until)
  16401. value)))
  16402. (setf n1 (if (= missing-hours 0) cday
  16403. (- cday (1+ (/ missing-hours 24)))))
  16404. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16405. ((or "d" "w")
  16406. (let ((value (if (equal type "w") (* 7 value) value)))
  16407. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16408. (setf n2 (+ n1 value))))
  16409. ("m"
  16410. (let* ((add-months
  16411. (lambda (d n)
  16412. ;; Add N months to gregorian date D, i.e.,
  16413. ;; a list (MONTH DAY YEAR). Return a valid
  16414. ;; gregorian date.
  16415. (let ((m (+ (nth 0 d) n)))
  16416. (list (mod m 12)
  16417. (nth 1 d)
  16418. (+ (/ m 12) (nth 2 d))))))
  16419. (months ; Complete months to TARGET.
  16420. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16421. (- (nth 0 target) (nth 0 base))
  16422. ;; If START's day is greater than
  16423. ;; TARGET's, remove incomplete month.
  16424. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16425. value)
  16426. value))
  16427. (before (funcall add-months base months)))
  16428. (setf n1 (calendar-absolute-from-gregorian before))
  16429. (setf n2
  16430. (calendar-absolute-from-gregorian
  16431. (funcall add-months before value)))))
  16432. (_
  16433. (let* ((d (nth 1 base))
  16434. (m (nth 0 base))
  16435. (y (nth 2 base))
  16436. (years ; Complete years to TARGET.
  16437. (* (/ (- (nth 2 target)
  16438. y
  16439. ;; If START's month and day are
  16440. ;; greater than TARGET's, remove
  16441. ;; incomplete year.
  16442. (if (or (> (nth 0 target) m)
  16443. (and (= (nth 0 target) m)
  16444. (> (nth 1 target) d)))
  16445. 0
  16446. 1))
  16447. value)
  16448. value))
  16449. (before (list m d (+ y years))))
  16450. (setf n1 (calendar-absolute-from-gregorian before))
  16451. (setf n2 (calendar-absolute-from-gregorian
  16452. (list m d (+ (nth 2 before) value)))))))
  16453. ;; Handle PREFER parameter, if any.
  16454. (cond
  16455. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16456. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16457. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16458. (defun org-date-to-gregorian (d)
  16459. "Turn any specification of date D into a Gregorian date for the calendar."
  16460. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16461. ((and (listp d) (= (length d) 3)) d)
  16462. ((stringp d)
  16463. (let ((d (org-parse-time-string d)))
  16464. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16465. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16466. (defun org-parse-time-string (s &optional nodefault)
  16467. "Parse the standard Org-mode time string.
  16468. This should be a lot faster than the normal `parse-time-string'.
  16469. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16470. hour and minute fields will be nil if not given."
  16471. (cond ((string-match org-ts-regexp0 s)
  16472. (list 0
  16473. (when (or (match-beginning 8) (not nodefault))
  16474. (string-to-number (or (match-string 8 s) "0")))
  16475. (when (or (match-beginning 7) (not nodefault))
  16476. (string-to-number (or (match-string 7 s) "0")))
  16477. (string-to-number (match-string 4 s))
  16478. (string-to-number (match-string 3 s))
  16479. (string-to-number (match-string 2 s))
  16480. nil nil nil))
  16481. ((string-match "^<[^>]+>$" s)
  16482. (decode-time (seconds-to-time (org-matcher-time s))))
  16483. (t (error "Not a standard Org-mode time string: %s" s))))
  16484. (defun org-timestamp-up (&optional arg)
  16485. "Increase the date item at the cursor by one.
  16486. If the cursor is on the year, change the year. If it is on the month,
  16487. the day or the time, change that.
  16488. With prefix ARG, change by that many units."
  16489. (interactive "p")
  16490. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16491. (defun org-timestamp-down (&optional arg)
  16492. "Decrease the date item at the cursor by one.
  16493. If the cursor is on the year, change the year. If it is on the month,
  16494. the day or the time, change that.
  16495. With prefix ARG, change by that many units."
  16496. (interactive "p")
  16497. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16498. (defun org-timestamp-up-day (&optional arg)
  16499. "Increase the date in the time stamp by one day.
  16500. With prefix ARG, change that many days."
  16501. (interactive "p")
  16502. (if (and (not (org-at-timestamp-p t))
  16503. (org-at-heading-p))
  16504. (org-todo 'up)
  16505. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16506. (defun org-timestamp-down-day (&optional arg)
  16507. "Decrease the date in the time stamp by one day.
  16508. With prefix ARG, change that many days."
  16509. (interactive "p")
  16510. (if (and (not (org-at-timestamp-p t))
  16511. (org-at-heading-p))
  16512. (org-todo 'down)
  16513. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16514. (defun org-at-timestamp-p (&optional inactive-ok)
  16515. "Non-nil if point is inside a timestamp.
  16516. When optional argument INACTIVE-OK is non-nil, also consider
  16517. inactive timestamps.
  16518. When this function returns a non-nil value, match data is set
  16519. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16520. INACTIVE-OK."
  16521. (interactive)
  16522. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16523. (pos (point))
  16524. (ans (or (looking-at tsr)
  16525. (save-excursion
  16526. (skip-chars-backward "^[<\n\r\t")
  16527. (when (> (point) (point-min)) (backward-char 1))
  16528. (and (looking-at tsr)
  16529. (> (- (match-end 0) pos) -1))))))
  16530. (and ans
  16531. (boundp 'org-ts-what)
  16532. (setq org-ts-what
  16533. (cond
  16534. ((= pos (match-beginning 0)) 'bracket)
  16535. ;; Point is considered to be "on the bracket" whether
  16536. ;; it's really on it or right after it.
  16537. ((= pos (1- (match-end 0))) 'bracket)
  16538. ((= pos (match-end 0)) 'after)
  16539. ((org-pos-in-match-range pos 2) 'year)
  16540. ((org-pos-in-match-range pos 3) 'month)
  16541. ((org-pos-in-match-range pos 7) 'hour)
  16542. ((org-pos-in-match-range pos 8) 'minute)
  16543. ((or (org-pos-in-match-range pos 4)
  16544. (org-pos-in-match-range pos 5)) 'day)
  16545. ((and (> pos (or (match-end 8) (match-end 5)))
  16546. (< pos (match-end 0)))
  16547. (- pos (or (match-end 8) (match-end 5))))
  16548. (t 'day))))
  16549. ans))
  16550. (defun org-toggle-timestamp-type ()
  16551. "Toggle the type (<active> or [inactive]) of a time stamp."
  16552. (interactive)
  16553. (when (org-at-timestamp-p t)
  16554. (let ((beg (match-beginning 0)) (end (match-end 0))
  16555. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16556. (save-excursion
  16557. (goto-char beg)
  16558. (while (re-search-forward "[][<>]" end t)
  16559. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16560. t t)))
  16561. (message "Timestamp is now %sactive"
  16562. (if (equal (char-after beg) ?<) "" "in")))))
  16563. (defun org-at-clock-log-p nil
  16564. "Is the cursor on the clock log line?"
  16565. (save-excursion
  16566. (move-beginning-of-line 1)
  16567. (looking-at org-clock-line-re)))
  16568. (defvar org-clock-history) ; defined in org-clock.el
  16569. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16570. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16571. "Change the date in the time stamp at point.
  16572. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16573. `year', `minute', `second'. If WHAT is not given, the cursor position
  16574. in the timestamp determines what will be changed.
  16575. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16576. (let ((origin (point)) origin-cat
  16577. with-hm inactive
  16578. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16579. org-ts-what
  16580. extra rem
  16581. ts time time0 fixnext clrgx)
  16582. (unless (org-at-timestamp-p t)
  16583. (user-error "Not at a timestamp"))
  16584. (if (and (not what) (eq org-ts-what 'bracket))
  16585. (org-toggle-timestamp-type)
  16586. ;; Point isn't on brackets. Remember the part of the time-stamp
  16587. ;; the point was in. Indeed, size of time-stamps may change,
  16588. ;; but point must be kept in the same category nonetheless.
  16589. (setq origin-cat org-ts-what)
  16590. (when (and (not what) (not (eq org-ts-what 'day))
  16591. org-display-custom-times
  16592. (get-text-property (point) 'display)
  16593. (not (get-text-property (1- (point)) 'display)))
  16594. (setq org-ts-what 'day))
  16595. (setq org-ts-what (or what org-ts-what)
  16596. inactive (= (char-after (match-beginning 0)) ?\[)
  16597. ts (match-string 0))
  16598. (replace-match "")
  16599. (when (string-match
  16600. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16601. ts)
  16602. (setq extra (match-string 1 ts))
  16603. (when suppress-tmp-delay
  16604. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16605. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16606. (setq with-hm t))
  16607. (setq time0 (org-parse-time-string ts))
  16608. (when (and updown
  16609. (eq org-ts-what 'minute)
  16610. (not current-prefix-arg))
  16611. ;; This looks like s-up and s-down. Change by one rounding step.
  16612. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16613. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16614. (setcar (cdr time0) (+ (nth 1 time0)
  16615. (if (> n 0) (- rem) (- dm rem))))))
  16616. (setq time
  16617. (apply #'encode-time
  16618. (or (car time0) 0)
  16619. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16620. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16621. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16622. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16623. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16624. (nthcdr 6 time0)))
  16625. (when (and (member org-ts-what '(hour minute))
  16626. extra
  16627. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16628. (setq extra (org-modify-ts-extra
  16629. extra
  16630. (if (eq org-ts-what 'hour) 2 5)
  16631. n dm)))
  16632. (when (integerp org-ts-what)
  16633. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16634. (when (eq what 'calendar)
  16635. (let ((cal-date (org-get-date-from-calendar)))
  16636. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16637. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16638. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16639. (setcar time0 (or (car time0) 0))
  16640. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16641. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16642. (setq time (apply 'encode-time time0))))
  16643. ;; Insert the new time-stamp, and ensure point stays in the same
  16644. ;; category as before (i.e. not after the last position in that
  16645. ;; category).
  16646. (let ((pos (point)))
  16647. ;; Stay before inserted string. `save-excursion' is of no use.
  16648. (setq org-last-changed-timestamp
  16649. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16650. (goto-char pos))
  16651. (save-match-data
  16652. (looking-at org-ts-regexp3)
  16653. (goto-char (cond
  16654. ;; `day' category ends before `hour' if any, or at
  16655. ;; the end of the day name.
  16656. ((eq origin-cat 'day)
  16657. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16658. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16659. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16660. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16661. ;; `year' and `month' have both fixed size: point
  16662. ;; couldn't have moved into another part.
  16663. (t origin))))
  16664. ;; Update clock if on a CLOCK line.
  16665. (org-clock-update-time-maybe)
  16666. ;; Maybe adjust the closest clock in `org-clock-history'
  16667. (when org-clock-adjust-closest
  16668. (if (not (and (org-at-clock-log-p)
  16669. (< 1 (length (delq nil (mapcar 'marker-position
  16670. org-clock-history))))))
  16671. (message "No clock to adjust")
  16672. (cond ((save-excursion ; fix previous clock?
  16673. (re-search-backward org-ts-regexp0 nil t)
  16674. (looking-back (concat org-clock-string " \\[")
  16675. (line-beginning-position)))
  16676. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16677. ((save-excursion ; fix next clock?
  16678. (re-search-backward org-ts-regexp0 nil t)
  16679. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16680. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16681. (save-window-excursion
  16682. ;; Find closest clock to point, adjust the previous/next one in history
  16683. (let* ((p (save-excursion (org-back-to-heading t)))
  16684. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16685. (clfixnth
  16686. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16687. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16688. (if (not clfixpos)
  16689. (message "No clock to adjust")
  16690. (save-excursion
  16691. (org-goto-marker-or-bmk clfixpos)
  16692. (org-show-subtree)
  16693. (when (re-search-forward clrgx nil t)
  16694. (goto-char (match-beginning 1))
  16695. (let (org-clock-adjust-closest)
  16696. (org-timestamp-change n org-ts-what updown))
  16697. (message "Clock adjusted in %s for heading: %s"
  16698. (file-name-nondirectory (buffer-file-name))
  16699. (org-get-heading t t)))))))))
  16700. ;; Try to recenter the calendar window, if any.
  16701. (when (and org-calendar-follow-timestamp-change
  16702. (get-buffer-window "*Calendar*" t)
  16703. (memq org-ts-what '(day month year)))
  16704. (org-recenter-calendar (time-to-days time))))))
  16705. (defun org-modify-ts-extra (s pos n dm)
  16706. "Change the different parts of the lead-time and repeat fields in timestamp."
  16707. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16708. ng h m new rem)
  16709. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16710. (cond
  16711. ((or (org-pos-in-match-range pos 2)
  16712. (org-pos-in-match-range pos 3))
  16713. (setq m (string-to-number (match-string 3 s))
  16714. h (string-to-number (match-string 2 s)))
  16715. (if (org-pos-in-match-range pos 2)
  16716. (setq h (+ h n))
  16717. (setq n (* dm (with-no-warnings (signum n))))
  16718. (unless (= 0 (setq rem (% m dm)))
  16719. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16720. (setq m (+ m n)))
  16721. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16722. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16723. (setq h (mod h 24))
  16724. (setq ng 1 new (format "-%02d:%02d" h m)))
  16725. ((org-pos-in-match-range pos 6)
  16726. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16727. ((org-pos-in-match-range pos 5)
  16728. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16729. ((org-pos-in-match-range pos 9)
  16730. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16731. ((org-pos-in-match-range pos 8)
  16732. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16733. (when ng
  16734. (setq s (concat
  16735. (substring s 0 (match-beginning ng))
  16736. new
  16737. (substring s (match-end ng))))))
  16738. s))
  16739. (defun org-recenter-calendar (d)
  16740. "If the calendar is visible, recenter it to date D."
  16741. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16742. (when cwin
  16743. (let ((calendar-move-hook nil))
  16744. (with-selected-window cwin
  16745. (calendar-goto-date
  16746. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16747. (defun org-goto-calendar (&optional arg)
  16748. "Go to the Emacs calendar at the current date.
  16749. If there is a time stamp in the current line, go to that date.
  16750. A prefix ARG can be used to force the current date."
  16751. (interactive "P")
  16752. (let ((tsr org-ts-regexp) diff
  16753. (calendar-move-hook nil)
  16754. (calendar-view-holidays-initially-flag nil)
  16755. (calendar-view-diary-initially-flag nil))
  16756. (when (or (org-at-timestamp-p)
  16757. (save-excursion
  16758. (beginning-of-line 1)
  16759. (looking-at (concat ".*" tsr))))
  16760. (let ((d1 (time-to-days (current-time)))
  16761. (d2 (time-to-days
  16762. (org-time-string-to-time (match-string 1)))))
  16763. (setq diff (- d2 d1))))
  16764. (calendar)
  16765. (calendar-goto-today)
  16766. (when (and diff (not arg)) (calendar-forward-day diff))))
  16767. (defun org-get-date-from-calendar ()
  16768. "Return a list (month day year) of date at point in calendar."
  16769. (with-current-buffer "*Calendar*"
  16770. (save-match-data
  16771. (calendar-cursor-to-date))))
  16772. (defun org-date-from-calendar ()
  16773. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16774. If there is already a time stamp at the cursor position, update it."
  16775. (interactive)
  16776. (if (org-at-timestamp-p t)
  16777. (org-timestamp-change 0 'calendar)
  16778. (let ((cal-date (org-get-date-from-calendar)))
  16779. (org-insert-time-stamp
  16780. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16781. (defcustom org-effort-durations
  16782. `(("min" . 1)
  16783. ("h" . 60)
  16784. ("d" . ,(* 60 8))
  16785. ("w" . ,(* 60 8 5))
  16786. ("m" . ,(* 60 8 5 4))
  16787. ("y" . ,(* 60 8 5 40)))
  16788. "Conversion factor to minutes for an effort modifier.
  16789. Each entry has the form (MODIFIER . MINUTES).
  16790. In an effort string, a number followed by MODIFIER is multiplied
  16791. by the specified number of MINUTES to obtain an effort in
  16792. minutes.
  16793. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16794. effort string \"2hours\" is equivalent to 120 minutes."
  16795. :group 'org-agenda
  16796. :version "25.1"
  16797. :package-version '(Org . "8.3")
  16798. :type '(alist :key-type (string :tag "Modifier")
  16799. :value-type (number :tag "Minutes")))
  16800. (defun org-minutes-to-clocksum-string (m)
  16801. "Format number of minutes as a clocksum string.
  16802. The format is determined by `org-time-clocksum-format',
  16803. `org-time-clocksum-use-fractional' and
  16804. `org-time-clocksum-fractional-format' and
  16805. `org-time-clocksum-use-effort-durations'."
  16806. (let ((clocksum "")
  16807. (m (round m)) ; Don't allow fractions of minutes
  16808. h d w mo y fmt n)
  16809. (setq h (if org-time-clocksum-use-effort-durations
  16810. (cdr (assoc "h" org-effort-durations)) 60)
  16811. d (if org-time-clocksum-use-effort-durations
  16812. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16813. w (if org-time-clocksum-use-effort-durations
  16814. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16815. mo (if org-time-clocksum-use-effort-durations
  16816. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16817. y (if org-time-clocksum-use-effort-durations
  16818. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16819. ;; fractional format
  16820. (if org-time-clocksum-use-fractional
  16821. (cond
  16822. ;; single format string
  16823. ((stringp org-time-clocksum-fractional-format)
  16824. (format org-time-clocksum-fractional-format (/ m (float h))))
  16825. ;; choice of fractional formats for different time units
  16826. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16827. (> (/ (truncate m) (* y d h)) 0))
  16828. (format fmt (/ m (* y d (float h)))))
  16829. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16830. (> (/ (truncate m) (* mo d h)) 0))
  16831. (format fmt (/ m (* mo d (float h)))))
  16832. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16833. (> (/ (truncate m) (* w d h)) 0))
  16834. (format fmt (/ m (* w d (float h)))))
  16835. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16836. (> (/ (truncate m) (* d h)) 0))
  16837. (format fmt (/ m (* d (float h)))))
  16838. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16839. (> (/ (truncate m) h) 0))
  16840. (format fmt (/ m (float h))))
  16841. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16842. (format fmt m))
  16843. ;; fall back to smallest time unit with a format
  16844. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16845. (format fmt (/ m (float h))))
  16846. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16847. (format fmt (/ m (* d (float h)))))
  16848. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16849. (format fmt (/ m (* w d (float h)))))
  16850. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16851. (format fmt (/ m (* mo d (float h)))))
  16852. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16853. (format fmt (/ m (* y d (float h))))))
  16854. ;; standard (non-fractional) format, with single format string
  16855. (if (stringp org-time-clocksum-format)
  16856. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16857. ;; separate formats components
  16858. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16859. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16860. (plist-get org-time-clocksum-format :require-years))
  16861. (setq clocksum (concat clocksum (format fmt n))
  16862. m (- m (* n y d h))))
  16863. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16864. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16865. (plist-get org-time-clocksum-format :require-months))
  16866. (setq clocksum (concat clocksum (format fmt n))
  16867. m (- m (* n mo d h))))
  16868. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16869. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16870. (plist-get org-time-clocksum-format :require-weeks))
  16871. (setq clocksum (concat clocksum (format fmt n))
  16872. m (- m (* n w d h))))
  16873. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16874. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16875. (plist-get org-time-clocksum-format :require-days))
  16876. (setq clocksum (concat clocksum (format fmt n))
  16877. m (- m (* n d h))))
  16878. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16879. (or (> (setq n (/ (truncate m) h)) 0)
  16880. (plist-get org-time-clocksum-format :require-hours))
  16881. (setq clocksum (concat clocksum (format fmt n))
  16882. m (- m (* n h))))
  16883. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16884. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16885. (setq clocksum (concat clocksum (format fmt m))))
  16886. ;; return formatted time duration
  16887. clocksum))))
  16888. (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
  16889. (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
  16890. "Org mode version 8.0")
  16891. (defun org-hours-to-clocksum-string (n)
  16892. (org-minutes-to-clocksum-string (* n 60)))
  16893. (defun org-hh:mm-string-to-minutes (s)
  16894. "Convert a string H:MM to a number of minutes.
  16895. If the string is just a number, interpret it as minutes.
  16896. In fact, the first hh:mm or number in the string will be taken,
  16897. there can be extra stuff in the string.
  16898. If no number is found, the return value is 0."
  16899. (cond
  16900. ((integerp s) s)
  16901. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16902. (+ (* (string-to-number (match-string 1 s)) 60)
  16903. (string-to-number (match-string 2 s))))
  16904. ((string-match "\\([0-9]+\\)" s)
  16905. (string-to-number (match-string 1 s)))
  16906. (t 0)))
  16907. (defcustom org-image-actual-width t
  16908. "Should we use the actual width of images when inlining them?
  16909. When set to t, always use the image width.
  16910. When set to a number, use imagemagick (when available) to set
  16911. the image's width to this value.
  16912. When set to a number in a list, try to get the width from any
  16913. #+ATTR.* keyword if it matches a width specification like
  16914. #+ATTR_HTML: :width 300px
  16915. and fall back on that number if none is found.
  16916. When set to nil, try to get the width from an #+ATTR.* keyword
  16917. and fall back on the original width if none is found.
  16918. This requires Emacs >= 24.1, build with imagemagick support."
  16919. :group 'org-appearance
  16920. :version "24.4"
  16921. :package-version '(Org . "8.0")
  16922. :type '(choice
  16923. (const :tag "Use the image width" t)
  16924. (integer :tag "Use a number of pixels")
  16925. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16926. (const :tag "Use #+ATTR* or don't resize" nil)))
  16927. (defcustom org-agenda-inhibit-startup nil
  16928. "Inhibit startup when preparing agenda buffers.
  16929. When this variable is t, the initialization of the Org agenda
  16930. buffers is inhibited: e.g. the visibility state is not set, the
  16931. tables are not re-aligned, etc."
  16932. :type 'boolean
  16933. :version "24.3"
  16934. :group 'org-agenda)
  16935. (defcustom org-agenda-ignore-properties nil
  16936. "Avoid updating text properties when building the agenda.
  16937. Properties are used to prepare buffers for effort estimates,
  16938. appointments, statistics and subtree-local categories.
  16939. If you don't use these in the agenda, you can add them to this
  16940. list and agenda building will be a bit faster.
  16941. The value is a list, with zero or more of the symbols `effort', `appt',
  16942. `stats' or `category'."
  16943. :type '(set :greedy t
  16944. (const effort)
  16945. (const appt)
  16946. (const stats)
  16947. (const category))
  16948. :version "25.1"
  16949. :package-version '(Org . "8.3")
  16950. :group 'org-agenda)
  16951. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16952. "Convert a duration string S to minutes.
  16953. A bare number is interpreted as minutes, modifiers can be set by
  16954. customizing `org-effort-durations' (which see).
  16955. Entries containing a colon are interpreted as H:MM by
  16956. `org-hh:mm-string-to-minutes'."
  16957. (let ((result 0)
  16958. (re (concat "\\([0-9.]+\\) *\\("
  16959. (regexp-opt (mapcar 'car org-effort-durations))
  16960. "\\)")))
  16961. (while (string-match re s)
  16962. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16963. (string-to-number (match-string 1 s))))
  16964. (setq s (replace-match "" nil t s)))
  16965. (setq result (floor result))
  16966. (cl-incf result (org-hh:mm-string-to-minutes s))
  16967. (if output-to-string (number-to-string result) result)))
  16968. ;;;; Files
  16969. (defun org-save-all-org-buffers ()
  16970. "Save all Org-mode buffers without user confirmation."
  16971. (interactive)
  16972. (message "Saving all Org-mode buffers...")
  16973. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16974. (when (featurep 'org-id) (org-id-locations-save))
  16975. (message "Saving all Org-mode buffers... done"))
  16976. (defun org-revert-all-org-buffers ()
  16977. "Revert all Org-mode buffers.
  16978. Prompt for confirmation when there are unsaved changes.
  16979. Be sure you know what you are doing before letting this function
  16980. overwrite your changes.
  16981. This function is useful in a setup where one tracks org files
  16982. with a version control system, to revert on one machine after pulling
  16983. changes from another. I believe the procedure must be like this:
  16984. 1. M-x org-save-all-org-buffers
  16985. 2. Pull changes from the other machine, resolve conflicts
  16986. 3. M-x org-revert-all-org-buffers"
  16987. (interactive)
  16988. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16989. (user-error "Abort"))
  16990. (save-excursion
  16991. (save-window-excursion
  16992. (dolist (b (buffer-list))
  16993. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16994. (with-current-buffer b buffer-file-name))
  16995. (pop-to-buffer-same-window b)
  16996. (revert-buffer t 'no-confirm)))
  16997. (when (and (featurep 'org-id) org-id-track-globally)
  16998. (org-id-locations-load)))))
  16999. ;;;; Agenda files
  17000. ;;;###autoload
  17001. (defun org-switchb (&optional arg)
  17002. "Switch between Org buffers.
  17003. With \\[universal-argument] prefix, restrict available buffers to files.
  17004. With \\[universal-argument] \\[universal-argument] \
  17005. prefix, restrict available buffers to agenda files."
  17006. (interactive "P")
  17007. (let ((blist (org-buffer-list
  17008. (cond ((equal arg '(4)) 'files)
  17009. ((equal arg '(16)) 'agenda)))))
  17010. (pop-to-buffer-same-window
  17011. (completing-read "Org buffer: "
  17012. (mapcar #'list (mapcar #'buffer-name blist))
  17013. nil t))))
  17014. (defun org-buffer-list (&optional predicate exclude-tmp)
  17015. "Return a list of Org buffers.
  17016. PREDICATE can be `export', `files' or `agenda'.
  17017. export restrict the list to Export buffers.
  17018. files restrict the list to buffers visiting Org files.
  17019. agenda restrict the list to buffers visiting agenda files.
  17020. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  17021. (let* ((bfn nil)
  17022. (agenda-files (and (eq predicate 'agenda)
  17023. (mapcar 'file-truename (org-agenda-files t))))
  17024. (filter
  17025. (cond
  17026. ((eq predicate 'files)
  17027. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  17028. ((eq predicate 'export)
  17029. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  17030. ((eq predicate 'agenda)
  17031. (lambda (b)
  17032. (with-current-buffer b
  17033. (and (derived-mode-p 'org-mode)
  17034. (setq bfn (buffer-file-name b))
  17035. (member (file-truename bfn) agenda-files)))))
  17036. (t (lambda (b) (with-current-buffer b
  17037. (or (derived-mode-p 'org-mode)
  17038. (string-match "\\*Org .*Export"
  17039. (buffer-name b)))))))))
  17040. (delq nil
  17041. (mapcar
  17042. (lambda(b)
  17043. (if (and (funcall filter b)
  17044. (or (not exclude-tmp)
  17045. (not (string-match "tmp" (buffer-name b)))))
  17046. b
  17047. nil))
  17048. (buffer-list)))))
  17049. (defun org-agenda-files (&optional unrestricted archives)
  17050. "Get the list of agenda files.
  17051. Optional UNRESTRICTED means return the full list even if a restriction
  17052. is currently in place.
  17053. When ARCHIVES is t, include all archive files that are really being
  17054. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  17055. `org-agenda-archives-mode' is t."
  17056. (let ((files
  17057. (cond
  17058. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  17059. ((stringp org-agenda-files) (org-read-agenda-file-list))
  17060. ((listp org-agenda-files) org-agenda-files)
  17061. (t (error "Invalid value of `org-agenda-files'")))))
  17062. (setq files (apply 'append
  17063. (mapcar (lambda (f)
  17064. (if (file-directory-p f)
  17065. (directory-files
  17066. f t org-agenda-file-regexp)
  17067. (list f)))
  17068. files)))
  17069. (when org-agenda-skip-unavailable-files
  17070. (setq files (delq nil
  17071. (mapcar (function
  17072. (lambda (file)
  17073. (and (file-readable-p file) file)))
  17074. files))))
  17075. (when (or (eq archives t)
  17076. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17077. (setq files (org-add-archive-files files)))
  17078. files))
  17079. (defun org-agenda-file-p (&optional file)
  17080. "Return non-nil, if FILE is an agenda file.
  17081. If FILE is omitted, use the file associated with the current
  17082. buffer."
  17083. (let ((fname (or file (buffer-file-name))))
  17084. (and fname
  17085. (member (file-truename fname)
  17086. (mapcar #'file-truename (org-agenda-files t))))))
  17087. (defun org-edit-agenda-file-list ()
  17088. "Edit the list of agenda files.
  17089. Depending on setup, this either uses customize to edit the variable
  17090. `org-agenda-files', or it visits the file that is holding the list. In the
  17091. latter case, the buffer is set up in a way that saving it automatically kills
  17092. the buffer and restores the previous window configuration."
  17093. (interactive)
  17094. (if (stringp org-agenda-files)
  17095. (let ((cw (current-window-configuration)))
  17096. (find-file org-agenda-files)
  17097. (setq-local org-window-configuration cw)
  17098. (add-hook 'after-save-hook
  17099. (lambda ()
  17100. (set-window-configuration
  17101. (prog1 org-window-configuration
  17102. (kill-buffer (current-buffer))))
  17103. (org-install-agenda-files-menu)
  17104. (message "New agenda file list installed"))
  17105. nil 'local)
  17106. (message "%s" (substitute-command-keys
  17107. "Edit list and finish with \\[save-buffer]")))
  17108. (customize-variable 'org-agenda-files)))
  17109. (defun org-store-new-agenda-file-list (list)
  17110. "Set new value for the agenda file list and save it correctly."
  17111. (if (stringp org-agenda-files)
  17112. (let ((fe (org-read-agenda-file-list t)) b u)
  17113. (while (setq b (find-buffer-visiting org-agenda-files))
  17114. (kill-buffer b))
  17115. (with-temp-file org-agenda-files
  17116. (insert
  17117. (mapconcat
  17118. (lambda (f) ;; Keep un-expanded entries.
  17119. (if (setq u (assoc f fe))
  17120. (cdr u)
  17121. f))
  17122. list "\n")
  17123. "\n")))
  17124. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17125. (org-insert-mode-line-in-empty-file nil))
  17126. (setq org-agenda-files list)
  17127. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17128. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17129. "Read the list of agenda files from a file.
  17130. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17131. filenames, used by `org-store-new-agenda-file-list' to write back
  17132. un-expanded file names."
  17133. (when (file-directory-p org-agenda-files)
  17134. (error "`org-agenda-files' cannot be a single directory"))
  17135. (when (stringp org-agenda-files)
  17136. (with-temp-buffer
  17137. (insert-file-contents org-agenda-files)
  17138. (mapcar
  17139. (lambda (f)
  17140. (let ((e (expand-file-name (substitute-in-file-name f)
  17141. org-directory)))
  17142. (if pair-with-expansion
  17143. (cons e f)
  17144. e)))
  17145. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17146. ;;;###autoload
  17147. (defun org-cycle-agenda-files ()
  17148. "Cycle through the files in `org-agenda-files'.
  17149. If the current buffer visits an agenda file, find the next one in the list.
  17150. If the current buffer does not, find the first agenda file."
  17151. (interactive)
  17152. (let* ((fs (or (org-agenda-files t)
  17153. (user-error "No agenda files")))
  17154. (files (copy-sequence fs))
  17155. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17156. file)
  17157. (when tcf
  17158. (while (and (setq file (pop files))
  17159. (not (equal (file-truename file) tcf)))))
  17160. (find-file (car (or files fs)))
  17161. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17162. (defun org-agenda-file-to-front (&optional to-end)
  17163. "Move/add the current file to the top of the agenda file list.
  17164. If the file is not present in the list, it is added to the front. If it is
  17165. present, it is moved there. With optional argument TO-END, add/move to the
  17166. end of the list."
  17167. (interactive "P")
  17168. (let ((org-agenda-skip-unavailable-files nil)
  17169. (file-alist (mapcar (lambda (x)
  17170. (cons (file-truename x) x))
  17171. (org-agenda-files t)))
  17172. (ctf (file-truename
  17173. (or buffer-file-name
  17174. (user-error "Please save the current buffer to a file"))))
  17175. x had)
  17176. (setq x (assoc ctf file-alist) had x)
  17177. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17178. (if to-end
  17179. (setq file-alist (append (delq x file-alist) (list x)))
  17180. (setq file-alist (cons x (delq x file-alist))))
  17181. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17182. (org-install-agenda-files-menu)
  17183. (message "File %s to %s of agenda file list"
  17184. (if had "moved" "added") (if to-end "end" "front"))))
  17185. (defun org-remove-file (&optional file)
  17186. "Remove current file from the list of files in variable `org-agenda-files'.
  17187. These are the files which are being checked for agenda entries.
  17188. Optional argument FILE means use this file instead of the current."
  17189. (interactive)
  17190. (let* ((org-agenda-skip-unavailable-files nil)
  17191. (file (or file buffer-file-name
  17192. (user-error "Current buffer does not visit a file")))
  17193. (true-file (file-truename file))
  17194. (afile (abbreviate-file-name file))
  17195. (files (delq nil (mapcar
  17196. (lambda (x)
  17197. (unless (equal true-file
  17198. (file-truename x))
  17199. x))
  17200. (org-agenda-files t)))))
  17201. (if (not (= (length files) (length (org-agenda-files t))))
  17202. (progn
  17203. (org-store-new-agenda-file-list files)
  17204. (org-install-agenda-files-menu)
  17205. (message "Removed from Org Agenda list: %s" afile))
  17206. (message "File was not in list: %s (not removed)" afile))))
  17207. (defun org-file-menu-entry (file)
  17208. (vector file (list 'find-file file) t))
  17209. (defun org-check-agenda-file (file)
  17210. "Make sure FILE exists. If not, ask user what to do."
  17211. (unless (file-exists-p file)
  17212. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17213. (abbreviate-file-name file))
  17214. (let ((r (downcase (read-char-exclusive))))
  17215. (cond
  17216. ((equal r ?r)
  17217. (org-remove-file file)
  17218. (throw 'nextfile t))
  17219. (t (user-error "Abort"))))))
  17220. (defun org-get-agenda-file-buffer (file)
  17221. "Get an agenda buffer visiting FILE.
  17222. If the buffer needs to be created, add it to the list of buffers
  17223. which might be released later."
  17224. (let ((buf (org-find-base-buffer-visiting file)))
  17225. (if buf
  17226. buf ; just return it
  17227. ;; Make a new buffer and remember it
  17228. (setq buf (find-file-noselect file))
  17229. (when buf (push buf org-agenda-new-buffers))
  17230. buf)))
  17231. (defun org-release-buffers (blist)
  17232. "Release all buffers in list, asking the user for confirmation when needed.
  17233. When a buffer is unmodified, it is just killed. When modified, it is saved
  17234. \(if the user agrees) and then killed."
  17235. (let (file)
  17236. (dolist (buf blist)
  17237. (setq file (buffer-file-name buf))
  17238. (when (and (buffer-modified-p buf)
  17239. file
  17240. (y-or-n-p (format "Save file %s? " file)))
  17241. (with-current-buffer buf (save-buffer)))
  17242. (kill-buffer buf))))
  17243. (defun org-agenda-prepare-buffers (files)
  17244. "Create buffers for all agenda files, protect archived trees and comments."
  17245. (interactive)
  17246. (let ((pa '(:org-archived t))
  17247. (pc '(:org-comment t))
  17248. (pall '(:org-archived t :org-comment t))
  17249. (inhibit-read-only t)
  17250. (org-inhibit-startup org-agenda-inhibit-startup)
  17251. (rea (concat ":" org-archive-tag ":"))
  17252. re pos)
  17253. (setq org-tag-alist-for-agenda nil
  17254. org-tag-groups-alist-for-agenda nil)
  17255. (save-excursion
  17256. (save-restriction
  17257. (dolist (file files)
  17258. (catch 'nextfile
  17259. (if (bufferp file)
  17260. (set-buffer file)
  17261. (org-check-agenda-file file)
  17262. (set-buffer (org-get-agenda-file-buffer file)))
  17263. (widen)
  17264. (org-set-regexps-and-options 'tags-only)
  17265. (setq pos (point))
  17266. (or (memq 'category org-agenda-ignore-properties)
  17267. (org-refresh-category-properties))
  17268. (or (memq 'stats org-agenda-ignore-properties)
  17269. (org-refresh-stats-properties))
  17270. (or (memq 'effort org-agenda-ignore-properties)
  17271. (org-refresh-effort-properties))
  17272. (or (memq 'appt org-agenda-ignore-properties)
  17273. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17274. (setq org-todo-keywords-for-agenda
  17275. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17276. (setq org-done-keywords-for-agenda
  17277. (append org-done-keywords-for-agenda org-done-keywords))
  17278. (setq org-todo-keyword-alist-for-agenda
  17279. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17280. (setq org-tag-alist-for-agenda
  17281. (org-uniquify
  17282. (append org-tag-alist-for-agenda
  17283. org-current-tag-alist)))
  17284. ;; Merge current file's tag groups into global
  17285. ;; `org-tag-groups-alist-for-agenda'.
  17286. (when org-group-tags
  17287. (dolist (alist org-tag-groups-alist)
  17288. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17289. (if old
  17290. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17291. (push alist org-tag-groups-alist-for-agenda)))))
  17292. (org-with-silent-modifications
  17293. (save-excursion
  17294. (remove-text-properties (point-min) (point-max) pall)
  17295. (when org-agenda-skip-archived-trees
  17296. (goto-char (point-min))
  17297. (while (re-search-forward rea nil t)
  17298. (when (org-at-heading-p t)
  17299. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17300. (goto-char (point-min))
  17301. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17302. (while (re-search-forward re nil t)
  17303. (when (save-match-data (org-in-commented-heading-p t))
  17304. (add-text-properties
  17305. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17306. (goto-char pos)))))
  17307. (setq org-todo-keywords-for-agenda
  17308. (org-uniquify org-todo-keywords-for-agenda))
  17309. (setq org-todo-keyword-alist-for-agenda
  17310. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17311. ;;;; CDLaTeX minor mode
  17312. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17313. "Keymap for the minor `org-cdlatex-mode'.")
  17314. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17315. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17316. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17317. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17318. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17319. (defvar org-cdlatex-texmathp-advice-is-done nil
  17320. "Flag remembering if we have applied the advice to texmathp already.")
  17321. (define-minor-mode org-cdlatex-mode
  17322. "Toggle the minor `org-cdlatex-mode'.
  17323. This mode supports entering LaTeX environment and math in LaTeX fragments
  17324. in Org-mode.
  17325. \\{org-cdlatex-mode-map}"
  17326. nil " OCDL" nil
  17327. (when org-cdlatex-mode
  17328. (require 'cdlatex)
  17329. (run-hooks 'cdlatex-mode-hook)
  17330. (cdlatex-compute-tables))
  17331. (unless org-cdlatex-texmathp-advice-is-done
  17332. (setq org-cdlatex-texmathp-advice-is-done t)
  17333. (defadvice texmathp (around org-math-always-on activate)
  17334. "Always return t in org-mode buffers.
  17335. This is because we want to insert math symbols without dollars even outside
  17336. the LaTeX math segments. If Orgmode thinks that point is actually inside
  17337. an embedded LaTeX fragment, let texmathp do its job.
  17338. \\[org-cdlatex-mode-map]"
  17339. (interactive)
  17340. (let (p)
  17341. (cond
  17342. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17343. ((eq this-command 'cdlatex-math-symbol)
  17344. (setq ad-return-value t
  17345. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17346. (t
  17347. (let ((p (org-inside-LaTeX-fragment-p)))
  17348. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17349. (setq ad-return-value t
  17350. texmathp-why '("Org-mode embedded math" . 0))
  17351. (when p ad-do-it)))))))))
  17352. (defun turn-on-org-cdlatex ()
  17353. "Unconditionally turn on `org-cdlatex-mode'."
  17354. (org-cdlatex-mode 1))
  17355. (defun org-try-cdlatex-tab ()
  17356. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17357. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17358. - inside a LaTeX fragment, or
  17359. - after the first word in a line, where an abbreviation expansion could
  17360. insert a LaTeX environment."
  17361. (when org-cdlatex-mode
  17362. (cond
  17363. ;; Before any word on the line: No expansion possible.
  17364. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17365. ;; Just after first word on the line: Expand it. Make sure it
  17366. ;; cannot happen on headlines, though.
  17367. ((save-excursion
  17368. (skip-chars-backward "a-zA-Z0-9*")
  17369. (skip-chars-backward " \t")
  17370. (and (bolp) (not (org-at-heading-p))))
  17371. (cdlatex-tab) t)
  17372. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17373. (defun org-cdlatex-underscore-caret (&optional _arg)
  17374. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17375. Revert to the normal definition outside of these fragments."
  17376. (interactive "P")
  17377. (if (org-inside-LaTeX-fragment-p)
  17378. (call-interactively 'cdlatex-sub-superscript)
  17379. (let (org-cdlatex-mode)
  17380. (call-interactively (key-binding (vector last-input-event))))))
  17381. (defun org-cdlatex-math-modify (&optional _arg)
  17382. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17383. Revert to the normal definition outside of these fragments."
  17384. (interactive "P")
  17385. (if (org-inside-LaTeX-fragment-p)
  17386. (call-interactively 'cdlatex-math-modify)
  17387. (let (org-cdlatex-mode)
  17388. (call-interactively (key-binding (vector last-input-event))))))
  17389. (defun org-cdlatex-environment-indent (&optional environment item)
  17390. "Execute `cdlatex-environment' and indent the inserted environment.
  17391. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17392. The inserted environment is indented to current indentation
  17393. unless point is at the beginning of the line, in which the
  17394. environment remains unintended."
  17395. (interactive)
  17396. ;; cdlatex-environment always return nil. Therefore, capture output
  17397. ;; first and determine if an environment was selected.
  17398. (let* ((beg (point-marker))
  17399. (end (copy-marker (point) t))
  17400. (inserted (progn
  17401. (ignore-errors (cdlatex-environment environment item))
  17402. (< beg end)))
  17403. ;; Figure out how many lines to move forward after the
  17404. ;; environment has been inserted.
  17405. (lines (when inserted
  17406. (save-excursion
  17407. (- (cl-loop while (< beg (point))
  17408. with x = 0
  17409. do (forward-line -1)
  17410. (cl-incf x)
  17411. finally return x)
  17412. (if (progn (goto-char beg)
  17413. (and (progn (skip-chars-forward " \t") (eolp))
  17414. (progn (skip-chars-backward " \t") (bolp))))
  17415. 1 0)))))
  17416. (env (org-trim (delete-and-extract-region beg end))))
  17417. (when inserted
  17418. ;; Get indentation of next line unless at column 0.
  17419. (let ((ind (if (bolp) 0
  17420. (save-excursion
  17421. (org-return-indent)
  17422. (prog1 (org-get-indentation)
  17423. (when (progn (skip-chars-forward " \t") (eolp))
  17424. (delete-region beg (point)))))))
  17425. (bol (progn (skip-chars-backward " \t") (bolp))))
  17426. ;; Insert a newline before environment unless at column zero
  17427. ;; to "escape" the current line. Insert a newline if
  17428. ;; something is one the same line as \end{ENVIRONMENT}.
  17429. (insert
  17430. (concat (unless bol "\n") env
  17431. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17432. (unless (zerop ind)
  17433. (save-excursion
  17434. (goto-char beg)
  17435. (while (< (point) end)
  17436. (unless (eolp) (indent-line-to ind))
  17437. (forward-line))))
  17438. (goto-char beg)
  17439. (forward-line lines)
  17440. (indent-line-to ind)))
  17441. (set-marker beg nil)
  17442. (set-marker end nil)))
  17443. ;;;; LaTeX fragments
  17444. (defun org-inside-LaTeX-fragment-p ()
  17445. "Test if point is inside a LaTeX fragment.
  17446. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17447. sequence appearing also before point.
  17448. Even though the matchers for math are configurable, this function assumes
  17449. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17450. delimiters are skipped when they have been removed by customization.
  17451. The return value is nil, or a cons cell with the delimiter and the
  17452. position of this delimiter.
  17453. This function does a reasonably good job, but can locally be fooled by
  17454. for example currency specifications. For example it will assume being in
  17455. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17456. fragments that are properly closed, but during editing, we have to live
  17457. with the uncertainty caused by missing closing delimiters. This function
  17458. looks only before point, not after."
  17459. (catch 'exit
  17460. (let ((pos (point))
  17461. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17462. (lim (progn
  17463. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17464. (point)))
  17465. dd-on str (start 0) m re)
  17466. (goto-char pos)
  17467. (when dodollar
  17468. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17469. re (nth 1 (assoc "$" org-latex-regexps)))
  17470. (while (string-match re str start)
  17471. (cond
  17472. ((= (match-end 0) (length str))
  17473. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17474. ((= (match-end 0) (- (length str) 5))
  17475. (throw 'exit nil))
  17476. (t (setq start (match-end 0))))))
  17477. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17478. (goto-char pos)
  17479. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17480. (and (match-beginning 2) (throw 'exit nil))
  17481. ;; count $$
  17482. (while (re-search-backward "\\$\\$" lim t)
  17483. (setq dd-on (not dd-on)))
  17484. (goto-char pos)
  17485. (when dd-on (cons "$$" m))))))
  17486. (defun org-inside-latex-macro-p ()
  17487. "Is point inside a LaTeX macro or its arguments?"
  17488. (save-match-data
  17489. (org-in-regexp
  17490. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17491. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17492. "Build an overlay between BEG and END using IMAGE file.
  17493. Argument IMAGETYPE is the extension of the displayed image,
  17494. as a string. It defaults to \"png\"."
  17495. (let ((ov (make-overlay beg end))
  17496. (imagetype (or (intern imagetype) 'png)))
  17497. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17498. (overlay-put ov 'evaporate t)
  17499. (overlay-put ov
  17500. 'modification-hooks
  17501. (list (lambda (o _flag _beg _end &optional _l)
  17502. (delete-overlay o))))
  17503. (overlay-put ov
  17504. 'display
  17505. (list 'image :type imagetype :file image :ascent 'center))))
  17506. (defun org--list-latex-overlays (&optional beg end)
  17507. "List all Org LaTeX overlays in current buffer.
  17508. Limit to overlays between BEG and END when those are provided."
  17509. (cl-remove-if-not
  17510. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17511. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17512. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17513. "Remove all overlays with LaTeX fragment images in current buffer.
  17514. When optional arguments BEG and END are non-nil, remove all
  17515. overlays between them instead. Return a non-nil value when some
  17516. overlays were removed, nil otherwise."
  17517. (let ((overlays (org--list-latex-overlays beg end)))
  17518. (mapc #'delete-overlay overlays)
  17519. overlays))
  17520. (defun org-toggle-latex-fragment (&optional arg)
  17521. "Preview the LaTeX fragment at point, or all locally or globally.
  17522. If the cursor is on a LaTeX fragment, create the image and overlay
  17523. it over the source code, if there is none. Remove it otherwise.
  17524. If there is no fragment at point, display all fragments in the
  17525. current section.
  17526. With prefix ARG, preview or clear image for all fragments in the
  17527. current subtree or in the whole buffer when used before the first
  17528. headline. With a double prefix ARG \\[universal-argument] \
  17529. \\[universal-argument] preview or clear images
  17530. for all fragments in the buffer."
  17531. (interactive "P")
  17532. (when (display-graphic-p)
  17533. (catch 'exit
  17534. (save-excursion
  17535. (let (beg end msg)
  17536. (cond
  17537. ((or (equal arg '(16))
  17538. (and (equal arg '(4))
  17539. (org-with-limited-levels (org-before-first-heading-p))))
  17540. (if (org-remove-latex-fragment-image-overlays)
  17541. (progn (message "LaTeX fragments images removed from buffer")
  17542. (throw 'exit nil))
  17543. (setq msg "Creating images for buffer...")))
  17544. ((equal arg '(4))
  17545. (org-with-limited-levels (org-back-to-heading t))
  17546. (setq beg (point))
  17547. (setq end (progn (org-end-of-subtree t) (point)))
  17548. (if (org-remove-latex-fragment-image-overlays beg end)
  17549. (progn
  17550. (message "LaTeX fragment images removed from subtree")
  17551. (throw 'exit nil))
  17552. (setq msg "Creating images for subtree...")))
  17553. ((let ((datum (org-element-context)))
  17554. (when (memq (org-element-type datum)
  17555. '(latex-environment latex-fragment))
  17556. (setq beg (org-element-property :begin datum))
  17557. (setq end (org-element-property :end datum))
  17558. (if (org-remove-latex-fragment-image-overlays beg end)
  17559. (progn (message "LaTeX fragment image removed")
  17560. (throw 'exit nil))
  17561. (setq msg "Creating image...")))))
  17562. (t
  17563. (org-with-limited-levels
  17564. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17565. (outline-previous-heading)
  17566. (point)))
  17567. (setq end (progn (outline-next-heading) (point)))
  17568. (if (org-remove-latex-fragment-image-overlays beg end)
  17569. (progn
  17570. (message "LaTeX fragment images removed from section")
  17571. (throw 'exit nil))
  17572. (setq msg "Creating images for section...")))))
  17573. (let ((file (buffer-file-name (buffer-base-buffer))))
  17574. (org-format-latex
  17575. (concat org-preview-latex-image-directory "org-ltximg")
  17576. beg end
  17577. ;; Emacs cannot overlay images from remote hosts. Create
  17578. ;; it in `temporary-file-directory' instead.
  17579. (if (or (not file) (file-remote-p file))
  17580. temporary-file-directory
  17581. default-directory)
  17582. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17583. (message (concat msg "done")))))))
  17584. (defun org-format-latex
  17585. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17586. "Replace LaTeX fragments with links to an image.
  17587. The function takes care of creating the replacement image.
  17588. Only consider fragments between BEG and END when those are
  17589. provided.
  17590. When optional argument OVERLAYS is non-nil, display the image on
  17591. top of the fragment instead of replacing it.
  17592. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17593. Some of the options can be changed using the variable
  17594. `org-format-latex-options', which see."
  17595. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17596. (unless (eq processing-type 'verbatim)
  17597. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17598. (cnt 0)
  17599. checkdir-flag)
  17600. (goto-char (or beg (point-min)))
  17601. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17602. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17603. (overlay-recenter (or end (point-max))))
  17604. (while (re-search-forward math-regexp end t)
  17605. (unless (and overlays
  17606. (eq (get-char-property (point) 'org-overlay-type)
  17607. 'org-latex-overlay))
  17608. (let* ((context (org-element-context))
  17609. (type (org-element-type context)))
  17610. (when (memq type '(latex-environment latex-fragment))
  17611. (let ((block-type (eq type 'latex-environment))
  17612. (value (org-element-property :value context))
  17613. (beg (org-element-property :begin context))
  17614. (end (save-excursion
  17615. (goto-char (org-element-property :end context))
  17616. (skip-chars-backward " \r\t\n")
  17617. (point))))
  17618. (cond
  17619. ((eq processing-type 'mathjax)
  17620. ;; Prepare for MathJax processing.
  17621. (if (not (string-match "\\`\\$\\$?" value))
  17622. (goto-char end)
  17623. (delete-region beg end)
  17624. (if (string= (match-string 0 value) "$$")
  17625. (insert "\\[" (substring value 2 -2) "\\]")
  17626. (insert "\\(" (substring value 1 -1) "\\)"))))
  17627. ((assq processing-type org-preview-latex-process-alist)
  17628. ;; Process to an image.
  17629. (cl-incf cnt)
  17630. (goto-char beg)
  17631. (let* ((processing-info
  17632. (cdr (assq processing-type org-preview-latex-process-alist)))
  17633. (face (face-at-point))
  17634. ;; Get the colors from the face at point.
  17635. (fg
  17636. (let ((color (plist-get org-format-latex-options
  17637. :foreground)))
  17638. (if (and forbuffer (eq color 'auto))
  17639. (face-attribute face :foreground nil 'default)
  17640. color)))
  17641. (bg
  17642. (let ((color (plist-get org-format-latex-options
  17643. :background)))
  17644. (if (and forbuffer (eq color 'auto))
  17645. (face-attribute face :background nil 'default)
  17646. color)))
  17647. (hash (sha1 (prin1-to-string
  17648. (list org-format-latex-header
  17649. org-latex-default-packages-alist
  17650. org-latex-packages-alist
  17651. org-format-latex-options
  17652. forbuffer value fg bg))))
  17653. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17654. (absprefix (expand-file-name prefix dir))
  17655. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17656. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17657. (sep (and block-type "\n\n"))
  17658. (link (concat sep "[[file:" linkfile "]]" sep))
  17659. (options
  17660. (org-combine-plists
  17661. org-format-latex-options
  17662. `(:foreground ,fg :background ,bg))))
  17663. (when msg (message msg cnt))
  17664. (unless checkdir-flag ; Ensure the directory exists.
  17665. (setq checkdir-flag t)
  17666. (let ((todir (file-name-directory absprefix)))
  17667. (unless (file-directory-p todir)
  17668. (make-directory todir t))))
  17669. (unless (file-exists-p movefile)
  17670. (org-create-formula-image
  17671. value movefile options forbuffer processing-type))
  17672. (if overlays
  17673. (progn
  17674. (dolist (o (overlays-in beg end))
  17675. (when (eq (overlay-get o 'org-overlay-type)
  17676. 'org-latex-overlay)
  17677. (delete-overlay o)))
  17678. (org--format-latex-make-overlay beg end movefile imagetype)
  17679. (goto-char end))
  17680. (delete-region beg end)
  17681. (insert
  17682. (org-add-props link
  17683. (list 'org-latex-src
  17684. (replace-regexp-in-string "\"" "" value)
  17685. 'org-latex-src-embed-type
  17686. (if block-type 'paragraph 'character)))))))
  17687. ((eq processing-type 'mathml)
  17688. ;; Process to MathML.
  17689. (unless (org-format-latex-mathml-available-p)
  17690. (user-error "LaTeX to MathML converter not configured"))
  17691. (cl-incf cnt)
  17692. (when msg (message msg cnt))
  17693. (goto-char beg)
  17694. (delete-region beg end)
  17695. (insert (org-format-latex-as-mathml
  17696. value block-type prefix dir)))
  17697. (t
  17698. (error "Unknown conversion process %s for LaTeX fragments"
  17699. processing-type)))))))))))
  17700. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17701. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17702. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17703. sucessful, return the portion between \"<math...> </math>\"
  17704. elements otherwise return nil. When MATHML-FILE is specified,
  17705. write the results in to that file. When invoked as an
  17706. interactive command, prompt for LATEX-FRAG, with initial value
  17707. set to the current active region and echo the results for user
  17708. inspection."
  17709. (interactive (list (let ((frag (when (org-region-active-p)
  17710. (buffer-substring-no-properties
  17711. (region-beginning) (region-end)))))
  17712. (read-string "LaTeX Fragment: " frag nil frag))))
  17713. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17714. (let* ((tmp-in-file
  17715. (let ((file (file-relative-name
  17716. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17717. (write-region latex-frag nil file)
  17718. file))
  17719. (tmp-out-file (file-relative-name
  17720. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17721. (cmd (format-spec
  17722. org-latex-to-mathml-convert-command
  17723. `((?j . ,(and org-latex-to-mathml-jar-file
  17724. (shell-quote-argument
  17725. (expand-file-name
  17726. org-latex-to-mathml-jar-file))))
  17727. (?I . ,(shell-quote-argument tmp-in-file))
  17728. (?i . ,latex-frag)
  17729. (?o . ,(shell-quote-argument tmp-out-file)))))
  17730. mathml shell-command-output)
  17731. (when (called-interactively-p 'any)
  17732. (unless (org-format-latex-mathml-available-p)
  17733. (user-error "LaTeX to MathML converter not configured")))
  17734. (message "Running %s" cmd)
  17735. (setq shell-command-output (shell-command-to-string cmd))
  17736. (setq mathml
  17737. (when (file-readable-p tmp-out-file)
  17738. (with-current-buffer (find-file-noselect tmp-out-file t)
  17739. (goto-char (point-min))
  17740. (when (re-search-forward
  17741. (concat
  17742. (regexp-quote
  17743. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17744. "[^>]*?>"
  17745. "\\(.\\|\n\\)*"
  17746. "</math>")
  17747. nil t)
  17748. (prog1 (match-string 0) (kill-buffer))))))
  17749. (cond
  17750. (mathml
  17751. (setq mathml
  17752. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17753. (when mathml-file
  17754. (write-region mathml nil mathml-file))
  17755. (when (called-interactively-p 'any)
  17756. (message mathml)))
  17757. ((message "LaTeX to MathML conversion failed")
  17758. (message shell-command-output)))
  17759. (delete-file tmp-in-file)
  17760. (when (file-exists-p tmp-out-file)
  17761. (delete-file tmp-out-file))
  17762. mathml))
  17763. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17764. prefix &optional dir)
  17765. "Use `org-create-math-formula' but check local cache first."
  17766. (let* ((absprefix (expand-file-name prefix dir))
  17767. (print-length nil) (print-level nil)
  17768. (formula-id (concat
  17769. "formula-"
  17770. (sha1
  17771. (prin1-to-string
  17772. (list latex-frag
  17773. org-latex-to-mathml-convert-command)))))
  17774. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17775. (formula-cache-dir (file-name-directory formula-cache)))
  17776. (unless (file-directory-p formula-cache-dir)
  17777. (make-directory formula-cache-dir t))
  17778. (unless (file-exists-p formula-cache)
  17779. (org-create-math-formula latex-frag formula-cache))
  17780. (if (file-exists-p formula-cache)
  17781. ;; Successful conversion. Return the link to MathML file.
  17782. (org-add-props
  17783. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17784. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17785. 'org-latex-src-embed-type (if latex-frag-type
  17786. 'paragraph 'character)))
  17787. ;; Failed conversion. Return the LaTeX fragment verbatim
  17788. latex-frag)))
  17789. (declare-function org-export-get-backend "ox" (name))
  17790. (declare-function org-export--get-global-options "ox" (&optional backend))
  17791. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17792. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17793. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17794. (defun org-create-formula--latex-header ()
  17795. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17796. (let ((info (org-combine-plists (org-export--get-global-options
  17797. (org-export-get-backend 'latex))
  17798. (org-export--get-inbuffer-options
  17799. (org-export-get-backend 'latex)))))
  17800. (org-latex-guess-babel-language
  17801. (org-latex-guess-inputenc
  17802. (org-splice-latex-header
  17803. org-format-latex-header
  17804. org-latex-default-packages-alist
  17805. org-latex-packages-alist t
  17806. (plist-get info :latex-header)))
  17807. info)))
  17808. (defun org--get-display-dpi ()
  17809. "Get the DPI of the display.
  17810. Assumes that the display has the same pixel width in the
  17811. horizontal and vertical directions."
  17812. (if (display-graphic-p)
  17813. (round (/ (display-pixel-height)
  17814. (/ (display-mm-height) 25.4)))
  17815. (error "Attempt to calculate the dpi of a non-graphic display")))
  17816. (defun org-create-formula-image
  17817. (string tofile options buffer &optional processing-type)
  17818. "Create an image from LaTeX source using external processes.
  17819. The LaTeX STRING is saved to a temporary LaTeX file, then
  17820. converted to an image file by process PROCESSING-TYPE defined in
  17821. `org-preview-latex-process-alist'. A nil value defaults to
  17822. `org-preview-latex-default-process'.
  17823. The generated image file is eventually moved to TOFILE.
  17824. The OPTIONS argument controls the size, foreground color and
  17825. background color of the generated image.
  17826. When BUFFER non-nil, this function is used for LaTeX previewing.
  17827. Otherwise, it is used to deal with LaTeX snippets showed in
  17828. a HTML file."
  17829. (let* ((processing-type (or processing-type
  17830. org-preview-latex-default-process))
  17831. (processing-info
  17832. (cdr (assq processing-type org-preview-latex-process-alist)))
  17833. (programs (plist-get processing-info :programs))
  17834. (error-message (or (plist-get processing-info :message) ""))
  17835. (use-xcolor (plist-get processing-info :use-xcolor))
  17836. (image-input-type (plist-get processing-info :image-input-type))
  17837. (image-output-type (plist-get processing-info :image-output-type))
  17838. (post-clean (or (plist-get processing-info :post-clean)
  17839. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17840. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17841. (latex-header (or (plist-get processing-info :latex-header)
  17842. (org-create-formula--latex-header)))
  17843. (latex-compiler (plist-get processing-info :latex-compiler))
  17844. (image-converter (plist-get processing-info :image-converter))
  17845. (tmpdir temporary-file-directory)
  17846. (texfilebase (make-temp-name
  17847. (expand-file-name "orgtex" tmpdir)))
  17848. (texfile (concat texfilebase ".tex"))
  17849. (font-height (face-attribute 'default :height nil))
  17850. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17851. '(1.0 . 1.0)))
  17852. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17853. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17854. (dpi (* scale (floor (if buffer font-height 140.0))))
  17855. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17856. "Black"))
  17857. (bg (or (plist-get options (if buffer :background :html-background))
  17858. "Transparent"))
  17859. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17860. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17861. (dolist (program programs)
  17862. (org-check-external-command program error-message))
  17863. (if use-xcolor
  17864. (progn (if (eq fg 'default)
  17865. (setq fg (org-latex-color :foreground))
  17866. (setq fg (org-latex-color-format fg)))
  17867. (if (eq bg 'default)
  17868. (setq bg (org-latex-color :background))
  17869. (setq bg (org-latex-color-format
  17870. (if (string= bg "Transparent") "white" bg))))
  17871. (with-temp-file texfile
  17872. (insert latex-header)
  17873. (insert "\n\\begin{document}\n"
  17874. "\\definecolor{fg}{rgb}{" fg "}\n"
  17875. "\\definecolor{bg}{rgb}{" bg "}\n"
  17876. "\n\\pagecolor{bg}\n"
  17877. "\n{\\color{fg}\n"
  17878. string
  17879. "\n}\n"
  17880. "\n\\end{document}\n")))
  17881. (if (eq fg 'default)
  17882. (setq fg (org-dvipng-color :foreground))
  17883. (unless (string= fg "Transparent")
  17884. (setq fg (org-dvipng-color-format fg))))
  17885. (if (eq bg 'default)
  17886. (setq bg (org-dvipng-color :background))
  17887. (unless (string= bg "Transparent")
  17888. (setq bg (org-dvipng-color-format bg))))
  17889. (with-temp-file texfile
  17890. (insert latex-header)
  17891. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17892. (let* ((err-msg (format "Please adjust '%s' part of \
  17893. `org-preview-latex-process-alist'."
  17894. processing-type))
  17895. (image-input-file
  17896. (org-compile-file
  17897. texfile latex-compiler image-input-type err-msg log-buf))
  17898. (image-output-file
  17899. (org-compile-file
  17900. image-input-file image-converter image-output-type err-msg log-buf
  17901. `((?F . ,(shell-quote-argument fg))
  17902. (?B . ,(shell-quote-argument bg))
  17903. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17904. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17905. (copy-file image-output-file tofile 'replace)
  17906. (dolist (e post-clean)
  17907. (when (file-exists-p (concat texfilebase e))
  17908. (delete-file (concat texfilebase e))))
  17909. image-output-file)))
  17910. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17911. "Fill a LaTeX header template TPL.
  17912. In the template, the following place holders will be recognized:
  17913. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17914. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17915. [PACKAGES] \\usepackage statements for PKG
  17916. [NO-PACKAGES] do not include PKG
  17917. [EXTRA] the string EXTRA
  17918. [NO-EXTRA] do not include EXTRA
  17919. For backward compatibility, if both the positive and the negative place
  17920. holder is missing, the positive one (without the \"NO-\") will be
  17921. assumed to be present at the end of the template.
  17922. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17923. EXTRA is a string.
  17924. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17925. (let (rpl (end ""))
  17926. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17927. (setq rpl (if (or (match-end 1) (not def-pkg))
  17928. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17929. tpl (replace-match rpl t t tpl))
  17930. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17931. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17932. (setq rpl (if (or (match-end 1) (not pkg))
  17933. "" (org-latex-packages-to-string pkg snippets-p t))
  17934. tpl (replace-match rpl t t tpl))
  17935. (when pkg (setq end
  17936. (concat end "\n"
  17937. (org-latex-packages-to-string pkg snippets-p)))))
  17938. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17939. (setq rpl (if (or (match-end 1) (not extra))
  17940. "" (concat extra "\n"))
  17941. tpl (replace-match rpl t t tpl))
  17942. (when (and extra (string-match "\\S-" extra))
  17943. (setq end (concat end "\n" extra))))
  17944. (if (string-match "\\S-" end)
  17945. (concat tpl "\n" end)
  17946. tpl)))
  17947. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17948. "Turn an alist of packages into a string with the \\usepackage macros."
  17949. (setq pkg (mapconcat (lambda(p)
  17950. (cond
  17951. ((stringp p) p)
  17952. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17953. (format "%% Package %s omitted" (cadr p)))
  17954. ((equal "" (car p))
  17955. (format "\\usepackage{%s}" (cadr p)))
  17956. (t
  17957. (format "\\usepackage[%s]{%s}"
  17958. (car p) (cadr p)))))
  17959. pkg
  17960. "\n"))
  17961. (if newline (concat pkg "\n") pkg))
  17962. (defun org-dvipng-color (attr)
  17963. "Return a RGB color specification for dvipng."
  17964. (apply #'format "rgb %s %s %s"
  17965. (mapcar #'org-normalize-color
  17966. (color-values (face-attribute 'default attr nil)))))
  17967. (defun org-dvipng-color-format (color-name)
  17968. "Convert COLOR-NAME to a RGB color value for dvipng."
  17969. (apply 'format "rgb %s %s %s"
  17970. (mapcar 'org-normalize-color
  17971. (color-values color-name))))
  17972. (defun org-latex-color (attr)
  17973. "Return a RGB color for the LaTeX color package."
  17974. (apply #'format "%s,%s,%s"
  17975. (mapcar #'org-normalize-color
  17976. (color-values (face-attribute 'default attr nil)))))
  17977. (defun org-latex-color-format (color-name)
  17978. "Convert COLOR-NAME to a RGB color value."
  17979. (apply 'format "%s,%s,%s"
  17980. (mapcar 'org-normalize-color
  17981. (color-values color-name))))
  17982. (defun org-normalize-color (value)
  17983. "Return string to be used as color value for an RGB component."
  17984. (format "%g" (/ value 65535.0)))
  17985. ;; Image display
  17986. (defvar-local org-inline-image-overlays nil)
  17987. (defun org-toggle-inline-images (&optional include-linked)
  17988. "Toggle the display of inline images.
  17989. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17990. (interactive "P")
  17991. (if org-inline-image-overlays
  17992. (progn
  17993. (org-remove-inline-images)
  17994. (when (called-interactively-p 'interactive)
  17995. (message "Inline image display turned off")))
  17996. (org-display-inline-images include-linked)
  17997. (when (called-interactively-p 'interactive)
  17998. (message (if org-inline-image-overlays
  17999. (format "%d images displayed inline"
  18000. (length org-inline-image-overlays))
  18001. "No images to display inline")))))
  18002. (defun org-redisplay-inline-images ()
  18003. "Refresh the display of inline images."
  18004. (interactive)
  18005. (if (not org-inline-image-overlays)
  18006. (org-toggle-inline-images)
  18007. (org-toggle-inline-images)
  18008. (org-toggle-inline-images)))
  18009. (defun org-display-inline-images (&optional include-linked refresh beg end)
  18010. "Display inline images.
  18011. An inline image is a link which follows either of these
  18012. conventions:
  18013. 1. Its path is a file with an extension matching return value
  18014. from `image-file-name-regexp' and it has no contents.
  18015. 2. Its description consists in a single link of the previous
  18016. type.
  18017. When optional argument INCLUDE-LINKED is non-nil, also links with
  18018. a text description part will be inlined. This can be nice for
  18019. a quick look at those images, but it does not reflect what
  18020. exported files will look like.
  18021. When optional argument REFRESH is non-nil, refresh existing
  18022. images between BEG and END. This will create new image displays
  18023. only if necessary. BEG and END default to the buffer
  18024. boundaries."
  18025. (interactive "P")
  18026. (when (display-graphic-p)
  18027. (unless refresh
  18028. (org-remove-inline-images)
  18029. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  18030. (org-with-wide-buffer
  18031. (goto-char (or beg (point-min)))
  18032. (let ((case-fold-search t)
  18033. (file-extension-re (image-file-name-regexp)))
  18034. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  18035. (let ((link (save-match-data (org-element-context))))
  18036. ;; Check if we're at an inline image.
  18037. (when (and (equal (org-element-property :type link) "file")
  18038. (or include-linked
  18039. (not (org-element-property :contents-begin link)))
  18040. (let ((parent (org-element-property :parent link)))
  18041. (or (not (eq (org-element-type parent) 'link))
  18042. (not (cdr (org-element-contents parent)))))
  18043. (org-string-match-p file-extension-re
  18044. (org-element-property :path link)))
  18045. (let ((file (expand-file-name
  18046. (org-link-unescape
  18047. (org-element-property :path link)))))
  18048. (when (file-exists-p file)
  18049. (let ((width
  18050. ;; Apply `org-image-actual-width' specifications.
  18051. (cond
  18052. ((not (image-type-available-p 'imagemagick)) nil)
  18053. ((eq org-image-actual-width t) nil)
  18054. ((listp org-image-actual-width)
  18055. (or
  18056. ;; First try to find a width among
  18057. ;; attributes associated to the paragraph
  18058. ;; containing link.
  18059. (let ((paragraph
  18060. (let ((e link))
  18061. (while (and (setq e (org-element-property
  18062. :parent e))
  18063. (not (eq (org-element-type e)
  18064. 'paragraph))))
  18065. e)))
  18066. (when paragraph
  18067. (save-excursion
  18068. (goto-char (org-element-property :begin paragraph))
  18069. (when
  18070. (re-search-forward
  18071. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18072. (org-element-property
  18073. :post-affiliated paragraph)
  18074. t)
  18075. (string-to-number (match-string 1))))))
  18076. ;; Otherwise, fall-back to provided number.
  18077. (car org-image-actual-width)))
  18078. ((numberp org-image-actual-width)
  18079. org-image-actual-width)))
  18080. (old (get-char-property-and-overlay
  18081. (org-element-property :begin link)
  18082. 'org-image-overlay)))
  18083. (if (and (car-safe old) refresh)
  18084. (image-refresh (overlay-get (cdr old) 'display))
  18085. (let ((image (create-image file
  18086. (and width 'imagemagick)
  18087. nil
  18088. :width width)))
  18089. (when image
  18090. (let* ((link
  18091. ;; If inline image is the description
  18092. ;; of another link, be sure to
  18093. ;; consider the latter as the one to
  18094. ;; apply the overlay on.
  18095. (let ((parent
  18096. (org-element-property :parent link)))
  18097. (if (eq (org-element-type parent) 'link)
  18098. parent
  18099. link)))
  18100. (ov (make-overlay
  18101. (org-element-property :begin link)
  18102. (progn
  18103. (goto-char
  18104. (org-element-property :end link))
  18105. (skip-chars-backward " \t")
  18106. (point)))))
  18107. (overlay-put ov 'display image)
  18108. (overlay-put ov 'face 'default)
  18109. (overlay-put ov 'org-image-overlay t)
  18110. (overlay-put
  18111. ov 'modification-hooks
  18112. (list 'org-display-inline-remove-overlay))
  18113. (push ov org-inline-image-overlays)))))))))))))))
  18114. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18115. "Remove inline-display overlay if a corresponding region is modified."
  18116. (let ((inhibit-modification-hooks t))
  18117. (when (and ov after)
  18118. (delete ov org-inline-image-overlays)
  18119. (delete-overlay ov))))
  18120. (defun org-remove-inline-images ()
  18121. "Remove inline display of images."
  18122. (interactive)
  18123. (mapc #'delete-overlay org-inline-image-overlays)
  18124. (setq org-inline-image-overlays nil))
  18125. ;;;; Key bindings
  18126. ;; Outline functions from `outline-mode-prefix-map'
  18127. ;; that can be remapped in Org:
  18128. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18129. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18130. (define-key org-mode-map [remap outline-forward-same-level]
  18131. 'org-forward-heading-same-level)
  18132. (define-key org-mode-map [remap outline-backward-same-level]
  18133. 'org-backward-heading-same-level)
  18134. (define-key org-mode-map [remap outline-show-branches]
  18135. 'org-kill-note-or-show-branches)
  18136. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18137. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18138. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18139. (define-key org-mode-map [remap outline-next-visible-heading]
  18140. 'org-next-visible-heading)
  18141. (define-key org-mode-map [remap outline-previous-visible-heading]
  18142. 'org-previous-visible-heading)
  18143. (define-key org-mode-map [remap show-children] 'org-show-children)
  18144. ;; Outline functions from `outline-mode-prefix-map' that can not
  18145. ;; be remapped in Org:
  18146. ;; - the column "key binding" shows whether the Outline function is still
  18147. ;; available in Org mode on the same key that it has been bound to in
  18148. ;; Outline mode:
  18149. ;; - "overridden": key used for a different functionality in Org mode
  18150. ;; - else: key still bound to the same Outline function in Org mode
  18151. ;; | Outline function | key binding | Org replacement |
  18152. ;; |------------------------------------+-------------+--------------------------|
  18153. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18154. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18155. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18156. ;; | `show-entry' | overridden | no replacement |
  18157. ;; | `show-branches' | `C-c C-k' | still same function |
  18158. ;; | `show-subtree' | overridden | visibility cycling |
  18159. ;; | `show-all' | overridden | no replacement |
  18160. ;; | `hide-subtree' | overridden | visibility cycling |
  18161. ;; | `hide-body' | overridden | no replacement |
  18162. ;; | `hide-entry' | overridden | visibility cycling |
  18163. ;; | `hide-leaves' | overridden | no replacement |
  18164. ;; | `hide-sublevels' | overridden | no replacement |
  18165. ;; | `hide-other' | overridden | no replacement |
  18166. ;; Make `C-c C-x' a prefix key
  18167. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18168. ;; TAB key with modifiers
  18169. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18170. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18171. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18172. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18173. ;; The following line is necessary under Suse GNU/Linux
  18174. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18175. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18176. (define-key org-mode-map [backtab] 'org-shifttab)
  18177. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18178. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18179. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18180. ;; Cursor keys with modifiers
  18181. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18182. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18183. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18184. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18185. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18186. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18187. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18188. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18189. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18190. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18191. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18192. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18193. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18194. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18195. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18196. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18197. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18198. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18199. ;; Babel keys
  18200. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18201. (dolist (pair org-babel-key-bindings)
  18202. (define-key org-babel-map (car pair) (cdr pair)))
  18203. ;;; Extra keys for tty access.
  18204. ;; We only set them when really needed because otherwise the
  18205. ;; menus don't show the simple keys
  18206. (when (or org-use-extra-keys (not window-system))
  18207. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18208. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18209. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18210. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18211. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18212. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18213. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18214. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18215. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18216. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18217. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18218. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18219. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18220. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18221. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18222. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18223. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18224. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18225. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18226. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18227. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18228. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18229. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18230. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18231. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18232. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18233. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18234. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18235. ;; All the other keys
  18236. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18237. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18238. (if (boundp 'narrow-map)
  18239. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18240. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18241. (if (boundp 'narrow-map)
  18242. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18243. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18244. (if (boundp 'narrow-map)
  18245. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18246. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18247. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18248. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18249. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18250. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18251. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18252. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18253. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18254. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18255. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18256. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18257. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18258. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18259. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18260. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18261. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18262. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18263. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18264. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18265. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18266. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18267. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18268. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18269. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18270. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18271. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18272. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18273. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18274. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18275. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18276. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18277. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18278. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18279. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18280. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18281. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18282. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18283. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18284. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18285. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18286. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18287. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18288. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18289. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18290. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18291. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18292. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18293. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18294. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18295. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18296. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18297. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18298. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18299. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18300. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18301. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18302. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18303. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18304. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18305. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18306. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18307. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18308. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18309. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18310. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18311. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18312. (org-defkey org-mode-map "\C-m" 'org-return)
  18313. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18314. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18315. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18316. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18317. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18318. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18319. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18320. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18321. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18322. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18323. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18324. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18325. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18326. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18327. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18328. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18329. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18330. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18331. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18332. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18333. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18334. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18335. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18336. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18337. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18338. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18339. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18340. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18341. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18342. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18343. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18344. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18345. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18346. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18347. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18348. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18349. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18350. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18351. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18352. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18353. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18354. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18355. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18356. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18357. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18358. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18359. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18360. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18361. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18362. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18363. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18364. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18365. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18366. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18367. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18368. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18369. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18370. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18371. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18372. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18373. (defconst org-speed-commands-default
  18374. '(
  18375. ("Outline Navigation")
  18376. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18377. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18378. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18379. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18380. ("F" . org-next-block)
  18381. ("B" . org-previous-block)
  18382. ("u" . (org-speed-move-safe 'outline-up-heading))
  18383. ("j" . org-goto)
  18384. ("g" . (org-refile t))
  18385. ("Outline Visibility")
  18386. ("c" . org-cycle)
  18387. ("C" . org-shifttab)
  18388. (" " . org-display-outline-path)
  18389. ("s" . org-narrow-to-subtree)
  18390. ("=" . org-columns)
  18391. ("Outline Structure Editing")
  18392. ("U" . org-metaup)
  18393. ("D" . org-metadown)
  18394. ("r" . org-metaright)
  18395. ("l" . org-metaleft)
  18396. ("R" . org-shiftmetaright)
  18397. ("L" . org-shiftmetaleft)
  18398. ("i" . (progn (forward-char 1) (call-interactively
  18399. 'org-insert-heading-respect-content)))
  18400. ("^" . org-sort)
  18401. ("w" . org-refile)
  18402. ("a" . org-archive-subtree-default-with-confirmation)
  18403. ("@" . org-mark-subtree)
  18404. ("#" . org-toggle-comment)
  18405. ("Clock Commands")
  18406. ("I" . org-clock-in)
  18407. ("O" . org-clock-out)
  18408. ("Meta Data Editing")
  18409. ("t" . org-todo)
  18410. ("," . (org-priority))
  18411. ("0" . (org-priority ?\ ))
  18412. ("1" . (org-priority ?A))
  18413. ("2" . (org-priority ?B))
  18414. ("3" . (org-priority ?C))
  18415. (":" . org-set-tags-command)
  18416. ("e" . org-set-effort)
  18417. ("E" . org-inc-effort)
  18418. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18419. (org-entry-put (point) "APPT_WARNTIME" m)))
  18420. ("Agenda Views etc")
  18421. ("v" . org-agenda)
  18422. ("/" . org-sparse-tree)
  18423. ("Misc")
  18424. ("o" . org-open-at-point)
  18425. ("?" . org-speed-command-help)
  18426. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18427. (">" . (org-agenda-remove-restriction-lock))
  18428. )
  18429. "The default speed commands.")
  18430. (defun org-print-speed-command (e)
  18431. (if (> (length (car e)) 1)
  18432. (progn
  18433. (princ "\n")
  18434. (princ (car e))
  18435. (princ "\n")
  18436. (princ (make-string (length (car e)) ?-))
  18437. (princ "\n"))
  18438. (princ (car e))
  18439. (princ " ")
  18440. (if (symbolp (cdr e))
  18441. (princ (symbol-name (cdr e)))
  18442. (prin1 (cdr e)))
  18443. (princ "\n")))
  18444. (defun org-speed-command-help ()
  18445. "Show the available speed commands."
  18446. (interactive)
  18447. (if (not org-use-speed-commands)
  18448. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18449. (with-output-to-temp-buffer "*Help*"
  18450. (princ "User-defined Speed commands\n===========================\n")
  18451. (mapc #'org-print-speed-command org-speed-commands-user)
  18452. (princ "\n")
  18453. (princ "Built-in Speed commands\n=======================\n")
  18454. (mapc #'org-print-speed-command org-speed-commands-default))
  18455. (with-current-buffer "*Help*"
  18456. (setq truncate-lines t))))
  18457. (defun org-speed-move-safe (cmd)
  18458. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18459. If not, return to the original position and throw an error."
  18460. (interactive)
  18461. (let ((pos (point)))
  18462. (call-interactively cmd)
  18463. (unless (and (bolp) (org-at-heading-p))
  18464. (goto-char pos)
  18465. (error "Boundary reached while executing %s" cmd))))
  18466. (defvar org-self-insert-command-undo-counter 0)
  18467. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18468. (defvar org-speed-command nil)
  18469. (defun org-speed-command-activate (keys)
  18470. "Hook for activating single-letter speed commands.
  18471. `org-speed-commands-default' specifies a minimal command set.
  18472. Use `org-speed-commands-user' for further customization."
  18473. (when (or (and (bolp) (looking-at org-outline-regexp))
  18474. (and (functionp org-use-speed-commands)
  18475. (funcall org-use-speed-commands)))
  18476. (cdr (assoc keys (append org-speed-commands-user
  18477. org-speed-commands-default)))))
  18478. (defun org-babel-speed-command-activate (keys)
  18479. "Hook for activating single-letter code block commands."
  18480. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18481. (cdr (assoc keys org-babel-key-bindings))))
  18482. (defcustom org-speed-command-hook
  18483. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18484. "Hook for activating speed commands at strategic locations.
  18485. Hook functions are called in sequence until a valid handler is
  18486. found.
  18487. Each hook takes a single argument, a user-pressed command key
  18488. which is also a `self-insert-command' from the global map.
  18489. Within the hook, examine the cursor position and the command key
  18490. and return nil or a valid handler as appropriate. Handler could
  18491. be one of an interactive command, a function, or a form.
  18492. Set `org-use-speed-commands' to non-nil value to enable this
  18493. hook. The default setting is `org-speed-command-activate'."
  18494. :group 'org-structure
  18495. :version "24.1"
  18496. :type 'hook)
  18497. (defun org-self-insert-command (N)
  18498. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18499. If the cursor is in a table looking at whitespace, the whitespace is
  18500. overwritten, and the table is not marked as requiring realignment."
  18501. (interactive "p")
  18502. (org-check-before-invisible-edit 'insert)
  18503. (cond
  18504. ((and org-use-speed-commands
  18505. (let ((kv (this-command-keys-vector)))
  18506. (setq org-speed-command
  18507. (run-hook-with-args-until-success
  18508. 'org-speed-command-hook
  18509. (make-string 1 (aref kv (1- (length kv))))))))
  18510. (cond
  18511. ((commandp org-speed-command)
  18512. (setq this-command org-speed-command)
  18513. (call-interactively org-speed-command))
  18514. ((functionp org-speed-command)
  18515. (funcall org-speed-command))
  18516. ((and org-speed-command (listp org-speed-command))
  18517. (eval org-speed-command))
  18518. (t (let (org-use-speed-commands)
  18519. (call-interactively 'org-self-insert-command)))))
  18520. ((and
  18521. (org-at-table-p)
  18522. (progn
  18523. ;; Check if we blank the field, and if that triggers align.
  18524. (and (featurep 'org-table) org-table-auto-blank-field
  18525. (memq last-command
  18526. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18527. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18528. ;; Got extra space, this field does not determine
  18529. ;; column width.
  18530. (let (org-table-may-need-update) (org-table-blank-field))
  18531. ;; No extra space, this field may determine column
  18532. ;; width.
  18533. (org-table-blank-field)))
  18534. t)
  18535. (eq N 1)
  18536. (looking-at "[^|\n]* \\( \\)|"))
  18537. ;; There is room for insertion without re-aligning the table.
  18538. (delete-region (match-beginning 1) (match-end 1))
  18539. (self-insert-command N))
  18540. (t
  18541. (setq org-table-may-need-update t)
  18542. (self-insert-command N)
  18543. (org-fix-tags-on-the-fly)
  18544. (when org-self-insert-cluster-for-undo
  18545. (if (not (eq last-command 'org-self-insert-command))
  18546. (setq org-self-insert-command-undo-counter 1)
  18547. (if (>= org-self-insert-command-undo-counter 20)
  18548. (setq org-self-insert-command-undo-counter 1)
  18549. (and (> org-self-insert-command-undo-counter 0)
  18550. buffer-undo-list (listp buffer-undo-list)
  18551. (not (cadr buffer-undo-list)) ; remove nil entry
  18552. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18553. (setq org-self-insert-command-undo-counter
  18554. (1+ org-self-insert-command-undo-counter))))))))
  18555. (defun org-check-before-invisible-edit (kind)
  18556. "Check is editing if kind KIND would be dangerous with invisible text around.
  18557. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18558. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18559. (when (and org-catch-invisible-edits
  18560. (or (not (boundp 'visible-mode)) (not visible-mode))
  18561. (or (get-char-property (point) 'invisible)
  18562. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18563. ;; OK, we need to take a closer look
  18564. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18565. (invisible-before-point (unless (bobp) (get-char-property
  18566. (1- (point)) 'invisible)))
  18567. (border-and-ok-direction
  18568. (or
  18569. ;; Check if we are acting predictably before invisible text
  18570. (and invisible-at-point (not invisible-before-point)
  18571. (memq kind '(insert delete-backward)))
  18572. ;; Check if we are acting predictably after invisible text
  18573. ;; This works not well, and I have turned it off. It seems
  18574. ;; better to always show and stop after invisible text.
  18575. ;; (and (not invisible-at-point) invisible-before-point
  18576. ;; (memq kind '(insert delete)))
  18577. )))
  18578. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18579. (memq invisible-before-point '(outline org-hide-block t)))
  18580. (when (eq org-catch-invisible-edits 'error)
  18581. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18582. (if (and org-custom-properties-overlays
  18583. (y-or-n-p "Display invisible properties in this buffer? "))
  18584. (org-toggle-custom-properties-visibility)
  18585. ;; Make the area visible
  18586. (save-excursion
  18587. (when invisible-before-point
  18588. (goto-char (previous-single-char-property-change
  18589. (point) 'invisible)))
  18590. (outline-show-subtree))
  18591. (cond
  18592. ((eq org-catch-invisible-edits 'show)
  18593. ;; That's it, we do the edit after showing
  18594. (message
  18595. "Unfolding invisible region around point before editing")
  18596. (sit-for 1))
  18597. ((and (eq org-catch-invisible-edits 'smart)
  18598. border-and-ok-direction)
  18599. (message "Unfolding invisible region around point before editing"))
  18600. (t
  18601. ;; Don't do the edit, make the user repeat it in full visibility
  18602. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18603. (defun org-fix-tags-on-the-fly ()
  18604. (when (and (equal (char-after (point-at-bol)) ?*)
  18605. (org-at-heading-p))
  18606. (org-align-tags-here org-tags-column)))
  18607. (defun org-delete-backward-char (N)
  18608. "Like `delete-backward-char', insert whitespace at field end in tables.
  18609. When deleting backwards, in tables this function will insert whitespace in
  18610. front of the next \"|\" separator, to keep the table aligned. The table will
  18611. still be marked for re-alignment if the field did fill the entire column,
  18612. because, in this case the deletion might narrow the column."
  18613. (interactive "p")
  18614. (save-match-data
  18615. (org-check-before-invisible-edit 'delete-backward)
  18616. (if (and (org-at-table-p)
  18617. (eq N 1)
  18618. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18619. (looking-at ".*?|"))
  18620. (let ((pos (point))
  18621. (noalign (looking-at "[^|\n\r]* |"))
  18622. (c org-table-may-need-update))
  18623. (backward-delete-char N)
  18624. (unless overwrite-mode
  18625. (skip-chars-forward "^|")
  18626. (insert " ")
  18627. (goto-char (1- pos)))
  18628. ;; noalign: if there were two spaces at the end, this field
  18629. ;; does not determine the width of the column.
  18630. (when noalign (setq org-table-may-need-update c)))
  18631. (backward-delete-char N)
  18632. (org-fix-tags-on-the-fly))))
  18633. (defun org-delete-char (N)
  18634. "Like `delete-char', but insert whitespace at field end in tables.
  18635. When deleting characters, in tables this function will insert whitespace in
  18636. front of the next \"|\" separator, to keep the table aligned. The table will
  18637. still be marked for re-alignment if the field did fill the entire column,
  18638. because, in this case the deletion might narrow the column."
  18639. (interactive "p")
  18640. (save-match-data
  18641. (org-check-before-invisible-edit 'delete)
  18642. (if (and (org-at-table-p)
  18643. (not (bolp))
  18644. (not (= (char-after) ?|))
  18645. (eq N 1))
  18646. (if (looking-at ".*?|")
  18647. (let ((pos (point))
  18648. (noalign (looking-at "[^|\n\r]* |"))
  18649. (c org-table-may-need-update))
  18650. (replace-match
  18651. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18652. (goto-char pos)
  18653. ;; noalign: if there were two spaces at the end, this field
  18654. ;; does not determine the width of the column.
  18655. (when noalign (setq org-table-may-need-update c)))
  18656. (delete-char N))
  18657. (delete-char N)
  18658. (org-fix-tags-on-the-fly))))
  18659. ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
  18660. (put 'org-self-insert-command 'delete-selection
  18661. (lambda ()
  18662. (not (run-hook-with-args-until-success
  18663. 'self-insert-uses-region-functions))))
  18664. (put 'orgtbl-self-insert-command 'delete-selection
  18665. (lambda ()
  18666. (not (run-hook-with-args-until-success
  18667. 'self-insert-uses-region-functions))))
  18668. (put 'org-delete-char 'delete-selection 'supersede)
  18669. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18670. (put 'org-yank 'delete-selection 'yank)
  18671. ;; Make `flyspell-mode' delay after some commands
  18672. (put 'org-self-insert-command 'flyspell-delayed t)
  18673. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18674. (put 'org-delete-char 'flyspell-delayed t)
  18675. (put 'org-delete-backward-char 'flyspell-delayed t)
  18676. ;; Make pabbrev-mode expand after org-mode commands
  18677. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18678. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18679. (defun org-remap (map &rest commands)
  18680. "In MAP, remap the functions given in COMMANDS.
  18681. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18682. (let (new old)
  18683. (while commands
  18684. (setq old (pop commands) new (pop commands))
  18685. (if (fboundp 'command-remapping)
  18686. (org-defkey map (vector 'remap old) new)
  18687. (substitute-key-definition old new map global-map)))))
  18688. (defun org-transpose-words ()
  18689. "Transpose words for Org.
  18690. This uses the `org-mode-transpose-word-syntax-table' syntax
  18691. table, which interprets characters in `org-emphasis-alist' as
  18692. word constituents."
  18693. (interactive)
  18694. (with-syntax-table org-mode-transpose-word-syntax-table
  18695. (call-interactively 'transpose-words)))
  18696. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18697. (when (eq org-enable-table-editor 'optimized)
  18698. ;; If the user wants maximum table support, we need to hijack
  18699. ;; some standard editing functions
  18700. (org-remap org-mode-map
  18701. 'self-insert-command 'org-self-insert-command
  18702. 'delete-char 'org-delete-char
  18703. 'delete-backward-char 'org-delete-backward-char)
  18704. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18705. (defvar org-ctrl-c-ctrl-c-hook nil
  18706. "Hook for functions attaching themselves to `C-c C-c'.
  18707. This can be used to add additional functionality to the C-c C-c
  18708. key which executes context-dependent commands. This hook is run
  18709. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18710. run after the last test.
  18711. Each function will be called with no arguments. The function
  18712. must check if the context is appropriate for it to act. If yes,
  18713. it should do its thing and then return a non-nil value. If the
  18714. context is wrong, just do nothing and return nil.")
  18715. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18716. "Hook for functions attaching themselves to `C-c C-c'.
  18717. This can be used to add additional functionality to the C-c C-c
  18718. key which executes context-dependent commands. This hook is run
  18719. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18720. before the first test.
  18721. Each function will be called with no arguments. The function
  18722. must check if the context is appropriate for it to act. If yes,
  18723. it should do its thing and then return a non-nil value. If the
  18724. context is wrong, just do nothing and return nil.")
  18725. (defvar org-tab-first-hook nil
  18726. "Hook for functions to attach themselves to TAB.
  18727. See `org-ctrl-c-ctrl-c-hook' for more information.
  18728. This hook runs as the first action when TAB is pressed, even before
  18729. `org-cycle' messes around with the `outline-regexp' to cater for
  18730. inline tasks and plain list item folding.
  18731. If any function in this hook returns t, any other actions that
  18732. would have been caused by TAB (such as table field motion or visibility
  18733. cycling) will not occur.")
  18734. (defvar org-tab-after-check-for-table-hook nil
  18735. "Hook for functions to attach themselves to TAB.
  18736. See `org-ctrl-c-ctrl-c-hook' for more information.
  18737. This hook runs after it has been established that the cursor is not in a
  18738. table, but before checking if the cursor is in a headline or if global cycling
  18739. should be done.
  18740. If any function in this hook returns t, not other actions like visibility
  18741. cycling will be done.")
  18742. (defvar org-tab-after-check-for-cycling-hook nil
  18743. "Hook for functions to attach themselves to TAB.
  18744. See `org-ctrl-c-ctrl-c-hook' for more information.
  18745. This hook runs after it has been established that not table field motion and
  18746. not visibility should be done because of current context. This is probably
  18747. the place where a package like yasnippets can hook in.")
  18748. (defvar org-tab-before-tab-emulation-hook nil
  18749. "Hook for functions to attach themselves to TAB.
  18750. See `org-ctrl-c-ctrl-c-hook' for more information.
  18751. This hook runs after every other options for TAB have been exhausted, but
  18752. before indentation and \t insertion takes place.")
  18753. (defvar org-metaleft-hook nil
  18754. "Hook for functions attaching themselves to `M-left'.
  18755. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18756. (defvar org-metaright-hook nil
  18757. "Hook for functions attaching themselves to `M-right'.
  18758. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18759. (defvar org-metaup-hook nil
  18760. "Hook for functions attaching themselves to `M-up'.
  18761. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18762. (defvar org-metadown-hook nil
  18763. "Hook for functions attaching themselves to `M-down'.
  18764. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18765. (defvar org-shiftmetaleft-hook nil
  18766. "Hook for functions attaching themselves to `M-S-left'.
  18767. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18768. (defvar org-shiftmetaright-hook nil
  18769. "Hook for functions attaching themselves to `M-S-right'.
  18770. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18771. (defvar org-shiftmetaup-hook nil
  18772. "Hook for functions attaching themselves to `M-S-up'.
  18773. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18774. (defvar org-shiftmetadown-hook nil
  18775. "Hook for functions attaching themselves to `M-S-down'.
  18776. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18777. (defvar org-metareturn-hook nil
  18778. "Hook for functions attaching themselves to `M-RET'.
  18779. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18780. (defvar org-shiftup-hook nil
  18781. "Hook for functions attaching themselves to `S-up'.
  18782. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18783. (defvar org-shiftup-final-hook nil
  18784. "Hook for functions attaching themselves to `S-up'.
  18785. This one runs after all other options except shift-select have been excluded.
  18786. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18787. (defvar org-shiftdown-hook nil
  18788. "Hook for functions attaching themselves to `S-down'.
  18789. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18790. (defvar org-shiftdown-final-hook nil
  18791. "Hook for functions attaching themselves to `S-down'.
  18792. This one runs after all other options except shift-select have been excluded.
  18793. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18794. (defvar org-shiftleft-hook nil
  18795. "Hook for functions attaching themselves to `S-left'.
  18796. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18797. (defvar org-shiftleft-final-hook nil
  18798. "Hook for functions attaching themselves to `S-left'.
  18799. This one runs after all other options except shift-select have been excluded.
  18800. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18801. (defvar org-shiftright-hook nil
  18802. "Hook for functions attaching themselves to `S-right'.
  18803. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18804. (defvar org-shiftright-final-hook nil
  18805. "Hook for functions attaching themselves to `S-right'.
  18806. This one runs after all other options except shift-select have been excluded.
  18807. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18808. (defun org-modifier-cursor-error ()
  18809. "Throw an error, a modified cursor command was applied in wrong context."
  18810. (user-error "This command is active in special context like tables, headlines or items"))
  18811. (defun org-shiftselect-error ()
  18812. "Throw an error because Shift-Cursor command was applied in wrong context."
  18813. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18814. (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
  18815. (user-error "This command works only in special context like headlines or timestamps")))
  18816. (defun org-call-for-shift-select (cmd)
  18817. (let ((this-command-keys-shift-translated t))
  18818. (call-interactively cmd)))
  18819. (defun org-shifttab (&optional arg)
  18820. "Global visibility cycling or move to previous table field.
  18821. Call `org-table-previous-field' within a table.
  18822. When ARG is nil, cycle globally through visibility states.
  18823. When ARG is a numeric prefix, show contents of this level."
  18824. (interactive "P")
  18825. (cond
  18826. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18827. ((integerp arg)
  18828. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18829. (message "Content view to level: %d" arg)
  18830. (org-content (prefix-numeric-value arg2))
  18831. (org-cycle-show-empty-lines t)
  18832. (setq org-cycle-global-status 'overview)))
  18833. (t (call-interactively 'org-global-cycle))))
  18834. (defun org-shiftmetaleft ()
  18835. "Promote subtree or delete table column.
  18836. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18837. `org-table-delete-column', depending on context. See the
  18838. individual commands for more information."
  18839. (interactive)
  18840. (cond
  18841. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18842. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18843. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18844. ((if (not (org-region-active-p)) (org-at-item-p)
  18845. (save-excursion (goto-char (region-beginning))
  18846. (org-at-item-p)))
  18847. (call-interactively 'org-outdent-item-tree))
  18848. (t (org-modifier-cursor-error))))
  18849. (defun org-shiftmetaright ()
  18850. "Demote subtree or insert table column.
  18851. Calls `org-demote-subtree', `org-indent-item-tree', or
  18852. `org-table-insert-column', depending on context. See the
  18853. individual commands for more information."
  18854. (interactive)
  18855. (cond
  18856. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18857. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18858. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18859. ((if (not (org-region-active-p)) (org-at-item-p)
  18860. (save-excursion (goto-char (region-beginning))
  18861. (org-at-item-p)))
  18862. (call-interactively 'org-indent-item-tree))
  18863. (t (org-modifier-cursor-error))))
  18864. (defun org-shiftmetaup (&optional _arg)
  18865. "Drag the line at point up.
  18866. In a table, kill the current row.
  18867. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18868. but also adjust the previous clocked item in the clock history.
  18869. Everywhere else, drag the line at point up."
  18870. (interactive "P")
  18871. (cond
  18872. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18873. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18874. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18875. (call-interactively 'org-timestamp-up)))
  18876. (t (call-interactively 'org-drag-line-backward))))
  18877. (defun org-shiftmetadown (&optional _arg)
  18878. "Drag the line at point down.
  18879. In a table, insert an empty row at the current line.
  18880. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18881. but also adjust the previous clocked item in the clock history.
  18882. Everywhere else, drag the line at point down."
  18883. (interactive "P")
  18884. (cond
  18885. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18886. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18887. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18888. (call-interactively 'org-timestamp-down)))
  18889. (t (call-interactively 'org-drag-line-forward))))
  18890. (defsubst org-hidden-tree-error ()
  18891. (user-error
  18892. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18893. (defun org-metaleft (&optional _arg)
  18894. "Promote heading, list item at point or move table column left.
  18895. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18896. depending on context. With no specific context, calls the Emacs
  18897. default `backward-word'. See the individual commands for more
  18898. information.
  18899. This function runs the hook `org-metaleft-hook' as a first step,
  18900. and returns at first non-nil value."
  18901. (interactive "P")
  18902. (cond
  18903. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18904. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18905. ((org-with-limited-levels
  18906. (or (org-at-heading-p)
  18907. (and (org-region-active-p)
  18908. (save-excursion
  18909. (goto-char (region-beginning))
  18910. (org-at-heading-p)))))
  18911. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18912. (call-interactively 'org-do-promote))
  18913. ;; At an inline task.
  18914. ((org-at-heading-p)
  18915. (call-interactively 'org-inlinetask-promote))
  18916. ((or (org-at-item-p)
  18917. (and (org-region-active-p)
  18918. (save-excursion
  18919. (goto-char (region-beginning))
  18920. (org-at-item-p))))
  18921. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18922. (call-interactively 'org-outdent-item))
  18923. (t (call-interactively 'backward-word))))
  18924. (defun org-metaright (&optional _arg)
  18925. "Demote heading, list item at point or move table column right.
  18926. In front of a drawer or a block keyword, indent it correctly.
  18927. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18928. `org-indnet-drawer' or `org-indent-block' depending on context.
  18929. With no specific context, calls the Emacs default `forward-word'.
  18930. See the individual commands for more information.
  18931. This function runs the hook `org-metaright-hook' as a first step,
  18932. and returns at first non-nil value."
  18933. (interactive "P")
  18934. (cond
  18935. ((run-hook-with-args-until-success 'org-metaright-hook))
  18936. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18937. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18938. ((org-at-block-p) (call-interactively 'org-indent-block))
  18939. ((org-with-limited-levels
  18940. (or (org-at-heading-p)
  18941. (and (org-region-active-p)
  18942. (save-excursion
  18943. (goto-char (region-beginning))
  18944. (org-at-heading-p)))))
  18945. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18946. (call-interactively 'org-do-demote))
  18947. ;; At an inline task.
  18948. ((org-at-heading-p)
  18949. (call-interactively 'org-inlinetask-demote))
  18950. ((or (org-at-item-p)
  18951. (and (org-region-active-p)
  18952. (save-excursion
  18953. (goto-char (region-beginning))
  18954. (org-at-item-p))))
  18955. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18956. (call-interactively 'org-indent-item))
  18957. (t (call-interactively 'forward-word))))
  18958. (defun org-check-for-hidden (what)
  18959. "Check if there are hidden headlines/items in the current visual line.
  18960. WHAT can be either `headlines' or `items'. If the current line is
  18961. an outline or item heading and it has a folded subtree below it,
  18962. this function returns t, nil otherwise."
  18963. (let ((re (cond
  18964. ((eq what 'headlines) org-outline-regexp-bol)
  18965. ((eq what 'items) (org-item-beginning-re))
  18966. (t (error "This should not happen"))))
  18967. beg end)
  18968. (save-excursion
  18969. (catch 'exit
  18970. (unless (org-region-active-p)
  18971. (setq beg (point-at-bol))
  18972. (beginning-of-line 2)
  18973. (while (and (not (eobp)) ;; this is like `next-line'
  18974. (get-char-property (1- (point)) 'invisible))
  18975. (beginning-of-line 2))
  18976. (setq end (point))
  18977. (goto-char beg)
  18978. (goto-char (point-at-eol))
  18979. (setq end (max end (point)))
  18980. (while (re-search-forward re end t)
  18981. (when (get-char-property (match-beginning 0) 'invisible)
  18982. (throw 'exit t))))
  18983. nil))))
  18984. (defun org-metaup (&optional _arg)
  18985. "Move subtree up or move table row up.
  18986. Calls `org-move-subtree-up' or `org-table-move-row' or
  18987. `org-move-item-up', depending on context. See the individual commands
  18988. for more information."
  18989. (interactive "P")
  18990. (cond
  18991. ((run-hook-with-args-until-success 'org-metaup-hook))
  18992. ((org-region-active-p)
  18993. (let* ((a (min (region-beginning) (region-end)))
  18994. (b (1- (max (region-beginning) (region-end))))
  18995. (c (save-excursion (goto-char a)
  18996. (move-beginning-of-line 0)))
  18997. (d (save-excursion (goto-char a)
  18998. (move-end-of-line 0) (point))))
  18999. (transpose-regions a b c d)
  19000. (goto-char c)))
  19001. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  19002. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  19003. ((org-at-item-p) (call-interactively 'org-move-item-up))
  19004. (t (org-drag-element-backward))))
  19005. (defun org-metadown (&optional _arg)
  19006. "Move subtree down or move table row down.
  19007. Calls `org-move-subtree-down' or `org-table-move-row' or
  19008. `org-move-item-down', depending on context. See the individual
  19009. commands for more information."
  19010. (interactive "P")
  19011. (cond
  19012. ((run-hook-with-args-until-success 'org-metadown-hook))
  19013. ((org-region-active-p)
  19014. (let* ((a (min (region-beginning) (region-end)))
  19015. (b (max (region-beginning) (region-end)))
  19016. (c (save-excursion (goto-char b)
  19017. (move-beginning-of-line 1)))
  19018. (d (save-excursion (goto-char b)
  19019. (move-end-of-line 1) (1+ (point)))))
  19020. (transpose-regions a b c d)
  19021. (goto-char d)))
  19022. ((org-at-table-p) (call-interactively 'org-table-move-row))
  19023. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  19024. ((org-at-item-p) (call-interactively 'org-move-item-down))
  19025. (t (org-drag-element-forward))))
  19026. (defun org-shiftup (&optional arg)
  19027. "Increase item in timestamp or increase priority of current headline.
  19028. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  19029. depending on context. See the individual commands for more information."
  19030. (interactive "P")
  19031. (cond
  19032. ((run-hook-with-args-until-success 'org-shiftup-hook))
  19033. ((and org-support-shift-select (org-region-active-p))
  19034. (org-call-for-shift-select 'previous-line))
  19035. ((org-at-timestamp-p t)
  19036. (call-interactively (if org-edit-timestamp-down-means-later
  19037. 'org-timestamp-down 'org-timestamp-up)))
  19038. ((and (not (eq org-support-shift-select 'always))
  19039. org-enable-priority-commands
  19040. (org-at-heading-p))
  19041. (call-interactively 'org-priority-up))
  19042. ((and (not org-support-shift-select) (org-at-item-p))
  19043. (call-interactively 'org-previous-item))
  19044. ((org-clocktable-try-shift 'up arg))
  19045. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  19046. (org-support-shift-select
  19047. (org-call-for-shift-select 'previous-line))
  19048. (t (org-shiftselect-error))))
  19049. (defun org-shiftdown (&optional arg)
  19050. "Decrease item in timestamp or decrease priority of current headline.
  19051. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  19052. depending on context. See the individual commands for more information."
  19053. (interactive "P")
  19054. (cond
  19055. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  19056. ((and org-support-shift-select (org-region-active-p))
  19057. (org-call-for-shift-select 'next-line))
  19058. ((org-at-timestamp-p t)
  19059. (call-interactively (if org-edit-timestamp-down-means-later
  19060. 'org-timestamp-up 'org-timestamp-down)))
  19061. ((and (not (eq org-support-shift-select 'always))
  19062. org-enable-priority-commands
  19063. (org-at-heading-p))
  19064. (call-interactively 'org-priority-down))
  19065. ((and (not org-support-shift-select) (org-at-item-p))
  19066. (call-interactively 'org-next-item))
  19067. ((org-clocktable-try-shift 'down arg))
  19068. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19069. (org-support-shift-select
  19070. (org-call-for-shift-select 'next-line))
  19071. (t (org-shiftselect-error))))
  19072. (defun org-shiftright (&optional arg)
  19073. "Cycle the thing at point or in the current line, depending on context.
  19074. Depending on context, this does one of the following:
  19075. - switch a timestamp at point one day into the future
  19076. - on a headline, switch to the next TODO keyword.
  19077. - on an item, switch entire list to the next bullet type
  19078. - on a property line, switch to the next allowed value
  19079. - on a clocktable definition line, move time block into the future"
  19080. (interactive "P")
  19081. (cond
  19082. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19083. ((and org-support-shift-select (org-region-active-p))
  19084. (org-call-for-shift-select 'forward-char))
  19085. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19086. ((and (not (eq org-support-shift-select 'always))
  19087. (org-at-heading-p))
  19088. (let ((org-inhibit-logging
  19089. (not org-treat-S-cursor-todo-selection-as-state-change))
  19090. (org-inhibit-blocking
  19091. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19092. (org-call-with-arg 'org-todo 'right)))
  19093. ((or (and org-support-shift-select
  19094. (not (eq org-support-shift-select 'always))
  19095. (org-at-item-bullet-p))
  19096. (and (not org-support-shift-select) (org-at-item-p)))
  19097. (org-call-with-arg 'org-cycle-list-bullet nil))
  19098. ((and (not (eq org-support-shift-select 'always))
  19099. (org-at-property-p))
  19100. (call-interactively 'org-property-next-allowed-value))
  19101. ((org-clocktable-try-shift 'right arg))
  19102. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19103. (org-support-shift-select
  19104. (org-call-for-shift-select 'forward-char))
  19105. (t (org-shiftselect-error))))
  19106. (defun org-shiftleft (&optional arg)
  19107. "Cycle the thing at point or in the current line, depending on context.
  19108. Depending on context, this does one of the following:
  19109. - switch a timestamp at point one day into the past
  19110. - on a headline, switch to the previous TODO keyword.
  19111. - on an item, switch entire list to the previous bullet type
  19112. - on a property line, switch to the previous allowed value
  19113. - on a clocktable definition line, move time block into the past"
  19114. (interactive "P")
  19115. (cond
  19116. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19117. ((and org-support-shift-select (org-region-active-p))
  19118. (org-call-for-shift-select 'backward-char))
  19119. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19120. ((and (not (eq org-support-shift-select 'always))
  19121. (org-at-heading-p))
  19122. (let ((org-inhibit-logging
  19123. (not org-treat-S-cursor-todo-selection-as-state-change))
  19124. (org-inhibit-blocking
  19125. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19126. (org-call-with-arg 'org-todo 'left)))
  19127. ((or (and org-support-shift-select
  19128. (not (eq org-support-shift-select 'always))
  19129. (org-at-item-bullet-p))
  19130. (and (not org-support-shift-select) (org-at-item-p)))
  19131. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19132. ((and (not (eq org-support-shift-select 'always))
  19133. (org-at-property-p))
  19134. (call-interactively 'org-property-previous-allowed-value))
  19135. ((org-clocktable-try-shift 'left arg))
  19136. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19137. (org-support-shift-select
  19138. (org-call-for-shift-select 'backward-char))
  19139. (t (org-shiftselect-error))))
  19140. (defun org-shiftcontrolright ()
  19141. "Switch to next TODO set."
  19142. (interactive)
  19143. (cond
  19144. ((and org-support-shift-select (org-region-active-p))
  19145. (org-call-for-shift-select 'forward-word))
  19146. ((and (not (eq org-support-shift-select 'always))
  19147. (org-at-heading-p))
  19148. (org-call-with-arg 'org-todo 'nextset))
  19149. (org-support-shift-select
  19150. (org-call-for-shift-select 'forward-word))
  19151. (t (org-shiftselect-error))))
  19152. (defun org-shiftcontrolleft ()
  19153. "Switch to previous TODO set."
  19154. (interactive)
  19155. (cond
  19156. ((and org-support-shift-select (org-region-active-p))
  19157. (org-call-for-shift-select 'backward-word))
  19158. ((and (not (eq org-support-shift-select 'always))
  19159. (org-at-heading-p))
  19160. (org-call-with-arg 'org-todo 'previousset))
  19161. (org-support-shift-select
  19162. (org-call-for-shift-select 'backward-word))
  19163. (t (org-shiftselect-error))))
  19164. (defun org-shiftcontrolup (&optional n)
  19165. "Change timestamps synchronously up in CLOCK log lines.
  19166. Optional argument N tells to change by that many units."
  19167. (interactive "P")
  19168. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19169. (let (org-support-shift-select)
  19170. (org-clock-timestamps-up n))
  19171. (user-error "Not at a clock log")))
  19172. (defun org-shiftcontroldown (&optional n)
  19173. "Change timestamps synchronously down in CLOCK log lines.
  19174. Optional argument N tells to change by that many units."
  19175. (interactive "P")
  19176. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19177. (let (org-support-shift-select)
  19178. (org-clock-timestamps-down n))
  19179. (user-error "Not at a clock log")))
  19180. (defun org-increase-number-at-point (&optional inc)
  19181. "Increment the number at point.
  19182. With an optional prefix numeric argument INC, increment using
  19183. this numeric value."
  19184. (interactive "p")
  19185. (if (not (number-at-point))
  19186. (user-error "Not on a number")
  19187. (unless inc (setq inc 1))
  19188. (let ((pos (point))
  19189. (beg (skip-chars-backward "-+^/*0-9eE."))
  19190. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19191. (setq nap (buffer-substring-no-properties
  19192. (+ pos beg) (+ pos beg end)))
  19193. (delete-region (+ pos beg) (+ pos beg end))
  19194. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19195. (when (org-at-table-p)
  19196. (org-table-align)
  19197. (org-table-end-of-field 1))))
  19198. (defun org-decrease-number-at-point (&optional inc)
  19199. "Decrement the number at point.
  19200. With an optional prefix numeric argument INC, decrement using
  19201. this numeric value."
  19202. (interactive "p")
  19203. (org-increase-number-at-point (- (or inc 1))))
  19204. (defun org-ctrl-c-ret ()
  19205. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19206. (interactive)
  19207. (cond
  19208. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19209. (t (call-interactively 'org-insert-heading))))
  19210. (defun org-find-visible ()
  19211. (let ((s (point)))
  19212. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19213. (get-char-property s 'invisible)))
  19214. s))
  19215. (defun org-find-invisible ()
  19216. (let ((s (point)))
  19217. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19218. (not (get-char-property s 'invisible))))
  19219. s))
  19220. (defun org-copy-visible (beg end)
  19221. "Copy the visible parts of the region."
  19222. (interactive "r")
  19223. (let (snippets s)
  19224. (save-excursion
  19225. (save-restriction
  19226. (narrow-to-region beg end)
  19227. (setq s (goto-char (point-min)))
  19228. (while (not (= (point) (point-max)))
  19229. (goto-char (org-find-invisible))
  19230. (push (buffer-substring s (point)) snippets)
  19231. (setq s (goto-char (org-find-visible))))))
  19232. (kill-new (apply 'concat (nreverse snippets)))))
  19233. (defun org-copy-special ()
  19234. "Copy region in table or copy current subtree.
  19235. Calls `org-table-copy' or `org-copy-subtree', depending on context.
  19236. See the individual commands for more information."
  19237. (interactive)
  19238. (call-interactively
  19239. (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
  19240. (defun org-cut-special ()
  19241. "Cut region in table or cut current subtree.
  19242. Calls `org-table-copy' or `org-cut-subtree', depending on context.
  19243. See the individual commands for more information."
  19244. (interactive)
  19245. (call-interactively
  19246. (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
  19247. (defun org-paste-special (arg)
  19248. "Paste rectangular region into table, or past subtree relative to level.
  19249. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19250. See the individual commands for more information."
  19251. (interactive "P")
  19252. (if (org-at-table-p)
  19253. (org-table-paste-rectangle)
  19254. (org-paste-subtree arg)))
  19255. (defsubst org-in-fixed-width-region-p ()
  19256. "Is point in a fixed-width region?"
  19257. (save-match-data
  19258. (eq 'fixed-width (org-element-type (org-element-at-point)))))
  19259. (defun org-edit-special (&optional arg)
  19260. "Call a special editor for the element at point.
  19261. When at a table, call the formula editor with `org-table-edit-formulas'.
  19262. When in a source code block, call `org-edit-src-code'.
  19263. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19264. When in an export block, call `org-edit-export-block'.
  19265. When at an #+INCLUDE keyword, visit the included file.
  19266. When at a footnote reference, call `org-edit-footnote-reference'
  19267. On a link, call `ffap' to visit the link at point.
  19268. Otherwise, return a user error."
  19269. (interactive "P")
  19270. (let ((element (org-element-at-point)))
  19271. (cl-assert (not buffer-read-only) nil
  19272. "Buffer is read-only: %s" (buffer-name))
  19273. (pcase (org-element-type element)
  19274. (`src-block
  19275. (if (not arg) (org-edit-src-code)
  19276. (let* ((info (org-babel-get-src-block-info))
  19277. (lang (nth 0 info))
  19278. (params (nth 2 info))
  19279. (session (cdr (assq :session params))))
  19280. (if (not session) (org-edit-src-code)
  19281. ;; At a src-block with a session and function called with
  19282. ;; an ARG: switch to the buffer related to the inferior
  19283. ;; process.
  19284. (switch-to-buffer
  19285. (funcall (intern (concat "org-babel-prep-session:" lang))
  19286. session params))))))
  19287. (`keyword
  19288. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19289. (org-open-link-from-string
  19290. (format "[[%s]]"
  19291. (expand-file-name
  19292. (let ((value (org-element-property :value element)))
  19293. (cond ((not (org-string-nw-p value))
  19294. (user-error "No file to edit"))
  19295. ((string-match "\\`\"\\(.*?\\)\"" value)
  19296. (match-string 1 value))
  19297. ((string-match "\\`[^ \t\"]\\S-*" value)
  19298. (match-string 0 value))
  19299. (t (user-error "No valid file specified")))))))
  19300. (user-error "No special environment to edit here")))
  19301. (`table
  19302. (if (eq (org-element-property :type element) 'table.el)
  19303. (org-edit-table.el)
  19304. (call-interactively 'org-table-edit-formulas)))
  19305. ;; Only Org tables contain `table-row' type elements.
  19306. (`table-row (call-interactively 'org-table-edit-formulas))
  19307. (`example-block (org-edit-src-code))
  19308. (`export-block (org-edit-export-block))
  19309. (`fixed-width (org-edit-fixed-width-region))
  19310. (_
  19311. ;; No notable element at point. Though, we may be at a link or
  19312. ;; a footnote reference, which are objects. Thus, scan deeper.
  19313. (let ((context (org-element-context element)))
  19314. (pcase (org-element-type context)
  19315. (`footnote-reference (org-edit-footnote-reference))
  19316. (`inline-src-block (org-edit-inline-src-code))
  19317. (`link (call-interactively #'ffap))
  19318. (_ (user-error "No special environment to edit here"))))))))
  19319. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19320. (defun org-ctrl-c-ctrl-c (&optional arg)
  19321. "Set tags in headline, or update according to changed information at point.
  19322. This command does many different things, depending on context:
  19323. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19324. this is what we do.
  19325. - If the cursor is on a statistics cookie, update it.
  19326. - If the cursor is in a headline, prompt for tags and insert them
  19327. into the current line, aligned to `org-tags-column'. When called
  19328. with prefix arg, realign all tags in the current buffer.
  19329. - If the cursor is in one of the special #+KEYWORD lines, this
  19330. triggers scanning the buffer for these lines and updating the
  19331. information.
  19332. - If the cursor is inside a table, realign the table. This command
  19333. works even if the automatic table editor has been turned off.
  19334. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19335. the entire table.
  19336. - If the cursor is at a footnote reference or definition, jump to
  19337. the corresponding definition or references, respectively.
  19338. - If the cursor is a the beginning of a dynamic block, update it.
  19339. - If the current buffer is a capture buffer, close note and file it.
  19340. - If the cursor is on a <<<target>>>, update radio targets and
  19341. corresponding links in this buffer.
  19342. - If the cursor is on a numbered item in a plain list, renumber the
  19343. ordered list.
  19344. - If the cursor is on a checkbox, toggle it.
  19345. - If the cursor is on a code block, evaluate it. The variable
  19346. `org-confirm-babel-evaluate' can be used to control prompting
  19347. before code block evaluation, by default every code block
  19348. evaluation requires confirmation. Code block evaluation can be
  19349. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19350. (interactive "P")
  19351. (cond
  19352. ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
  19353. org-occur-highlights)
  19354. (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19355. (org-remove-occur-highlights)
  19356. (message "Temporary highlights/overlays removed from current buffer"))
  19357. ((and (local-variable-p 'org-finish-function (current-buffer))
  19358. (fboundp org-finish-function))
  19359. (funcall org-finish-function))
  19360. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19361. (t
  19362. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  19363. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19364. (user-error "C-c C-c can do nothing useful at this location"))
  19365. (let* ((context (org-element-context))
  19366. (type (org-element-type context)))
  19367. (cl-case type
  19368. ;; When at a link, act according to the parent instead.
  19369. (link (setq context (org-element-property :parent context))
  19370. (setq type (org-element-type context)))
  19371. ;; Unsupported object types: refer to the first supported
  19372. ;; element or object containing it.
  19373. ((bold code entity export-snippet inline-babel-call inline-src-block
  19374. italic latex-fragment line-break macro strike-through subscript
  19375. superscript underline verbatim)
  19376. (setq context
  19377. (org-element-lineage
  19378. context '(radio-target paragraph verse-block table-cell)))))
  19379. ;; For convenience: at the first line of a paragraph on the
  19380. ;; same line as an item, apply function on that item instead.
  19381. (when (eq type 'paragraph)
  19382. (let ((parent (org-element-property :parent context)))
  19383. (when (and (eq (org-element-type parent) 'item)
  19384. (= (line-beginning-position)
  19385. (org-element-property :begin parent)))
  19386. (setq context parent type 'item))))
  19387. ;; Act according to type of element or object at point.
  19388. (cl-case type
  19389. (clock (org-clock-update-time-maybe))
  19390. (dynamic-block
  19391. (save-excursion
  19392. (goto-char (org-element-property :post-affiliated context))
  19393. (org-update-dblock)))
  19394. (footnote-definition
  19395. (goto-char (org-element-property :post-affiliated context))
  19396. (call-interactively 'org-footnote-action))
  19397. (footnote-reference (call-interactively 'org-footnote-action))
  19398. ((headline inlinetask)
  19399. (save-excursion (goto-char (org-element-property :begin context))
  19400. (call-interactively 'org-set-tags)))
  19401. (item
  19402. ;; At an item: a double C-u set checkbox to "[-]"
  19403. ;; unconditionally, whereas a single one will toggle its
  19404. ;; presence. Without a universal argument, if the item
  19405. ;; has a checkbox, toggle it. Otherwise repair the list.
  19406. (let* ((box (org-element-property :checkbox context))
  19407. (struct (org-element-property :structure context))
  19408. (old-struct (copy-tree struct))
  19409. (parents (org-list-parents-alist struct))
  19410. (prevs (org-list-prevs-alist struct))
  19411. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19412. (org-list-set-checkbox
  19413. (org-element-property :begin context) struct
  19414. (cond ((equal arg '(16)) "[-]")
  19415. ((and (not box) (equal arg '(4))) "[ ]")
  19416. ((or (not box) (equal arg '(4))) nil)
  19417. ((eq box 'on) "[ ]")
  19418. (t "[X]")))
  19419. ;; Mimic `org-list-write-struct' but with grabbing
  19420. ;; a return value from `org-list-struct-fix-box'.
  19421. (org-list-struct-fix-ind struct parents 2)
  19422. (org-list-struct-fix-item-end struct)
  19423. (org-list-struct-fix-bul struct prevs)
  19424. (org-list-struct-fix-ind struct parents)
  19425. (let ((block-item
  19426. (org-list-struct-fix-box struct parents prevs orderedp)))
  19427. (if (and box (equal struct old-struct))
  19428. (if (equal arg '(16))
  19429. (message "Checkboxes already reset")
  19430. (user-error "Cannot toggle this checkbox: %s"
  19431. (if (eq box 'on)
  19432. "all subitems checked"
  19433. "unchecked subitems")))
  19434. (org-list-struct-apply-struct struct old-struct)
  19435. (org-update-checkbox-count-maybe))
  19436. (when block-item
  19437. (message "Checkboxes were removed due to empty box at line %d"
  19438. (org-current-line block-item))))))
  19439. (keyword
  19440. (let ((org-inhibit-startup-visibility-stuff t)
  19441. (org-startup-align-all-tables nil))
  19442. (when (boundp 'org-table-coordinate-overlays)
  19443. (mapc #'delete-overlay org-table-coordinate-overlays)
  19444. (setq org-table-coordinate-overlays nil))
  19445. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19446. (message "Local setup has been refreshed"))
  19447. (plain-list
  19448. ;; At a plain list, with a double C-u argument, set
  19449. ;; checkboxes of each item to "[-]", whereas a single one
  19450. ;; will toggle their presence according to the state of the
  19451. ;; first item in the list. Without an argument, repair the
  19452. ;; list.
  19453. (let* ((begin (org-element-property :contents-begin context))
  19454. (beginm (move-marker (make-marker) begin))
  19455. (struct (org-element-property :structure context))
  19456. (old-struct (copy-tree struct))
  19457. (first-box (save-excursion
  19458. (goto-char begin)
  19459. (looking-at org-list-full-item-re)
  19460. (match-string-no-properties 3)))
  19461. (new-box (cond ((equal arg '(16)) "[-]")
  19462. ((equal arg '(4)) (unless first-box "[ ]"))
  19463. ((equal first-box "[X]") "[ ]")
  19464. (t "[X]"))))
  19465. (cond
  19466. (arg
  19467. (dolist (pos
  19468. (org-list-get-all-items
  19469. begin struct (org-list-prevs-alist struct)))
  19470. (org-list-set-checkbox pos struct new-box)))
  19471. ((and first-box (eq (point) begin))
  19472. ;; For convenience, when point is at bol on the first
  19473. ;; item of the list and no argument is provided, simply
  19474. ;; toggle checkbox of that item, if any.
  19475. (org-list-set-checkbox begin struct new-box)))
  19476. (org-list-write-struct
  19477. struct (org-list-parents-alist struct) old-struct)
  19478. (org-update-checkbox-count-maybe)
  19479. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19480. ((property-drawer node-property)
  19481. (call-interactively 'org-property-action))
  19482. ((radio-target target)
  19483. (call-interactively 'org-update-radio-target-regexp))
  19484. (statistics-cookie
  19485. (call-interactively 'org-update-statistics-cookies))
  19486. ((table table-cell table-row)
  19487. ;; At a table, recalculate every field and align it. Also
  19488. ;; send the table if necessary. If the table has
  19489. ;; a `table.el' type, just give up. At a table row or
  19490. ;; cell, maybe recalculate line but always align table.
  19491. (if (eq (org-element-property :type context) 'table.el)
  19492. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19493. Use \\[org-edit-special] to edit table.el tables"))
  19494. (let ((org-enable-table-editor t))
  19495. (if (or (eq type 'table)
  19496. ;; Check if point is at a TBLFM line.
  19497. (and (eq type 'table-row)
  19498. (= (point) (org-element-property :end context))))
  19499. (save-excursion
  19500. (if (org-at-TBLFM-p)
  19501. (progn (require 'org-table)
  19502. (org-table-calc-current-TBLFM))
  19503. (goto-char (org-element-property :contents-begin context))
  19504. (org-call-with-arg 'org-table-recalculate (or arg t))
  19505. (orgtbl-send-table 'maybe)))
  19506. (org-table-maybe-eval-formula)
  19507. (cond (arg (call-interactively 'org-table-recalculate))
  19508. ((org-table-maybe-recalculate-line))
  19509. (t (org-table-align)))))))
  19510. (timestamp (org-timestamp-change 0 'day))
  19511. (otherwise
  19512. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19513. (user-error
  19514. "C-c C-c can do nothing useful at this location")))))))))
  19515. (defun org-mode-restart ()
  19516. (interactive)
  19517. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19518. (funcall major-mode)
  19519. (hack-local-variables)
  19520. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19521. (org-indent-mode -1)))
  19522. (message "%s restarted" major-mode))
  19523. (defun org-kill-note-or-show-branches ()
  19524. "If this is a Note buffer, abort storing the note. Else call `show-branches'."
  19525. (interactive)
  19526. (if (not org-finish-function)
  19527. (progn
  19528. (outline-hide-subtree)
  19529. (call-interactively 'outline-show-branches))
  19530. (let ((org-note-abort t))
  19531. (funcall org-finish-function))))
  19532. (defun org-delete-indentation (&optional ARG)
  19533. "Join current line to previous and fix whitespace at join.
  19534. If previous line is a headline add to headline title. Otherwise
  19535. the function calls `delete-indentation'.
  19536. With argument, join this line to following line."
  19537. (interactive "*P")
  19538. (if (save-excursion
  19539. (if ARG (beginning-of-line)
  19540. (forward-line -1))
  19541. (looking-at org-complex-heading-regexp))
  19542. ;; At headline.
  19543. (let ((tags-column (when (match-beginning 5)
  19544. (save-excursion (goto-char (match-beginning 5))
  19545. (current-column))))
  19546. (string (concat " " (progn (when ARG (forward-line 1))
  19547. (org-trim (delete-and-extract-region
  19548. (line-beginning-position)
  19549. (line-end-position)))))))
  19550. (unless (bobp) (delete-region (point) (1- (point))))
  19551. (goto-char (or (match-end 4)
  19552. (match-beginning 5)
  19553. (match-end 0)))
  19554. (skip-chars-backward " \t")
  19555. (save-excursion (insert string))
  19556. ;; Adjust alignment of tags.
  19557. (when tags-column
  19558. (org-align-tags-here (if org-auto-align-tags
  19559. org-tags-column
  19560. tags-column))))
  19561. (delete-indentation ARG)))
  19562. (defun org-open-line (n)
  19563. "Insert a new row in tables, call `open-line' elsewhere.
  19564. If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
  19565. (interactive "*p")
  19566. (cond
  19567. ((not org-special-ctrl-o)
  19568. (open-line n))
  19569. ((org-at-table-p)
  19570. (org-table-insert-row))
  19571. (t
  19572. (open-line n))))
  19573. (defun org-return (&optional indent)
  19574. "Goto next table row or insert a newline.
  19575. Calls `org-table-next-row' or `newline', depending on context.
  19576. When optional INDENT argument is non-nil, call
  19577. `newline-and-indent' instead of `newline'.
  19578. When `org-return-follows-link' is non-nil and point is on
  19579. a timestamp or a link, call `org-open-at-point'. However, it
  19580. will not happen if point is in a table or on a \"dead\"
  19581. object (e.g., within a comment). In these case, you need to use
  19582. `org-open-at-point' directly."
  19583. (interactive)
  19584. (let ((context (if org-return-follows-link (org-element-context)
  19585. (org-element-at-point))))
  19586. (cond
  19587. ;; In a table, call `org-table-next-row'.
  19588. ((or (and (eq (org-element-type context) 'table)
  19589. (>= (point) (org-element-property :contents-begin context))
  19590. (< (point) (org-element-property :contents-end context)))
  19591. (org-element-lineage context '(table-row table-cell) t))
  19592. (org-table-justify-field-maybe)
  19593. (call-interactively #'org-table-next-row))
  19594. ;; On a link or a timestamp, call `org-open-at-point' if
  19595. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19596. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19597. ((and org-return-follows-link
  19598. (or (org-in-regexp org-ts-regexp-both nil t)
  19599. (org-in-regexp org-tsr-regexp-both nil t)
  19600. (org-in-regexp org-any-link-re nil t)))
  19601. (call-interactively #'org-open-at-point))
  19602. ;; Insert newline in heading, but preserve tags.
  19603. ((and (not (bolp))
  19604. (save-excursion (beginning-of-line)
  19605. (looking-at org-complex-heading-regexp)))
  19606. ;; At headline. Split line. However, if point is on keyword,
  19607. ;; priority cookie or tags, do not break any of them: add
  19608. ;; a newline after the headline instead.
  19609. (let ((tags-column (and (match-beginning 5)
  19610. (save-excursion (goto-char (match-beginning 5))
  19611. (current-column))))
  19612. (string
  19613. (when (and (match-end 4)
  19614. (>= (point)
  19615. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19616. (<= (point) (match-end 4)))
  19617. (delete-and-extract-region (point) (match-end 4)))))
  19618. (when (and tags-column string) ; Adjust tag alignment.
  19619. (org-align-tags-here
  19620. (if org-auto-align-tags org-tags-column tags-column)))
  19621. (end-of-line)
  19622. (org-show-entry)
  19623. (if indent (newline-and-indent) (newline))
  19624. (when string (save-excursion (insert (org-trim string))))))
  19625. ;; In a list, make sure indenting keeps trailing text within.
  19626. ((and indent
  19627. (not (eolp))
  19628. (org-element-lineage context '(item)))
  19629. (let ((trailing-data
  19630. (delete-and-extract-region (point) (line-end-position))))
  19631. (newline-and-indent)
  19632. (save-excursion (insert trailing-data))))
  19633. (t (if indent (newline-and-indent) (newline))))))
  19634. (defun org-return-indent ()
  19635. "Goto next table row or insert a newline and indent.
  19636. Calls `org-table-next-row' or `newline-and-indent', depending on
  19637. context. See the individual commands for more information."
  19638. (interactive)
  19639. (org-return t))
  19640. (defun org-ctrl-c-star ()
  19641. "Compute table, or change heading status of lines.
  19642. Calls `org-table-recalculate' or `org-toggle-heading',
  19643. depending on context."
  19644. (interactive)
  19645. (cond
  19646. ((org-at-table-p)
  19647. (call-interactively 'org-table-recalculate))
  19648. (t
  19649. ;; Convert all lines in region to list items
  19650. (call-interactively 'org-toggle-heading))))
  19651. (defun org-ctrl-c-minus ()
  19652. "Insert separator line in table or modify bullet status of line.
  19653. Also turns a plain line or a region of lines into list items.
  19654. Calls `org-table-insert-hline', `org-toggle-item', or
  19655. `org-cycle-list-bullet', depending on context."
  19656. (interactive)
  19657. (cond
  19658. ((org-at-table-p)
  19659. (call-interactively 'org-table-insert-hline))
  19660. ((org-region-active-p)
  19661. (call-interactively 'org-toggle-item))
  19662. ((org-in-item-p)
  19663. (call-interactively 'org-cycle-list-bullet))
  19664. (t
  19665. (call-interactively 'org-toggle-item))))
  19666. (defun org-toggle-heading (&optional nstars)
  19667. "Convert headings to normal text, or items or text to headings.
  19668. If there is no active region, only convert the current line.
  19669. With a \\[universal-argument] prefix, convert the whole list at
  19670. point into heading.
  19671. In a region:
  19672. - If the first non blank line is a headline, remove the stars
  19673. from all headlines in the region.
  19674. - If it is a normal line, turn each and every normal line (i.e.,
  19675. not an heading or an item) in the region into headings. If you
  19676. want to convert only the first line of this region, use one
  19677. universal prefix argument.
  19678. - If it is a plain list item, turn all plain list items into headings.
  19679. When converting a line into a heading, the number of stars is chosen
  19680. such that the lines become children of the current entry. However,
  19681. when a numeric prefix argument is given, its value determines the
  19682. number of stars to add."
  19683. (interactive "P")
  19684. (let ((skip-blanks
  19685. (function
  19686. ;; Return beginning of first non-blank line, starting from
  19687. ;; line at POS.
  19688. (lambda (pos)
  19689. (save-excursion
  19690. (goto-char pos)
  19691. (while (org-at-comment-p) (forward-line))
  19692. (skip-chars-forward " \r\t\n")
  19693. (point-at-bol)))))
  19694. beg end toggled)
  19695. ;; Determine boundaries of changes. If a universal prefix has
  19696. ;; been given, put the list in a region. If region ends at a bol,
  19697. ;; do not consider the last line to be in the region.
  19698. (when (and current-prefix-arg (org-at-item-p))
  19699. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19700. (org-mark-element))
  19701. (if (org-region-active-p)
  19702. (setq beg (funcall skip-blanks (region-beginning))
  19703. end (copy-marker (save-excursion
  19704. (goto-char (region-end))
  19705. (if (bolp) (point) (point-at-eol)))))
  19706. (setq beg (funcall skip-blanks (point-at-bol))
  19707. end (copy-marker (point-at-eol))))
  19708. ;; Ensure inline tasks don't count as headings.
  19709. (org-with-limited-levels
  19710. (save-excursion
  19711. (goto-char beg)
  19712. (cond
  19713. ;; Case 1. Started at an heading: de-star headings.
  19714. ((org-at-heading-p)
  19715. (while (< (point) end)
  19716. (when (org-at-heading-p t)
  19717. (looking-at org-outline-regexp) (replace-match "")
  19718. (setq toggled t))
  19719. (forward-line)))
  19720. ;; Case 2. Started at an item: change items into headlines.
  19721. ;; One star will be added by `org-list-to-subtree'.
  19722. ((org-at-item-p)
  19723. (while (< (point) end)
  19724. (when (org-at-item-p)
  19725. ;; Pay attention to cases when region ends before list.
  19726. (let* ((struct (org-list-struct))
  19727. (list-end
  19728. (min (org-list-get-bottom-point struct) (1+ end))))
  19729. (save-restriction
  19730. (narrow-to-region (point) list-end)
  19731. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19732. (setq toggled t))
  19733. (forward-line)))
  19734. ;; Case 3. Started at normal text: make every line an heading,
  19735. ;; skipping headlines and items.
  19736. (t (let* ((stars
  19737. (make-string
  19738. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19739. (add-stars
  19740. (cond (nstars "") ; stars from prefix only
  19741. ((equal stars "") "*") ; before first heading
  19742. (org-odd-levels-only "**") ; inside heading, odd
  19743. (t "*"))) ; inside heading, oddeven
  19744. (rpl (concat stars add-stars " "))
  19745. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19746. (while (< (point) (if (equal nstars '(4)) lend end))
  19747. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19748. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19749. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19750. (forward-line)))))))
  19751. (unless toggled (message "Cannot toggle heading from here"))))
  19752. (defun org-meta-return (&optional _arg)
  19753. "Insert a new heading or wrap a region in a table.
  19754. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19755. on context. See the individual commands for more information."
  19756. (interactive)
  19757. (org-check-before-invisible-edit 'insert)
  19758. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19759. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19760. #'org-insert-heading))))
  19761. ;;; Menu entries
  19762. (defsubst org-in-subtree-not-table-p ()
  19763. "Are we in a subtree and not in a table?"
  19764. (and (not (org-before-first-heading-p))
  19765. (not (org-at-table-p))))
  19766. ;; Define the Org-mode menus
  19767. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19768. '("Tbl"
  19769. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19770. ["Next Field" org-cycle (org-at-table-p)]
  19771. ["Previous Field" org-shifttab (org-at-table-p)]
  19772. ["Next Row" org-return (org-at-table-p)]
  19773. "--"
  19774. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19775. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19776. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19777. "--"
  19778. ("Column"
  19779. ["Move Column Left" org-metaleft (org-at-table-p)]
  19780. ["Move Column Right" org-metaright (org-at-table-p)]
  19781. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19782. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19783. ("Row"
  19784. ["Move Row Up" org-metaup (org-at-table-p)]
  19785. ["Move Row Down" org-metadown (org-at-table-p)]
  19786. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19787. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19788. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19789. "--"
  19790. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19791. ("Rectangle"
  19792. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19793. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19794. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19795. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19796. "--"
  19797. ("Calculate"
  19798. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19799. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19800. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19801. "--"
  19802. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19803. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19804. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19805. "--"
  19806. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19807. "--"
  19808. ["Sum Column/Rectangle" org-table-sum
  19809. (or (org-at-table-p) (org-region-active-p))]
  19810. ["Which Column?" org-table-current-column (org-at-table-p)])
  19811. ["Debug Formulas"
  19812. org-table-toggle-formula-debugger
  19813. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19814. ["Show Col/Row Numbers"
  19815. org-table-toggle-coordinate-overlays
  19816. :style toggle
  19817. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19818. "--"
  19819. ["Create" org-table-create (and (not (org-at-table-p))
  19820. org-enable-table-editor)]
  19821. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19822. ["Import from File" org-table-import (not (org-at-table-p))]
  19823. ["Export to File" org-table-export (org-at-table-p)]
  19824. "--"
  19825. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19826. "--"
  19827. ("Plot"
  19828. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19829. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19830. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19831. '("Org"
  19832. ("Show/Hide"
  19833. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19834. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19835. ["Sparse Tree..." org-sparse-tree t]
  19836. ["Reveal Context" org-reveal t]
  19837. ["Show All" outline-show-all t]
  19838. "--"
  19839. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19840. "--"
  19841. ["New Heading" org-insert-heading t]
  19842. ("Navigate Headings"
  19843. ["Up" outline-up-heading t]
  19844. ["Next" outline-next-visible-heading t]
  19845. ["Previous" outline-previous-visible-heading t]
  19846. ["Next Same Level" outline-forward-same-level t]
  19847. ["Previous Same Level" outline-backward-same-level t]
  19848. "--"
  19849. ["Jump" org-goto t])
  19850. ("Edit Structure"
  19851. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19852. "--"
  19853. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19854. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19855. "--"
  19856. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19857. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19858. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19859. "--"
  19860. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19861. "--"
  19862. ["Copy visible text" org-copy-visible t]
  19863. "--"
  19864. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19865. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19866. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19867. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19868. "--"
  19869. ["Sort Region/Children" org-sort t]
  19870. "--"
  19871. ["Convert to odd levels" org-convert-to-odd-levels t]
  19872. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19873. ("Editing"
  19874. ["Emphasis..." org-emphasize t]
  19875. ["Edit Source Example" org-edit-special t]
  19876. "--"
  19877. ["Footnote new/jump" org-footnote-action t]
  19878. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19879. ("Archive"
  19880. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19881. "--"
  19882. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19883. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19884. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19885. )
  19886. "--"
  19887. ("Hyperlinks"
  19888. ["Store Link (Global)" org-store-link t]
  19889. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19890. ["Insert Link" org-insert-link t]
  19891. ["Follow Link" org-open-at-point t]
  19892. "--"
  19893. ["Next link" org-next-link t]
  19894. ["Previous link" org-previous-link t]
  19895. "--"
  19896. ["Descriptive Links"
  19897. org-toggle-link-display
  19898. :style radio
  19899. :selected org-descriptive-links
  19900. ]
  19901. ["Literal Links"
  19902. org-toggle-link-display
  19903. :style radio
  19904. :selected (not org-descriptive-links)])
  19905. "--"
  19906. ("TODO Lists"
  19907. ["TODO/DONE/-" org-todo t]
  19908. ("Select keyword"
  19909. ["Next keyword" org-shiftright (org-at-heading-p)]
  19910. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19911. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19912. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19913. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19914. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19915. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19916. "--"
  19917. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19918. :selected org-enforce-todo-dependencies :style toggle :active t]
  19919. "Settings for tree at point"
  19920. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19921. :selected (org-entry-get nil "ORDERED")
  19922. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19923. ["Do Children parallel" org-toggle-ordered-property :style radio
  19924. :selected (not (org-entry-get nil "ORDERED"))
  19925. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19926. "--"
  19927. ["Set Priority" org-priority t]
  19928. ["Priority Up" org-shiftup t]
  19929. ["Priority Down" org-shiftdown t]
  19930. "--"
  19931. ["Get news from all feeds" org-feed-update-all t]
  19932. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19933. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19934. ("TAGS and Properties"
  19935. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19936. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19937. "--"
  19938. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19939. ["Column view of properties" org-columns t]
  19940. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19941. ("Dates and Scheduling"
  19942. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19943. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19944. ("Change Date"
  19945. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19946. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19947. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19948. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19949. ["Compute Time Range" org-evaluate-time-range t]
  19950. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19951. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19952. "--"
  19953. ["Custom time format" org-toggle-time-stamp-overlays
  19954. :style radio :selected org-display-custom-times]
  19955. "--"
  19956. ["Goto Calendar" org-goto-calendar t]
  19957. ["Date from Calendar" org-date-from-calendar t]
  19958. "--"
  19959. ["Start/Restart Timer" org-timer-start t]
  19960. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19961. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19962. ["Insert Timer String" org-timer t]
  19963. ["Insert Timer Item" org-timer-item t])
  19964. ("Logging work"
  19965. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19966. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19967. ["Clock out" org-clock-out t]
  19968. ["Clock cancel" org-clock-cancel t]
  19969. "--"
  19970. ["Mark as default task" org-clock-mark-default-task t]
  19971. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19972. ["Goto running clock" org-clock-goto t]
  19973. "--"
  19974. ["Display times" org-clock-display t]
  19975. ["Create clock table" org-clock-report t]
  19976. "--"
  19977. ["Record DONE time"
  19978. (progn (setq org-log-done (not org-log-done))
  19979. (message "Switching to %s will %s record a timestamp"
  19980. (car org-done-keywords)
  19981. (if org-log-done "automatically" "not")))
  19982. :style toggle :selected org-log-done])
  19983. "--"
  19984. ["Agenda Command..." org-agenda t]
  19985. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19986. ("File List for Agenda")
  19987. ("Special views current file"
  19988. ["TODO Tree" org-show-todo-tree t]
  19989. ["Check Deadlines" org-check-deadlines t]
  19990. ["Timeline" org-timeline t]
  19991. ["Tags/Property tree" org-match-sparse-tree t])
  19992. "--"
  19993. ["Export/Publish..." org-export-dispatch t]
  19994. ("LaTeX"
  19995. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19996. :selected org-cdlatex-mode]
  19997. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19998. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19999. ["Modify math symbol" org-cdlatex-math-modify
  20000. (org-inside-LaTeX-fragment-p)]
  20001. ["Insert citation" org-reftex-citation t])
  20002. "--"
  20003. ("MobileOrg"
  20004. ["Push Files and Views" org-mobile-push t]
  20005. ["Get Captured and Flagged" org-mobile-pull t]
  20006. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  20007. "--"
  20008. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  20009. "--"
  20010. ("Documentation"
  20011. ["Show Version" org-version t]
  20012. ["Info Documentation" org-info t])
  20013. ("Customize"
  20014. ["Browse Org Group" org-customize t]
  20015. "--"
  20016. ["Expand This Menu" org-create-customize-menu
  20017. (fboundp 'customize-menu-create)])
  20018. ["Send bug report" org-submit-bug-report t]
  20019. "--"
  20020. ("Refresh/Reload"
  20021. ["Refresh setup current buffer" org-mode-restart t]
  20022. ["Reload Org (after update)" org-reload t]
  20023. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20024. ))
  20025. (defun org-info (&optional node)
  20026. "Read documentation for Org-mode in the info system.
  20027. With optional NODE, go directly to that node."
  20028. (interactive)
  20029. (info (format "(org)%s" (or node ""))))
  20030. ;;;###autoload
  20031. (defun org-submit-bug-report ()
  20032. "Submit a bug report on Org-mode via mail.
  20033. Don't hesitate to report any problems or inaccurate documentation.
  20034. If you don't have setup sending mail from (X)Emacs, please copy the
  20035. output buffer into your mail program, as it gives us important
  20036. information about your Org-mode version and configuration."
  20037. (interactive)
  20038. (require 'reporter)
  20039. (defvar reporter-prompt-for-summary-p)
  20040. (org-load-modules-maybe)
  20041. (org-require-autoloaded-modules)
  20042. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20043. (reporter-submit-bug-report
  20044. "emacs-orgmode@gnu.org"
  20045. (org-version nil 'full)
  20046. (let (list)
  20047. (save-window-excursion
  20048. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20049. (delete-other-windows)
  20050. (erase-buffer)
  20051. (insert "You are about to submit a bug report to the Org-mode mailing list.
  20052. We would like to add your full Org-mode and Outline configuration to the
  20053. bug report. This greatly simplifies the work of the maintainer and
  20054. other experts on the mailing list.
  20055. HOWEVER, some variables you have customized may contain private
  20056. information. The names of customers, colleagues, or friends, might
  20057. appear in the form of file names, tags, todo states, or search strings.
  20058. If you answer yes to the prompt, you might want to check and remove
  20059. such private information before sending the email.")
  20060. (add-text-properties (point-min) (point-max) '(face org-warning))
  20061. (when (yes-or-no-p "Include your Org-mode configuration ")
  20062. (mapatoms
  20063. (lambda (v)
  20064. (and (boundp v)
  20065. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20066. (or (and (symbol-value v)
  20067. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20068. (and
  20069. (get v 'custom-type) (get v 'standard-value)
  20070. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20071. (push v list)))))
  20072. (kill-buffer (get-buffer "*Warn about privacy*"))
  20073. list))
  20074. nil nil
  20075. "Remember to cover the basics, that is, what you expected to happen and
  20076. what in fact did happen. You don't know how to make a good report? See
  20077. http://orgmode.org/manual/Feedback.html#Feedback
  20078. Your bug report will be posted to the Org-mode mailing list.
  20079. ------------------------------------------------------------------------")
  20080. (save-excursion
  20081. (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20082. (replace-match "\\1Bug: \\3 [\\2]")))))
  20083. (defun org-install-agenda-files-menu ()
  20084. (let ((bl (buffer-list)))
  20085. (save-excursion
  20086. (while bl
  20087. (set-buffer (pop bl))
  20088. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20089. (when (derived-mode-p 'org-mode)
  20090. (easy-menu-change
  20091. '("Org") "File List for Agenda"
  20092. (append
  20093. (list
  20094. ["Edit File List" (org-edit-agenda-file-list) t]
  20095. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20096. ["Remove Current File from List" org-remove-file t]
  20097. ["Cycle through agenda files" org-cycle-agenda-files t]
  20098. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20099. "--")
  20100. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20101. ;;;; Documentation
  20102. (defun org-require-autoloaded-modules ()
  20103. (interactive)
  20104. (mapc #'require
  20105. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20106. org-table org-timer)))
  20107. ;;;###autoload
  20108. (defun org-reload (&optional uncompiled)
  20109. "Reload all org lisp files.
  20110. With prefix arg UNCOMPILED, load the uncompiled versions."
  20111. (interactive "P")
  20112. (require 'loadhist)
  20113. (let* ((org-dir (org-find-library-dir "org"))
  20114. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20115. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20116. (remove-re (format "\\`%s\\'"
  20117. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20118. (feats (delete-dups
  20119. (mapcar 'file-name-sans-extension
  20120. (mapcar 'file-name-nondirectory
  20121. (delq nil
  20122. (mapcar 'feature-file
  20123. features))))))
  20124. (lfeat (append
  20125. (sort
  20126. (setq feats
  20127. (delq nil (mapcar
  20128. (lambda (f)
  20129. (if (and (string-match feature-re f)
  20130. (not (string-match remove-re f)))
  20131. f nil))
  20132. feats)))
  20133. 'string-lessp)
  20134. (list "org-version" "org")))
  20135. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20136. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20137. load-uncore load-misses)
  20138. (setq load-misses
  20139. (delq 't
  20140. (mapcar (lambda (f)
  20141. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20142. (and (string= org-dir contrib-dir)
  20143. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20144. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20145. (add-to-list 'load-uncore f 'append)
  20146. 't)
  20147. f))
  20148. lfeat)))
  20149. (when load-uncore
  20150. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20151. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20152. (if load-misses
  20153. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20154. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20155. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20156. ;;;###autoload
  20157. (defun org-customize ()
  20158. "Call the customize function with org as argument."
  20159. (interactive)
  20160. (org-load-modules-maybe)
  20161. (org-require-autoloaded-modules)
  20162. (customize-browse 'org))
  20163. (defun org-create-customize-menu ()
  20164. "Create a full customization menu for Org-mode, insert it into the menu."
  20165. (interactive)
  20166. (org-load-modules-maybe)
  20167. (org-require-autoloaded-modules)
  20168. (if (fboundp 'customize-menu-create)
  20169. (progn
  20170. (easy-menu-change
  20171. '("Org") "Customize"
  20172. `(["Browse Org group" org-customize t]
  20173. "--"
  20174. ,(customize-menu-create 'org)
  20175. ["Set" Custom-set t]
  20176. ["Save" Custom-save t]
  20177. ["Reset to Current" Custom-reset-current t]
  20178. ["Reset to Saved" Custom-reset-saved t]
  20179. ["Reset to Standard Settings" Custom-reset-standard t]))
  20180. (message "\"Org\"-menu now contains full customization menu"))
  20181. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20182. ;;;; Miscellaneous stuff
  20183. ;;; Generally useful functions
  20184. (defun org-get-at-eol (property n)
  20185. "Get text property PROPERTY at the end of line less N characters."
  20186. (get-text-property (- (point-at-eol) n) property))
  20187. (defun org-find-text-property-in-string (prop s)
  20188. "Return the first non-nil value of property PROP in string S."
  20189. (or (get-text-property 0 prop s)
  20190. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20191. prop s)))
  20192. (defun org-display-warning (message) ;; Copied from Emacs-Muse
  20193. "Display the given MESSAGE as a warning."
  20194. (if (fboundp 'display-warning)
  20195. (display-warning 'org message :warning)
  20196. (let ((buf (get-buffer-create "*Org warnings*")))
  20197. (with-current-buffer buf
  20198. (goto-char (point-max))
  20199. (insert "Warning (Org): " message)
  20200. (unless (bolp)
  20201. (newline)))
  20202. (display-buffer buf)
  20203. (sit-for 0))))
  20204. (defun org-eval (form)
  20205. "Eval FORM and return result."
  20206. (condition-case error
  20207. (eval form)
  20208. (error (format "%%![Error: %s]" error))))
  20209. (defun org-in-clocktable-p ()
  20210. "Check if the cursor is in a clocktable."
  20211. (let ((pos (point)) start)
  20212. (save-excursion
  20213. (end-of-line 1)
  20214. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20215. (setq start (match-beginning 0))
  20216. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20217. (>= (match-end 0) pos)
  20218. start))))
  20219. (defun org-in-verbatim-emphasis ()
  20220. (save-match-data
  20221. (and (org-in-regexp org-emph-re 2)
  20222. (>= (point) (match-beginning 3))
  20223. (<= (point) (match-end 4))
  20224. (member (match-string 3) '("=" "~")))))
  20225. (defun org-overlay-display (ovl text &optional face evap)
  20226. "Make overlay OVL display TEXT with face FACE."
  20227. (overlay-put ovl 'display text)
  20228. (if face (overlay-put ovl 'face face))
  20229. (if evap (overlay-put ovl 'evaporate t)))
  20230. (defun org-overlay-before-string (ovl text &optional face evap)
  20231. "Make overlay OVL display TEXT with face FACE."
  20232. (if face (org-add-props text nil 'face face))
  20233. (overlay-put ovl 'before-string text)
  20234. (if evap (overlay-put ovl 'evaporate t)))
  20235. (defun org-find-overlays (prop &optional pos delete)
  20236. "Find all overlays specifying PROP at POS or point.
  20237. If DELETE is non-nil, delete all those overlays."
  20238. (let (found)
  20239. (dolist (ov (overlays-at (or pos (point))) found)
  20240. (cond ((not (overlay-get ov prop)))
  20241. (delete (delete-overlay ov))
  20242. (t (push ov found))))))
  20243. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20244. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20245. (if (and marker (marker-buffer marker)
  20246. (buffer-live-p (marker-buffer marker)))
  20247. (progn
  20248. (pop-to-buffer-same-window (marker-buffer marker))
  20249. (when (or (> marker (point-max)) (< marker (point-min)))
  20250. (widen))
  20251. (goto-char marker)
  20252. (org-show-context 'org-goto))
  20253. (if bookmark
  20254. (bookmark-jump bookmark)
  20255. (error "Cannot find location"))))
  20256. (defun org-quote-csv-field (s)
  20257. "Quote field for inclusion in CSV material."
  20258. (if (string-match "[\",]" s)
  20259. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20260. s))
  20261. (defun org-force-self-insert (N)
  20262. "Needed to enforce self-insert under remapping."
  20263. (interactive "p")
  20264. (self-insert-command N))
  20265. (defun org-string-width (s)
  20266. "Compute width of string, ignoring invisible characters.
  20267. This ignores character with invisibility property `org-link', and also
  20268. characters with property `org-cwidth', because these will become invisible
  20269. upon the next fontification round."
  20270. (let (b l)
  20271. (when (or (eq t buffer-invisibility-spec)
  20272. (assq 'org-link buffer-invisibility-spec))
  20273. (while (setq b (text-property-any 0 (length s)
  20274. 'invisible 'org-link s))
  20275. (setq s (concat (substring s 0 b)
  20276. (substring s (or (next-single-property-change
  20277. b 'invisible s)
  20278. (length s)))))))
  20279. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20280. (setq s (concat (substring s 0 b)
  20281. (substring s (or (next-single-property-change
  20282. b 'org-cwidth s)
  20283. (length s))))))
  20284. (setq l (string-width s) b -1)
  20285. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20286. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20287. l))
  20288. (defun org-shorten-string (s maxlength)
  20289. "Shorten string S so tht it is no longer than MAXLENGTH characters.
  20290. If the string is shorter or has length MAXLENGTH, just return the
  20291. original string. If it is longer, the functions finds a space in the
  20292. string, breaks this string off at that locations and adds three dots
  20293. as ellipsis. Including the ellipsis, the string will not be longer
  20294. than MAXLENGTH. If finding a good breaking point in the string does
  20295. not work, the string is just chopped off in the middle of a word
  20296. if necessary."
  20297. (if (<= (length s) maxlength)
  20298. s
  20299. (let* ((n (max (- maxlength 4) 1))
  20300. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20301. (if (string-match re s)
  20302. (concat (match-string 1 s) "...")
  20303. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20304. (defun org-get-indentation (&optional line)
  20305. "Get the indentation of the current line, interpreting tabs.
  20306. When LINE is given, assume it represents a line and compute its indentation."
  20307. (if line
  20308. (when (string-match "^ *" (org-remove-tabs line))
  20309. (match-end 0))
  20310. (save-excursion
  20311. (beginning-of-line 1)
  20312. (skip-chars-forward " \t")
  20313. (current-column))))
  20314. (defun org-get-string-indentation (s)
  20315. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20316. (let ((n -1) (i 0) (w tab-width) c)
  20317. (catch 'exit
  20318. (while (< (setq n (1+ n)) (length s))
  20319. (setq c (aref s n))
  20320. (cond ((= c ?\ ) (setq i (1+ i)))
  20321. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20322. (t (throw 'exit t)))))
  20323. i))
  20324. (defun org-remove-tabs (s &optional width)
  20325. "Replace tabulators in S with spaces.
  20326. Assumes that s is a single line, starting in column 0."
  20327. (setq width (or width tab-width))
  20328. (while (string-match "\t" s)
  20329. (setq s (replace-match
  20330. (make-string
  20331. (- (* width (/ (+ (match-beginning 0) width) width))
  20332. (match-beginning 0)) ?\ )
  20333. t t s)))
  20334. s)
  20335. (defun org-fix-indentation (line ind)
  20336. "Fix indentation in LINE.
  20337. IND is a cons cell with target and minimum indentation.
  20338. If the current indentation in LINE is smaller than the minimum,
  20339. leave it alone. If it is larger than ind, set it to the target."
  20340. (let* ((l (org-remove-tabs line))
  20341. (i (org-get-indentation l))
  20342. (i1 (car ind)) (i2 (cdr ind)))
  20343. (when (>= i i2) (setq l (substring line i2)))
  20344. (if (> i1 0)
  20345. (concat (make-string i1 ?\ ) l)
  20346. l)))
  20347. (defun org-remove-indentation (code &optional n)
  20348. "Remove maximum common indentation in string CODE and return it.
  20349. N may optionally be the number of columns to remove. Return CODE
  20350. as-is if removal failed."
  20351. (with-temp-buffer
  20352. (insert code)
  20353. (if (org-do-remove-indentation n) (buffer-string) code)))
  20354. (defun org-do-remove-indentation (&optional n)
  20355. "Remove the maximum common indentation from the buffer.
  20356. When optional argument N is a positive integer, remove exactly
  20357. that much characters from indentation, if possible. Return nil
  20358. if it fails."
  20359. (catch :exit
  20360. (goto-char (point-min))
  20361. ;; Find maximum common indentation, if not specified.
  20362. (let ((n (or n
  20363. (let ((min-ind (point-max)))
  20364. (save-excursion
  20365. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20366. (let ((ind (1- (current-column))))
  20367. (if (zerop ind) (throw :exit nil)
  20368. (setq min-ind (min min-ind ind))))))
  20369. min-ind))))
  20370. (if (zerop n) (throw :exit nil)
  20371. ;; Remove exactly N indentation, but give up if not possible.
  20372. (while (not (eobp))
  20373. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20374. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20375. ((< ind n) (throw :exit nil))
  20376. (t (indent-line-to (- ind n))))
  20377. (forward-line)))
  20378. ;; Signal success.
  20379. t))))
  20380. (defun org-fill-template (template alist)
  20381. "Find each %key of ALIST in TEMPLATE and replace it."
  20382. (let ((case-fold-search nil))
  20383. (dolist (entry (sort (copy-sequence alist)
  20384. (lambda (a b) (< (length (car a)) (length (car b))))))
  20385. (setq template
  20386. (replace-regexp-in-string
  20387. (concat "%" (regexp-quote (car entry)))
  20388. (or (cdr entry) "") template t t)))
  20389. template))
  20390. (defun org-base-buffer (buffer)
  20391. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20392. (if (not buffer)
  20393. buffer
  20394. (or (buffer-base-buffer buffer)
  20395. buffer)))
  20396. (defun org-wrap (string &optional width lines)
  20397. "Wrap string to either a number of lines, or a width in characters.
  20398. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20399. that costs. If there is a word longer than WIDTH, the text is actually
  20400. wrapped to the length of that word.
  20401. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20402. many lines, whatever width that takes.
  20403. The return value is a list of lines, without newlines at the end."
  20404. (let* ((words (org-split-string string "[ \t\n]+"))
  20405. (maxword (apply 'max (mapcar 'org-string-width words)))
  20406. w ll)
  20407. (cond (width
  20408. (org-do-wrap words (max maxword width)))
  20409. (lines
  20410. (setq w maxword)
  20411. (setq ll (org-do-wrap words maxword))
  20412. (if (<= (length ll) lines)
  20413. ll
  20414. (setq ll words)
  20415. (while (> (length ll) lines)
  20416. (setq w (1+ w))
  20417. (setq ll (org-do-wrap words w)))
  20418. ll))
  20419. (t (error "Cannot wrap this")))))
  20420. (defun org-do-wrap (words width)
  20421. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20422. (let (lines line)
  20423. (while words
  20424. (setq line (pop words))
  20425. (while (and words (< (+ (length line) (length (car words))) width))
  20426. (setq line (concat line " " (pop words))))
  20427. (setq lines (push line lines)))
  20428. (nreverse lines)))
  20429. (defun org-split-string (string &optional separators)
  20430. "Splits STRING into substrings at SEPARATORS.
  20431. SEPARATORS is a regular expression.
  20432. No empty strings are returned if there are matches at the beginning
  20433. and end of string."
  20434. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20435. (let ((start 0) notfirst list)
  20436. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20437. (if (and notfirst
  20438. (= start (match-beginning 0))
  20439. (< start (length string)))
  20440. (1+ start) start))
  20441. (< (match-beginning 0) (length string)))
  20442. (setq notfirst t)
  20443. (or (eq (match-beginning 0) 0)
  20444. (and (eq (match-beginning 0) (match-end 0))
  20445. (eq (match-beginning 0) start))
  20446. (push (substring string start (match-beginning 0)) list))
  20447. (setq start (match-end 0)))
  20448. (or (eq start (length string))
  20449. (push (substring string start) list))
  20450. (nreverse list)))
  20451. (defun org-quote-vert (s)
  20452. "Replace \"|\" with \"\\vert\"."
  20453. (while (string-match "|" s)
  20454. (setq s (replace-match "\\vert" t t s)))
  20455. s)
  20456. (defun org-uuidgen-p (s)
  20457. "Is S an ID created by UUIDGEN?"
  20458. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20459. (defun org-in-src-block-p (&optional inside)
  20460. "Whether point is in a code source block.
  20461. When INSIDE is non-nil, don't consider we are within a src block
  20462. when point is at #+BEGIN_SRC or #+END_SRC."
  20463. (let ((case-fold-search t))
  20464. (or (and (eq (get-char-property (point) 'src-block) t))
  20465. (and (not inside)
  20466. (save-match-data
  20467. (save-excursion
  20468. (beginning-of-line)
  20469. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20470. (defun org-context ()
  20471. "Return a list of contexts of the current cursor position.
  20472. If several contexts apply, all are returned.
  20473. Each context entry is a list with a symbol naming the context, and
  20474. two positions indicating start and end of the context. Possible
  20475. contexts are:
  20476. :headline anywhere in a headline
  20477. :headline-stars on the leading stars in a headline
  20478. :todo-keyword on a TODO keyword (including DONE) in a headline
  20479. :tags on the TAGS in a headline
  20480. :priority on the priority cookie in a headline
  20481. :item on the first line of a plain list item
  20482. :item-bullet on the bullet/number of a plain list item
  20483. :checkbox on the checkbox in a plain list item
  20484. :table in an org-mode table
  20485. :table-special on a special filed in a table
  20486. :table-table in a table.el table
  20487. :clocktable in a clocktable
  20488. :src-block in a source block
  20489. :link on a hyperlink
  20490. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20491. :target on a <<target>>
  20492. :radio-target on a <<<radio-target>>>
  20493. :latex-fragment on a LaTeX fragment
  20494. :latex-preview on a LaTeX fragment with overlaid preview image
  20495. This function expects the position to be visible because it uses font-lock
  20496. faces as a help to recognize the following contexts: :table-special, :link,
  20497. and :keyword."
  20498. (let* ((f (get-text-property (point) 'face))
  20499. (faces (if (listp f) f (list f)))
  20500. (case-fold-search t)
  20501. (p (point)) clist o)
  20502. ;; First the large context
  20503. (cond
  20504. ((org-at-heading-p t)
  20505. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20506. (when (progn
  20507. (beginning-of-line 1)
  20508. (looking-at org-todo-line-tags-regexp))
  20509. (push (org-point-in-group p 1 :headline-stars) clist)
  20510. (push (org-point-in-group p 2 :todo-keyword) clist)
  20511. (push (org-point-in-group p 4 :tags) clist))
  20512. (goto-char p)
  20513. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20514. (when (looking-at "\\[#[A-Z0-9]\\]")
  20515. (push (org-point-in-group p 0 :priority) clist)))
  20516. ((org-at-item-p)
  20517. (push (org-point-in-group p 2 :item-bullet) clist)
  20518. (push (list :item (point-at-bol)
  20519. (save-excursion (org-end-of-item) (point)))
  20520. clist)
  20521. (and (org-at-item-checkbox-p)
  20522. (push (org-point-in-group p 0 :checkbox) clist)))
  20523. ((org-at-table-p)
  20524. (push (list :table (org-table-begin) (org-table-end)) clist)
  20525. (when (memq 'org-formula faces)
  20526. (push (list :table-special
  20527. (previous-single-property-change p 'face)
  20528. (next-single-property-change p 'face)) clist)))
  20529. ((org-at-table-p 'any)
  20530. (push (list :table-table) clist)))
  20531. (goto-char p)
  20532. (let ((case-fold-search t))
  20533. ;; New the "medium" contexts: clocktables, source blocks
  20534. (cond ((org-in-clocktable-p)
  20535. (push (list :clocktable
  20536. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20537. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20538. (match-beginning 1))
  20539. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20540. (match-end 0))) clist))
  20541. ((org-in-src-block-p)
  20542. (push (list :src-block
  20543. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20544. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20545. (match-beginning 1))
  20546. (and (search-forward "#+END_SRC" nil t)
  20547. (match-beginning 0))) clist))))
  20548. (goto-char p)
  20549. ;; Now the small context
  20550. (cond
  20551. ((org-at-timestamp-p)
  20552. (push (org-point-in-group p 0 :timestamp) clist))
  20553. ((memq 'org-link faces)
  20554. (push (list :link
  20555. (previous-single-property-change p 'face)
  20556. (next-single-property-change p 'face)) clist))
  20557. ((memq 'org-special-keyword faces)
  20558. (push (list :keyword
  20559. (previous-single-property-change p 'face)
  20560. (next-single-property-change p 'face)) clist))
  20561. ((org-at-target-p)
  20562. (push (org-point-in-group p 0 :target) clist)
  20563. (goto-char (1- (match-beginning 0)))
  20564. (when (looking-at org-radio-target-regexp)
  20565. (push (org-point-in-group p 0 :radio-target) clist))
  20566. (goto-char p))
  20567. ((setq o (cl-some
  20568. (lambda (o)
  20569. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20570. o))
  20571. (overlays-at (point))))
  20572. (push (list :latex-fragment
  20573. (overlay-start o) (overlay-end o)) clist)
  20574. (push (list :latex-preview
  20575. (overlay-start o) (overlay-end o)) clist))
  20576. ((org-inside-LaTeX-fragment-p)
  20577. ;; FIXME: positions wrong.
  20578. (push (list :latex-fragment (point) (point)) clist)))
  20579. (setq clist (nreverse (delq nil clist)))
  20580. clist))
  20581. (defun org-in-regexp (regexp &optional nlines visually)
  20582. "Check if point is inside a match of REGEXP.
  20583. Normally only the current line is checked, but you can include
  20584. NLINES extra lines around point into the search. If VISUALLY is
  20585. set, require that the cursor is not after the match but really
  20586. on, so that the block visually is on the match.
  20587. Return nil or a cons cell (BEG . END) where BEG and END are,
  20588. respectively, the positions at the beginning and the end of the
  20589. match."
  20590. (catch :exit
  20591. (let ((pos (point))
  20592. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20593. (save-excursion
  20594. (beginning-of-line (- 1 (or nlines 0)))
  20595. (while (and (re-search-forward regexp eol t)
  20596. (<= (match-beginning 0) pos))
  20597. (let ((end (match-end 0)))
  20598. (when (or (> end pos) (and (= end pos) (not visually)))
  20599. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20600. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20601. "Non-nil when point is between matches of START-RE and END-RE.
  20602. Also return a non-nil value when point is on one of the matches.
  20603. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20604. buffer positions. Default values are the positions of headlines
  20605. surrounding the point.
  20606. The functions returns a cons cell whose car (resp. cdr) is the
  20607. position before START-RE (resp. after END-RE)."
  20608. (save-match-data
  20609. (let ((pos (point))
  20610. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20611. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20612. beg end)
  20613. (save-excursion
  20614. ;; Point is on a block when on START-RE or if START-RE can be
  20615. ;; found before it...
  20616. (and (or (org-in-regexp start-re)
  20617. (re-search-backward start-re limit-up t))
  20618. (setq beg (match-beginning 0))
  20619. ;; ... and END-RE after it...
  20620. (goto-char (match-end 0))
  20621. (re-search-forward end-re limit-down t)
  20622. (> (setq end (match-end 0)) pos)
  20623. ;; ... without another START-RE in-between.
  20624. (goto-char (match-beginning 0))
  20625. (not (re-search-backward start-re (1+ beg) t))
  20626. ;; Return value.
  20627. (cons beg end))))))
  20628. (defun org-in-block-p (names)
  20629. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20630. NAMES is a list of strings containing names of blocks.
  20631. Return first block name matched, or nil. Beware that in case of
  20632. nested blocks, the returned name may not belong to the closest
  20633. block from point."
  20634. (save-match-data
  20635. (catch 'exit
  20636. (let ((case-fold-search t)
  20637. (lim-up (save-excursion (outline-previous-heading)))
  20638. (lim-down (save-excursion (outline-next-heading))))
  20639. (dolist (name names)
  20640. (let ((n (regexp-quote name)))
  20641. (when (org-between-regexps-p
  20642. (concat "^[ \t]*#\\+begin_" n)
  20643. (concat "^[ \t]*#\\+end_" n)
  20644. lim-up lim-down)
  20645. (throw 'exit n)))))
  20646. nil)))
  20647. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20648. "Call `multi-occur' with buffers for all agenda files."
  20649. (interactive "sOrg-files matching: ")
  20650. (let* ((files (org-agenda-files))
  20651. (tnames (mapcar #'file-truename files))
  20652. (extra org-agenda-text-search-extra-files))
  20653. (when (eq (car extra) 'agenda-archives)
  20654. (setq extra (cdr extra))
  20655. (setq files (org-add-archive-files files)))
  20656. (dolist (f extra)
  20657. (unless (member (file-truename f) tnames)
  20658. (unless (member f files) (setq files (append files (list f))))
  20659. (setq tnames (append tnames (list (file-truename f))))))
  20660. (multi-occur
  20661. (mapcar (lambda (x)
  20662. (with-current-buffer
  20663. ;; FIXME: Why not just (find-file-noselect x)?
  20664. ;; Is it to avoid the "revert buffer" prompt?
  20665. (or (get-file-buffer x) (find-file-noselect x))
  20666. (widen)
  20667. (current-buffer)))
  20668. files)
  20669. regexp)))
  20670. (add-hook 'occur-mode-find-occurrence-hook
  20671. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20672. (defun org-occur-link-in-agenda-files ()
  20673. "Create a link and search for it in the agendas.
  20674. The link is not stored in `org-stored-links', it is just created
  20675. for the search purpose."
  20676. (interactive)
  20677. (let ((link (condition-case nil
  20678. (org-store-link nil)
  20679. (error "Unable to create a link to here"))))
  20680. (org-occur-in-agenda-files (regexp-quote link))))
  20681. (defun org-reverse-string (string)
  20682. "Return the reverse of STRING."
  20683. (apply 'string (reverse (string-to-list string))))
  20684. ;; defsubst org-uniquify must be defined before first use
  20685. (defun org-uniquify-alist (alist)
  20686. "Merge elements of ALIST with the same key.
  20687. For example, in this alist:
  20688. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20689. => \\='((a 1 3) (b 2))
  20690. merge (a 1) and (a 3) into (a 1 3).
  20691. The function returns the new ALIST."
  20692. (let (rtn)
  20693. (dolist (e alist rtn)
  20694. (let (n)
  20695. (if (not (assoc (car e) rtn))
  20696. (push e rtn)
  20697. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20698. (setq rtn (assq-delete-all (car e) rtn))
  20699. (push n rtn))))))
  20700. (defun org-delete-all (elts list)
  20701. "Remove all elements in ELTS from LIST.
  20702. Comparison is done with `equal'. It is a destructive operation
  20703. that may remove elements by altering the list structure."
  20704. (while elts
  20705. (setq list (delete (pop elts) list)))
  20706. list)
  20707. (defun org-back-over-empty-lines ()
  20708. "Move backwards over whitespace, to the beginning of the first empty line.
  20709. Returns the number of empty lines passed."
  20710. (let ((pos (point)))
  20711. (if (cdr (assoc 'heading org-blank-before-new-entry))
  20712. (skip-chars-backward " \t\n\r")
  20713. (unless (eobp)
  20714. (forward-line -1)))
  20715. (beginning-of-line 2)
  20716. (goto-char (min (point) pos))
  20717. (count-lines (point) pos)))
  20718. (defun org-skip-whitespace ()
  20719. (skip-chars-forward " \t\n\r"))
  20720. (defun org-point-in-group (point group &optional context)
  20721. "Check if POINT is in match-group GROUP.
  20722. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20723. match. If the match group does not exist or point is not inside it,
  20724. return nil."
  20725. (and (match-beginning group)
  20726. (>= point (match-beginning group))
  20727. (<= point (match-end group))
  20728. (if context
  20729. (list context (match-beginning group) (match-end group))
  20730. t)))
  20731. (defun org-switch-to-buffer-other-window (&rest args)
  20732. "Switch to buffer in a second window on the current frame.
  20733. In particular, do not allow pop-up frames.
  20734. Returns the newly created buffer."
  20735. (org-no-popups
  20736. (apply 'switch-to-buffer-other-window args)))
  20737. (defun org-combine-plists (&rest plists)
  20738. "Create a single property list from all plists in PLISTS.
  20739. The process starts by copying the first list, and then setting properties
  20740. from the other lists. Settings in the last list are the most significant
  20741. ones and overrule settings in the other lists."
  20742. (let ((rtn (copy-sequence (pop plists)))
  20743. p v ls)
  20744. (while plists
  20745. (setq ls (pop plists))
  20746. (while ls
  20747. (setq p (pop ls) v (pop ls))
  20748. (setq rtn (plist-put rtn p v))))
  20749. rtn))
  20750. (defun org-replace-escapes (string table)
  20751. "Replace %-escapes in STRING with values in TABLE.
  20752. TABLE is an association list with keys like \"%a\" and string values.
  20753. The sequences in STRING may contain normal field width and padding information,
  20754. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20755. so values can contain further %-escapes if they are define later in TABLE."
  20756. (let ((tbl (copy-alist table))
  20757. (case-fold-search nil)
  20758. (pchg 0)
  20759. re rpl)
  20760. (dolist (e tbl)
  20761. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20762. (when (and (cdr e) (string-match re (cdr e)))
  20763. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20764. (safe "SREF"))
  20765. (add-text-properties 0 3 (list 'sref sref) safe)
  20766. (setcdr e (replace-match safe t t (cdr e)))))
  20767. (while (string-match re string)
  20768. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20769. (cdr e)))
  20770. (setq string (replace-match rpl t t string))))
  20771. (while (setq pchg (next-property-change pchg string))
  20772. (let ((sref (get-text-property pchg 'sref string)))
  20773. (when (and sref (string-match "SREF" string pchg))
  20774. (setq string (replace-match sref t t string)))))
  20775. string))
  20776. (defun org-sublist (list start end)
  20777. "Return a section of LIST, from START to END.
  20778. Counting starts at 1."
  20779. (cl-subseq list (1- start) end))
  20780. (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
  20781. (defun org-find-base-buffer-visiting (file)
  20782. "Like `find-buffer-visiting' but always return the base buffer and
  20783. not an indirect buffer."
  20784. (let ((buf (or (get-file-buffer file)
  20785. (find-buffer-visiting file))))
  20786. (if buf
  20787. (or (buffer-base-buffer buf) buf)
  20788. nil)))
  20789. ;;; TODO: Only called once, from ox-odt which should probably use
  20790. ;;; org-export-inline-image-p or something.
  20791. (defun org-file-image-p (file)
  20792. "Return non-nil if FILE is an image."
  20793. (save-match-data
  20794. (string-match (image-file-name-regexp) file)))
  20795. (defun org-get-cursor-date (&optional with-time)
  20796. "Return the date at cursor in as a time.
  20797. This works in the calendar and in the agenda, anywhere else it just
  20798. returns the current time.
  20799. If WITH-TIME is non-nil, returns the time of the event at point (in
  20800. the agenda) or the current time of the day."
  20801. (let (date day defd tp hod mod)
  20802. (when with-time
  20803. (setq tp (get-text-property (point) 'time))
  20804. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20805. (setq hod (string-to-number (match-string 1 tp))
  20806. mod (string-to-number (match-string 2 tp))))
  20807. (or tp (let ((now (decode-time)))
  20808. (setq hod (nth 2 now)
  20809. mod (nth 1 now)))))
  20810. (cond
  20811. ((eq major-mode 'calendar-mode)
  20812. (setq date (calendar-cursor-to-date)
  20813. defd (encode-time 0 (or mod 0) (or hod 0)
  20814. (nth 1 date) (nth 0 date) (nth 2 date))))
  20815. ((eq major-mode 'org-agenda-mode)
  20816. (setq day (get-text-property (point) 'day))
  20817. (when day
  20818. (setq date (calendar-gregorian-from-absolute day)
  20819. defd (encode-time 0 (or mod 0) (or hod 0)
  20820. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20821. (or defd (current-time))))
  20822. (defun org-mark-subtree (&optional up)
  20823. "Mark the current subtree.
  20824. This puts point at the start of the current subtree, and mark at
  20825. the end. If a numeric prefix UP is given, move up into the
  20826. hierarchy of headlines by UP levels before marking the subtree."
  20827. (interactive "P")
  20828. (org-with-limited-levels
  20829. (cond ((org-at-heading-p) (beginning-of-line))
  20830. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20831. (t (outline-previous-visible-heading 1))))
  20832. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20833. (if (called-interactively-p 'any)
  20834. (call-interactively 'org-mark-element)
  20835. (org-mark-element)))
  20836. (defun org-file-newer-than-p (file time)
  20837. "Non-nil if FILE is newer than TIME.
  20838. FILE is a filename, as a string, TIME is a list of integers, as
  20839. returned by, e.g., `current-time'."
  20840. (and (file-exists-p file)
  20841. ;; Only compare times up to whole seconds as some file-systems
  20842. ;; (e.g. HFS+) do not retain any finer granularity. As
  20843. ;; a consequence, make sure we return non-nil when the two
  20844. ;; times are equal.
  20845. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20846. (cl-subseq time 0 2)))))
  20847. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20848. "Compile a SOURCE file using PROCESS.
  20849. PROCESS is either a function or a list of shell commands, as
  20850. strings. EXT is a file extension, without the leading dot, as
  20851. a string. It is used to check if the process actually succeeded.
  20852. PROCESS must create a file with the same base name and directory
  20853. as SOURCE, but ending with EXT. The function then returns its
  20854. filename. Otherwise, it raises an error. The error message can
  20855. then be refined by providing string ERR-MSG, which is appended to
  20856. the standard message.
  20857. If PROCESS is a function, it is called with a single argument:
  20858. the SOURCE file.
  20859. If it is a list of commands, each of them is called using
  20860. `shell-command'. By default, in each command, %b, %f, %F and %o
  20861. are replaced with, respectively, SOURCE base name, name, full
  20862. name and directory. It is possible, however, to use more
  20863. place-holders by specifying them in optional argument SPEC, as an
  20864. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20865. When PROCESS is a list of commands, optional argument LOG-BUF can
  20866. be set to a buffer or a buffer name. `shell-command' then uses
  20867. it for output.
  20868. `default-directory' is set to SOURCE directory during the whole
  20869. process."
  20870. (let* ((source-name (file-name-nondirectory source))
  20871. (base-name (file-name-sans-extension source-name))
  20872. (full-name (file-truename source))
  20873. (out-dir (file-name-directory source))
  20874. (time (current-time))
  20875. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20876. (save-window-excursion
  20877. (let ((default-directory (file-name-directory full-name)))
  20878. (pcase process
  20879. ((pred functionp) (funcall process (shell-quote-argument source)))
  20880. ((pred consp)
  20881. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20882. (spec (append spec
  20883. `((?b . ,(shell-quote-argument base-name))
  20884. (?f . ,(shell-quote-argument source-name))
  20885. (?F . ,(shell-quote-argument full-name))
  20886. (?o . ,(shell-quote-argument out-dir))))))
  20887. (dolist (command process)
  20888. (shell-command (format-spec command spec) log-buf))))
  20889. (_ (error "No valid command to process %S%s" source err-msg)))))
  20890. ;; Check for process failure.
  20891. (let ((output (concat out-dir base-name "." ext)))
  20892. (unless (org-file-newer-than-p output time)
  20893. (error (format "File %S wasn't produced%s" output err-msg)))
  20894. output)))
  20895. ;;; Indentation
  20896. (defun org--get-expected-indentation (element contentsp)
  20897. "Expected indentation column for current line, according to ELEMENT.
  20898. ELEMENT is an element containing point. CONTENTSP is non-nil
  20899. when indentation is to be computed according to contents of
  20900. ELEMENT."
  20901. (let ((type (org-element-type element))
  20902. (start (org-element-property :begin element))
  20903. (post-affiliated (org-element-property :post-affiliated element)))
  20904. (org-with-wide-buffer
  20905. (cond
  20906. (contentsp
  20907. (cl-case type
  20908. ((diary-sexp footnote-definition) 0)
  20909. ((headline inlinetask nil)
  20910. (if (not org-adapt-indentation) 0
  20911. (let ((level (org-current-level)))
  20912. (if level (1+ level) 0))))
  20913. ((item plain-list) (org-list-item-body-column post-affiliated))
  20914. (t
  20915. (goto-char start)
  20916. (org-get-indentation))))
  20917. ((memq type '(headline inlinetask nil))
  20918. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20919. (org--get-expected-indentation element t)
  20920. 0))
  20921. ((memq type '(diary-sexp footnote-definition)) 0)
  20922. ;; First paragraph of a footnote definition or an item.
  20923. ;; Indent like parent.
  20924. ((< (line-beginning-position) start)
  20925. (org--get-expected-indentation
  20926. (org-element-property :parent element) t))
  20927. ;; At first line: indent according to previous sibling, if any,
  20928. ;; ignoring footnote definitions and inline tasks, or parent's
  20929. ;; contents.
  20930. ((= (line-beginning-position) start)
  20931. (catch 'exit
  20932. (while t
  20933. (if (= (point-min) start) (throw 'exit 0)
  20934. (goto-char (1- start))
  20935. (let* ((previous (org-element-at-point))
  20936. (parent previous))
  20937. (while (and parent (<= (org-element-property :end parent) start))
  20938. (setq previous parent
  20939. parent (org-element-property :parent parent)))
  20940. (cond
  20941. ((not previous) (throw 'exit 0))
  20942. ((> (org-element-property :end previous) start)
  20943. (throw 'exit (org--get-expected-indentation previous t)))
  20944. ((memq (org-element-type previous)
  20945. '(footnote-definition inlinetask))
  20946. (setq start (org-element-property :begin previous)))
  20947. (t (goto-char (org-element-property :begin previous))
  20948. (throw 'exit
  20949. (if (bolp) (org-get-indentation)
  20950. ;; At first paragraph in an item or
  20951. ;; a footnote definition.
  20952. (org--get-expected-indentation
  20953. (org-element-property :parent previous) t))))))))))
  20954. ;; Otherwise, move to the first non-blank line above.
  20955. (t
  20956. (beginning-of-line)
  20957. (let ((pos (point)))
  20958. (skip-chars-backward " \r\t\n")
  20959. (cond
  20960. ;; Two blank lines end a footnote definition or a plain
  20961. ;; list. When we indent an empty line after them, the
  20962. ;; containing list or footnote definition is over, so it
  20963. ;; qualifies as a previous sibling. Therefore, we indent
  20964. ;; like its first line.
  20965. ((and (memq type '(footnote-definition plain-list))
  20966. (> (count-lines (point) pos) 2))
  20967. (goto-char start)
  20968. (org-get-indentation))
  20969. ;; Line above is the first one of a paragraph at the
  20970. ;; beginning of an item or a footnote definition. Indent
  20971. ;; like parent.
  20972. ((< (line-beginning-position) start)
  20973. (org--get-expected-indentation
  20974. (org-element-property :parent element) t))
  20975. ;; Line above is the beginning of an element, i.e., point
  20976. ;; was originally on the blank lines between element's start
  20977. ;; and contents.
  20978. ((= (line-beginning-position) post-affiliated)
  20979. (org--get-expected-indentation element t))
  20980. ;; POS is after contents in a greater element. Indent like
  20981. ;; the beginning of the element.
  20982. ;;
  20983. ;; As a special case, if point is at the end of a footnote
  20984. ;; definition or an item, indent like the very last element
  20985. ;; within. If that last element is an item, indent like its
  20986. ;; contents.
  20987. ((and (not (eq type 'paragraph))
  20988. (let ((cend (org-element-property :contents-end element)))
  20989. (and cend (<= cend pos))))
  20990. (if (memq type '(footnote-definition item plain-list))
  20991. (let ((last (org-element-at-point)))
  20992. (org--get-expected-indentation
  20993. last (eq (org-element-type last) 'item)))
  20994. (goto-char start)
  20995. (org-get-indentation)))
  20996. ;; In any other case, indent like the current line.
  20997. (t (org-get-indentation)))))))))
  20998. (defun org--align-node-property ()
  20999. "Align node property at point.
  21000. Alignment is done according to `org-property-format', which see."
  21001. (when (save-excursion
  21002. (beginning-of-line)
  21003. (looking-at org-property-re))
  21004. (replace-match
  21005. (concat (match-string 4)
  21006. (org-trim
  21007. (format org-property-format (match-string 1) (match-string 3))))
  21008. t t)))
  21009. (defun org-indent-line ()
  21010. "Indent line depending on context.
  21011. Indentation is done according to the following rules:
  21012. - Footnote definitions, diary sexps, headlines and inline tasks
  21013. have to start at column 0.
  21014. - On the very first line of an element, consider, in order, the
  21015. next rules until one matches:
  21016. 1. If there's a sibling element before, ignoring footnote
  21017. definitions and inline tasks, indent like its first line.
  21018. 2. If element has a parent, indent like its contents. More
  21019. precisely, if parent is an item, indent after the
  21020. description part, if any, or the bullet (see
  21021. `org-list-description-max-indent'). Else, indent like
  21022. parent's first line.
  21023. 3. Otherwise, indent relatively to current level, if
  21024. `org-adapt-indentation' is non-nil, or to left margin.
  21025. - On a blank line at the end of an element, indent according to
  21026. the type of the element. More precisely
  21027. 1. If element is a plain list, an item, or a footnote
  21028. definition, indent like the very last element within.
  21029. 2. If element is a paragraph, indent like its last non blank
  21030. line.
  21031. 3. Otherwise, indent like its very first line.
  21032. - In the code part of a source block, use language major mode
  21033. to indent current line if `org-src-tab-acts-natively' is
  21034. non-nil. If it is nil, do nothing.
  21035. - Otherwise, indent like the first non-blank line above.
  21036. The function doesn't indent an item as it could break the whole
  21037. list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
  21038. \\[org-shiftmetaright].
  21039. Also align node properties according to `org-property-format'."
  21040. (interactive)
  21041. (cond
  21042. (orgstruct-is-++
  21043. (let ((indent-line-function
  21044. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  21045. (indent-according-to-mode)))
  21046. ((org-at-heading-p) 'noindent)
  21047. (t
  21048. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21049. (type (org-element-type element)))
  21050. (cond ((and (memq type '(plain-list item))
  21051. (= (line-beginning-position)
  21052. (org-element-property :post-affiliated element)))
  21053. 'noindent)
  21054. ((and (eq type 'src-block)
  21055. org-src-tab-acts-natively
  21056. (> (line-beginning-position)
  21057. (org-element-property :post-affiliated element))
  21058. (< (line-beginning-position)
  21059. (org-with-wide-buffer
  21060. (goto-char (org-element-property :end element))
  21061. (skip-chars-backward " \r\t\n")
  21062. (line-beginning-position))))
  21063. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21064. (t
  21065. (let ((column (org--get-expected-indentation element nil)))
  21066. ;; Preserve current column.
  21067. (if (<= (current-column) (current-indentation))
  21068. (indent-line-to column)
  21069. (save-excursion (indent-line-to column))))
  21070. ;; Align node property. Also preserve current column.
  21071. (when (eq type 'node-property)
  21072. (let ((column (current-column)))
  21073. (org--align-node-property)
  21074. (org-move-to-column column)))))))))
  21075. (defun org-indent-region (start end)
  21076. "Indent each non-blank line in the region.
  21077. Called from a program, START and END specify the region to
  21078. indent. The function will not indent contents of example blocks,
  21079. verse blocks and export blocks as leading white spaces are
  21080. assumed to be significant there."
  21081. (interactive "r")
  21082. (save-excursion
  21083. (goto-char start)
  21084. (skip-chars-forward " \r\t\n")
  21085. (unless (eobp) (beginning-of-line))
  21086. (let ((indent-to
  21087. (lambda (ind pos)
  21088. ;; Set IND as indentation for all lines between point and
  21089. ;; POS. Blank lines are ignored. Leave point after POS
  21090. ;; once done.
  21091. (let ((limit (copy-marker pos)))
  21092. (while (< (point) limit)
  21093. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21094. (forward-line))
  21095. (set-marker limit nil))))
  21096. (end (copy-marker end)))
  21097. (while (< (point) end)
  21098. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21099. (let* ((element (org-element-at-point))
  21100. (type (org-element-type element))
  21101. (element-end (copy-marker (org-element-property :end element)))
  21102. (ind (org--get-expected-indentation element nil)))
  21103. (cond
  21104. ((or (memq type '(paragraph table table-row))
  21105. (not (or (org-element-property :contents-begin element)
  21106. (memq type
  21107. '(example-block export-block src-block)))))
  21108. ;; Elements here are indented as a single block. Also
  21109. ;; align node properties.
  21110. (when (eq type 'node-property)
  21111. (org--align-node-property)
  21112. (beginning-of-line))
  21113. (funcall indent-to ind (min element-end end)))
  21114. (t
  21115. ;; Elements in this category consist of three parts:
  21116. ;; before the contents, the contents, and after the
  21117. ;; contents. The contents are treated specially,
  21118. ;; according to the element type, or not indented at
  21119. ;; all. Other parts are indented as a single block.
  21120. (let* ((post (copy-marker
  21121. (org-element-property :post-affiliated element)))
  21122. (cbeg
  21123. (copy-marker
  21124. (cond
  21125. ((not (org-element-property :contents-begin element))
  21126. ;; Fake contents for source blocks.
  21127. (org-with-wide-buffer
  21128. (goto-char post)
  21129. (forward-line)
  21130. (point)))
  21131. ((memq type '(footnote-definition item plain-list))
  21132. ;; Contents in these elements could start on
  21133. ;; the same line as the beginning of the
  21134. ;; element. Make sure we start indenting
  21135. ;; from the second line.
  21136. (org-with-wide-buffer
  21137. (goto-char post)
  21138. (end-of-line)
  21139. (skip-chars-forward " \r\t\n")
  21140. (if (eobp) (point) (line-beginning-position))))
  21141. (t (org-element-property :contents-begin element)))))
  21142. (cend (copy-marker
  21143. (or (org-element-property :contents-end element)
  21144. ;; Fake contents for source blocks.
  21145. (org-with-wide-buffer
  21146. (goto-char element-end)
  21147. (skip-chars-backward " \r\t\n")
  21148. (line-beginning-position)))
  21149. t)))
  21150. ;; Do not change items indentation individually as it
  21151. ;; might break the list as a whole. On the other
  21152. ;; hand, when at a plain list, indent it as a whole.
  21153. (cond ((eq type 'plain-list)
  21154. (let ((offset (- ind (org-get-indentation))))
  21155. (unless (zerop offset)
  21156. (indent-rigidly (org-element-property :begin element)
  21157. (org-element-property :end element)
  21158. offset))
  21159. (goto-char cbeg)))
  21160. ((eq type 'item) (goto-char cbeg))
  21161. (t (funcall indent-to ind (min cbeg end))))
  21162. (when (< (point) end)
  21163. (cl-case type
  21164. ((example-block export-block verse-block))
  21165. (src-block
  21166. ;; In a source block, indent source code
  21167. ;; according to language major mode, but only if
  21168. ;; `org-src-tab-acts-natively' is non-nil.
  21169. (when (and (< (point) end) org-src-tab-acts-natively)
  21170. (ignore-errors
  21171. (org-babel-do-in-edit-buffer
  21172. (indent-region (point-min) (point-max))))))
  21173. (t (org-indent-region (point) (min cend end))))
  21174. (goto-char (min cend end))
  21175. (when (< (point) end)
  21176. (funcall indent-to ind (min element-end end))))
  21177. (set-marker post nil)
  21178. (set-marker cbeg nil)
  21179. (set-marker cend nil))))
  21180. (set-marker element-end nil))))
  21181. (set-marker end nil))))
  21182. (defun org-indent-drawer ()
  21183. "Indent the drawer at point."
  21184. (interactive)
  21185. (unless (save-excursion
  21186. (beginning-of-line)
  21187. (looking-at-p org-drawer-regexp))
  21188. (user-error "Not at a drawer"))
  21189. (let ((element (org-element-at-point)))
  21190. (unless (memq (org-element-type element) '(drawer property-drawer))
  21191. (user-error "Not at a drawer"))
  21192. (org-with-wide-buffer
  21193. (org-indent-region (org-element-property :begin element)
  21194. (org-element-property :end element))))
  21195. (message "Drawer at point indented"))
  21196. (defun org-indent-block ()
  21197. "Indent the block at point."
  21198. (interactive)
  21199. (unless (save-excursion
  21200. (beginning-of-line)
  21201. (let ((case-fold-search t))
  21202. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21203. (user-error "Not at a block"))
  21204. (let ((element (org-element-at-point)))
  21205. (unless (memq (org-element-type element)
  21206. '(comment-block center-block dynamic-block example-block
  21207. export-block quote-block special-block
  21208. src-block verse-block))
  21209. (user-error "Not at a block"))
  21210. (org-with-wide-buffer
  21211. (org-indent-region (org-element-property :begin element)
  21212. (org-element-property :end element))))
  21213. (message "Block at point indented"))
  21214. ;;; Filling
  21215. ;; We use our own fill-paragraph and auto-fill functions.
  21216. ;; `org-fill-paragraph' relies on adaptive filling and context
  21217. ;; checking. Appropriate `fill-prefix' is computed with
  21218. ;; `org-adaptive-fill-function'.
  21219. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21220. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21221. ;; `org-adaptive-fill-function' value. Internally,
  21222. ;; `org-comment-line-break-function' breaks the line.
  21223. ;; `org-setup-filling' installs filling and auto-filling related
  21224. ;; variables during `org-mode' initialization.
  21225. (defvar org-element-paragraph-separate) ; org-element.el
  21226. (defun org-setup-filling ()
  21227. (require 'org-element)
  21228. ;; Prevent auto-fill from inserting unwanted new items.
  21229. (when (boundp 'fill-nobreak-predicate)
  21230. (setq-local
  21231. fill-nobreak-predicate
  21232. (org-uniquify
  21233. (append fill-nobreak-predicate
  21234. '(org-fill-line-break-nobreak-p
  21235. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21236. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21237. (setq-local paragraph-start paragraph-ending)
  21238. (setq-local paragraph-separate paragraph-ending))
  21239. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21240. (setq-local auto-fill-inhibit-regexp nil)
  21241. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21242. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21243. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21244. (defun org-fill-line-break-nobreak-p ()
  21245. "Non-nil when a new line at point would create an Org line break."
  21246. (save-excursion
  21247. (skip-chars-backward "[ \t]")
  21248. (skip-chars-backward "\\\\")
  21249. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21250. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21251. "Non-nil when a new line at point would split a timestamp."
  21252. (and (org-at-timestamp-p t)
  21253. (not (looking-at org-ts-regexp-both))))
  21254. (declare-function message-in-body-p "message" ())
  21255. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21256. (defun org-adaptive-fill-function ()
  21257. "Compute a fill prefix for the current line.
  21258. Return fill prefix, as a string, or nil if current line isn't
  21259. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21260. matches in paragraphs or comments, use it."
  21261. (catch 'exit
  21262. (when (derived-mode-p 'message-mode)
  21263. (save-excursion
  21264. (beginning-of-line)
  21265. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21266. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21267. ((looking-at message-cite-prefix-regexp)
  21268. (throw 'exit (match-string-no-properties 0)))
  21269. ((looking-at org-outline-regexp)
  21270. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21271. (org-with-wide-buffer
  21272. (unless (org-at-heading-p)
  21273. (let* ((p (line-beginning-position))
  21274. (element (save-excursion
  21275. (beginning-of-line)
  21276. (org-element-at-point)))
  21277. (type (org-element-type element))
  21278. (post-affiliated (org-element-property :post-affiliated element)))
  21279. (unless (< p post-affiliated)
  21280. (cl-case type
  21281. (comment
  21282. (save-excursion
  21283. (beginning-of-line)
  21284. (looking-at "[ \t]*")
  21285. (concat (match-string 0) "# ")))
  21286. (footnote-definition "")
  21287. ((item plain-list)
  21288. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21289. (paragraph
  21290. ;; Fill prefix is usually the same as the current line,
  21291. ;; unless the paragraph is at the beginning of an item.
  21292. (let ((parent (org-element-property :parent element)))
  21293. (save-excursion
  21294. (beginning-of-line)
  21295. (cond ((eq (org-element-type parent) 'item)
  21296. (make-string (org-list-item-body-column
  21297. (org-element-property :begin parent))
  21298. ?\s))
  21299. ((and adaptive-fill-regexp
  21300. ;; Locally disable
  21301. ;; `adaptive-fill-function' to let
  21302. ;; `fill-context-prefix' handle
  21303. ;; `adaptive-fill-regexp' variable.
  21304. (let (adaptive-fill-function)
  21305. (fill-context-prefix
  21306. post-affiliated
  21307. (org-element-property :end element)))))
  21308. ((looking-at "[ \t]+") (match-string 0))
  21309. (t "")))))
  21310. (comment-block
  21311. ;; Only fill contents if P is within block boundaries.
  21312. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21313. (forward-line)
  21314. (point)))
  21315. (cend (save-excursion
  21316. (goto-char (org-element-property :end element))
  21317. (skip-chars-backward " \r\t\n")
  21318. (line-beginning-position))))
  21319. (when (and (>= p cbeg) (< p cend))
  21320. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21321. (match-string 0)
  21322. "")))))))))))
  21323. (declare-function message-goto-body "message" ())
  21324. (defvar message-cite-prefix-regexp) ; From message.el
  21325. (defun org-fill-paragraph (&optional justify)
  21326. "Fill element at point, when applicable.
  21327. This function only applies to comment blocks, comments, example
  21328. blocks and paragraphs. Also, as a special case, re-align table
  21329. when point is at one.
  21330. If JUSTIFY is non-nil (interactively, with prefix argument),
  21331. justify as well. If `sentence-end-double-space' is non-nil, then
  21332. period followed by one space does not end a sentence, so don't
  21333. break a line there. The variable `fill-column' controls the
  21334. width for filling.
  21335. For convenience, when point is at a plain list, an item or
  21336. a footnote definition, try to fill the first paragraph within."
  21337. (interactive)
  21338. (if (and (derived-mode-p 'message-mode)
  21339. (or (not (message-in-body-p))
  21340. (save-excursion (move-beginning-of-line 1)
  21341. (looking-at message-cite-prefix-regexp))))
  21342. ;; First ensure filling is correct in message-mode.
  21343. (let ((fill-paragraph-function
  21344. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21345. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21346. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21347. (paragraph-separate
  21348. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21349. (fill-paragraph nil))
  21350. (with-syntax-table org-mode-transpose-word-syntax-table
  21351. ;; Move to end of line in order to get the first paragraph
  21352. ;; within a plain list or a footnote definition.
  21353. (let ((element (save-excursion
  21354. (end-of-line)
  21355. (or (ignore-errors (org-element-at-point))
  21356. (user-error "An element cannot be parsed line %d"
  21357. (line-number-at-pos (point)))))))
  21358. ;; First check if point is in a blank line at the beginning of
  21359. ;; the buffer. In that case, ignore filling.
  21360. (cl-case (org-element-type element)
  21361. ;; Use major mode filling function is src blocks.
  21362. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21363. ;; Align Org tables, leave table.el tables as-is.
  21364. (table-row (org-table-align) t)
  21365. (table
  21366. (when (eq (org-element-property :type element) 'org)
  21367. (save-excursion
  21368. (goto-char (org-element-property :post-affiliated element))
  21369. (org-table-align)))
  21370. t)
  21371. (paragraph
  21372. ;; Paragraphs may contain `line-break' type objects.
  21373. (let ((beg (max (point-min)
  21374. (org-element-property :contents-begin element)))
  21375. (end (min (point-max)
  21376. (org-element-property :contents-end element))))
  21377. ;; Do nothing if point is at an affiliated keyword.
  21378. (if (< (line-end-position) beg) t
  21379. (when (derived-mode-p 'message-mode)
  21380. ;; In `message-mode', do not fill following citation
  21381. ;; in current paragraph nor text before message body.
  21382. (let ((body-start (save-excursion (message-goto-body))))
  21383. (when body-start (setq beg (max body-start beg))))
  21384. (when (save-excursion
  21385. (re-search-forward
  21386. (concat "^" message-cite-prefix-regexp) end t))
  21387. (setq end (match-beginning 0))))
  21388. ;; Fill paragraph, taking line breaks into account.
  21389. (save-excursion
  21390. (goto-char beg)
  21391. (let ((cuts (list beg)))
  21392. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21393. (when (eq 'line-break
  21394. (org-element-type
  21395. (save-excursion (backward-char)
  21396. (org-element-context))))
  21397. (push (point) cuts)))
  21398. (dolist (c (delq end cuts))
  21399. (fill-region-as-paragraph c end justify)
  21400. (setq end c))))
  21401. t)))
  21402. ;; Contents of `comment-block' type elements should be
  21403. ;; filled as plain text, but only if point is within block
  21404. ;; markers.
  21405. (comment-block
  21406. (let* ((case-fold-search t)
  21407. (beg (save-excursion
  21408. (goto-char (org-element-property :begin element))
  21409. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21410. (forward-line)
  21411. (point)))
  21412. (end (save-excursion
  21413. (goto-char (org-element-property :end element))
  21414. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21415. (line-beginning-position))))
  21416. (if (or (< (point) beg) (> (point) end)) t
  21417. (fill-region-as-paragraph
  21418. (save-excursion (end-of-line)
  21419. (re-search-backward "^[ \t]*$" beg 'move)
  21420. (line-beginning-position))
  21421. (save-excursion (beginning-of-line)
  21422. (re-search-forward "^[ \t]*$" end 'move)
  21423. (line-beginning-position))
  21424. justify))))
  21425. ;; Fill comments.
  21426. (comment
  21427. (let ((begin (org-element-property :post-affiliated element))
  21428. (end (org-element-property :end element)))
  21429. (when (and (>= (point) begin) (<= (point) end))
  21430. (let ((begin (save-excursion
  21431. (end-of-line)
  21432. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21433. (progn (forward-line) (point))
  21434. begin)))
  21435. (end (save-excursion
  21436. (end-of-line)
  21437. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21438. (1- (line-beginning-position))
  21439. (skip-chars-backward " \r\t\n")
  21440. (line-end-position)))))
  21441. ;; Do not fill comments when at a blank line.
  21442. (when (> end begin)
  21443. (let ((fill-prefix
  21444. (save-excursion
  21445. (beginning-of-line)
  21446. (looking-at "[ \t]*#")
  21447. (let ((comment-prefix (match-string 0)))
  21448. (goto-char (match-end 0))
  21449. (if (looking-at adaptive-fill-regexp)
  21450. (concat comment-prefix (match-string 0))
  21451. (concat comment-prefix " "))))))
  21452. (save-excursion
  21453. (fill-region-as-paragraph begin end justify))))))
  21454. t))
  21455. ;; Ignore every other element.
  21456. (otherwise t))))))
  21457. (defun org-auto-fill-function ()
  21458. "Auto-fill function."
  21459. ;; Check if auto-filling is meaningful.
  21460. (let ((fc (current-fill-column)))
  21461. (when (and fc (> (current-column) fc))
  21462. (let* ((fill-prefix (org-adaptive-fill-function))
  21463. ;; Enforce empty fill prefix, if required. Otherwise, it
  21464. ;; will be computed again.
  21465. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21466. (when fill-prefix (do-auto-fill))))))
  21467. (defun org-comment-line-break-function (&optional soft)
  21468. "Break line at point and indent, continuing comment if within one.
  21469. The inserted newline is marked hard if variable
  21470. `use-hard-newlines' is true, unless optional argument SOFT is
  21471. non-nil."
  21472. (if soft (insert-and-inherit ?\n) (newline 1))
  21473. (save-excursion (forward-char -1) (delete-horizontal-space))
  21474. (delete-horizontal-space)
  21475. (indent-to-left-margin)
  21476. (insert-before-markers-and-inherit fill-prefix))
  21477. ;;; Fixed Width Areas
  21478. (defun org-toggle-fixed-width ()
  21479. "Toggle fixed-width markup.
  21480. Add or remove fixed-width markup on current line, whenever it
  21481. makes sense. Return an error otherwise.
  21482. If a region is active and if it contains only fixed-width areas
  21483. or blank lines, remove all fixed-width markup in it. If the
  21484. region contains anything else, convert all non-fixed-width lines
  21485. to fixed-width ones.
  21486. Blank lines at the end of the region are ignored unless the
  21487. region only contains such lines."
  21488. (interactive)
  21489. (if (not (org-region-active-p))
  21490. ;; No region:
  21491. ;;
  21492. ;; Remove fixed width marker only in a fixed-with element.
  21493. ;;
  21494. ;; Add fixed width maker in paragraphs, in blank lines after
  21495. ;; elements or at the beginning of a headline or an inlinetask,
  21496. ;; and before any one-line elements (e.g., a clock).
  21497. (progn
  21498. (beginning-of-line)
  21499. (let* ((element (org-element-at-point))
  21500. (type (org-element-type element)))
  21501. (cond
  21502. ((and (eq type 'fixed-width)
  21503. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21504. (replace-match
  21505. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21506. ((and (memq type '(babel-call clock comment diary-sexp headline
  21507. horizontal-rule keyword paragraph
  21508. planning))
  21509. (<= (org-element-property :post-affiliated element) (point)))
  21510. (skip-chars-forward " \t")
  21511. (insert ": "))
  21512. ((and (looking-at-p "[ \t]*$")
  21513. (or (eq type 'inlinetask)
  21514. (save-excursion
  21515. (skip-chars-forward " \r\t\n")
  21516. (<= (org-element-property :end element) (point)))))
  21517. (delete-region (point) (line-end-position))
  21518. (org-indent-line)
  21519. (insert ": "))
  21520. (t (user-error "Cannot insert a fixed-width line here")))))
  21521. ;; Region active.
  21522. (let* ((begin (save-excursion
  21523. (goto-char (region-beginning))
  21524. (line-beginning-position)))
  21525. (end (copy-marker
  21526. (save-excursion
  21527. (goto-char (region-end))
  21528. (unless (eolp) (beginning-of-line))
  21529. (if (save-excursion (re-search-backward "\\S-" begin t))
  21530. (progn (skip-chars-backward " \r\t\n") (point))
  21531. (point)))))
  21532. (all-fixed-width-p
  21533. (catch 'not-all-p
  21534. (save-excursion
  21535. (goto-char begin)
  21536. (skip-chars-forward " \r\t\n")
  21537. (when (eobp) (throw 'not-all-p nil))
  21538. (while (< (point) end)
  21539. (let ((element (org-element-at-point)))
  21540. (if (eq (org-element-type element) 'fixed-width)
  21541. (goto-char (org-element-property :end element))
  21542. (throw 'not-all-p nil))))
  21543. t))))
  21544. (if all-fixed-width-p
  21545. (save-excursion
  21546. (goto-char begin)
  21547. (while (< (point) end)
  21548. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21549. (replace-match
  21550. "" nil nil nil
  21551. (if (= (line-end-position) (match-end 0)) 0 1)))
  21552. (forward-line)))
  21553. (let ((min-ind (point-max)))
  21554. ;; Find minimum indentation across all lines.
  21555. (save-excursion
  21556. (goto-char begin)
  21557. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21558. (setq min-ind 0)
  21559. (catch 'zerop
  21560. (while (< (point) end)
  21561. (unless (looking-at-p "[ \t]*$")
  21562. (let ((ind (org-get-indentation)))
  21563. (setq min-ind (min min-ind ind))
  21564. (when (zerop ind) (throw 'zerop t))))
  21565. (forward-line)))))
  21566. ;; Loop over all lines and add fixed-width markup everywhere
  21567. ;; but in fixed-width lines.
  21568. (save-excursion
  21569. (goto-char begin)
  21570. (while (< (point) end)
  21571. (cond
  21572. ((org-at-heading-p)
  21573. (insert ": ")
  21574. (forward-line)
  21575. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21576. (insert ":")
  21577. (forward-line)))
  21578. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21579. (let* ((element (org-element-at-point))
  21580. (element-end (org-element-property :end element)))
  21581. (if (eq (org-element-type element) 'fixed-width)
  21582. (progn (goto-char element-end)
  21583. (skip-chars-backward " \r\t\n")
  21584. (forward-line))
  21585. (let ((limit (min end element-end)))
  21586. (while (< (point) limit)
  21587. (org-move-to-column min-ind t)
  21588. (insert ": ")
  21589. (forward-line))))))
  21590. (t
  21591. (org-move-to-column min-ind t)
  21592. (insert ": ")
  21593. (forward-line)))))))
  21594. (set-marker end nil))))
  21595. ;;; Comments
  21596. ;; Org comments syntax is quite complex. It requires the entire line
  21597. ;; to be just a comment. Also, even with the right syntax at the
  21598. ;; beginning of line, some some elements (i.e. verse-block or
  21599. ;; example-block) don't accept comments. Usual Emacs comment commands
  21600. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21601. ;; Org still relies on `comment-dwim', but cannot trust
  21602. ;; `comment-only-p'. So, `comment-region-function' and
  21603. ;; `uncomment-region-function' both point
  21604. ;; to`org-comment-or-uncomment-region'. Eventually,
  21605. ;; `org-insert-comment' takes care of insertion of comments at the
  21606. ;; beginning of line.
  21607. ;; `org-setup-comments-handling' install comments related variables
  21608. ;; during `org-mode' initialization.
  21609. (defun org-setup-comments-handling ()
  21610. (interactive)
  21611. (setq-local comment-use-syntax nil)
  21612. (setq-local comment-start "# ")
  21613. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21614. (setq-local comment-insert-comment-function 'org-insert-comment)
  21615. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21616. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21617. (defun org-insert-comment ()
  21618. "Insert an empty comment above current line.
  21619. If the line is empty, insert comment at its beginning. When
  21620. point is within a source block, comment according to the related
  21621. major mode."
  21622. (if (let ((element (org-element-at-point)))
  21623. (and (eq (org-element-type element) 'src-block)
  21624. (< (save-excursion
  21625. (goto-char (org-element-property :post-affiliated element))
  21626. (line-end-position))
  21627. (point))
  21628. (> (save-excursion
  21629. (goto-char (org-element-property :end element))
  21630. (skip-chars-backward " \r\t\n")
  21631. (line-beginning-position))
  21632. (point))))
  21633. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21634. (beginning-of-line)
  21635. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21636. (open-line 1))
  21637. (org-indent-line)
  21638. (insert "# ")))
  21639. (defvar comment-empty-lines) ; From newcomment.el.
  21640. (defun org-comment-or-uncomment-region (beg end &rest _)
  21641. "Comment or uncomment each non-blank line in the region.
  21642. Uncomment each non-blank line between BEG and END if it only
  21643. contains commented lines. Otherwise, comment them. If region is
  21644. strictly within a source block, use appropriate comment syntax."
  21645. (if (let ((element (org-element-at-point)))
  21646. (and (eq (org-element-type element) 'src-block)
  21647. (< (save-excursion
  21648. (goto-char (org-element-property :post-affiliated element))
  21649. (line-end-position))
  21650. beg)
  21651. (>= (save-excursion
  21652. (goto-char (org-element-property :end element))
  21653. (skip-chars-backward " \r\t\n")
  21654. (line-beginning-position))
  21655. end)))
  21656. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21657. (save-restriction
  21658. ;; Restrict region
  21659. (narrow-to-region (save-excursion (goto-char beg)
  21660. (skip-chars-forward " \r\t\n" end)
  21661. (line-beginning-position))
  21662. (save-excursion (goto-char end)
  21663. (skip-chars-backward " \r\t\n" beg)
  21664. (line-end-position)))
  21665. (let ((uncommentp
  21666. ;; UNCOMMENTP is non-nil when every non blank line between
  21667. ;; BEG and END is a comment.
  21668. (save-excursion
  21669. (goto-char (point-min))
  21670. (while (and (not (eobp))
  21671. (let ((element (org-element-at-point)))
  21672. (and (eq (org-element-type element) 'comment)
  21673. (goto-char (min (point-max)
  21674. (org-element-property
  21675. :end element)))))))
  21676. (eobp))))
  21677. (if uncommentp
  21678. ;; Only blank lines and comments in region: uncomment it.
  21679. (save-excursion
  21680. (goto-char (point-min))
  21681. (while (not (eobp))
  21682. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21683. (replace-match "" nil nil nil 1))
  21684. (forward-line)))
  21685. ;; Comment each line in region.
  21686. (let ((min-indent (point-max)))
  21687. ;; First find the minimum indentation across all lines.
  21688. (save-excursion
  21689. (goto-char (point-min))
  21690. (while (and (not (eobp)) (not (zerop min-indent)))
  21691. (unless (looking-at "[ \t]*$")
  21692. (setq min-indent (min min-indent (current-indentation))))
  21693. (forward-line)))
  21694. ;; Then loop over all lines.
  21695. (save-excursion
  21696. (goto-char (point-min))
  21697. (while (not (eobp))
  21698. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21699. ;; Don't get fooled by invisible text (e.g. link path)
  21700. ;; when moving to column MIN-INDENT.
  21701. (let ((buffer-invisibility-spec nil))
  21702. (org-move-to-column min-indent t))
  21703. (insert comment-start))
  21704. (forward-line)))))))))
  21705. (defun org-comment-dwim (_arg)
  21706. "Call `comment-dwim' within a source edit buffer if needed."
  21707. (interactive "*P")
  21708. (if (org-in-src-block-p)
  21709. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21710. (call-interactively 'comment-dwim)))
  21711. ;;; Timestamps API
  21712. ;; This section contains tools to operate on timestamp objects, as
  21713. ;; returned by, e.g. `org-element-context'.
  21714. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21715. "Encode TIMESTAMP object into Emacs internal time.
  21716. Use end of date range or time range when END is non-nil."
  21717. (apply #'encode-time
  21718. (cons 0
  21719. (mapcar
  21720. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21721. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21722. '(:minute-start :hour-start :day-start :month-start
  21723. :year-start))))))
  21724. (defun org-timestamp-has-time-p (timestamp)
  21725. "Non-nil when TIMESTAMP has a time specified."
  21726. (org-element-property :hour-start timestamp))
  21727. (defun org-timestamp-format (timestamp format &optional end utc)
  21728. "Format a TIMESTAMP object into a string.
  21729. FORMAT is a format specifier to be passed to
  21730. `format-time-string'.
  21731. When optional argument END is non-nil, use end of date-range or
  21732. time-range, if possible.
  21733. When optional argument UTC is non-nil, time will be expressed as
  21734. Universal Time."
  21735. (format-time-string
  21736. format (org-timestamp--to-internal-time timestamp end)
  21737. (and utc t)))
  21738. (defun org-timestamp-split-range (timestamp &optional end)
  21739. "Extract a TIMESTAMP object from a date or time range.
  21740. END, when non-nil, means extract the end of the range.
  21741. Otherwise, extract its start.
  21742. Return a new timestamp object."
  21743. (let ((type (org-element-property :type timestamp)))
  21744. (if (memq type '(active inactive diary)) timestamp
  21745. (let ((split-ts (org-element-copy timestamp)))
  21746. ;; Set new type.
  21747. (org-element-put-property
  21748. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21749. ;; Copy start properties over end properties if END is
  21750. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21751. (let ((p-alist '((:minute-start . :minute-end)
  21752. (:hour-start . :hour-end)
  21753. (:day-start . :day-end)
  21754. (:month-start . :month-end)
  21755. (:year-start . :year-end))))
  21756. (dolist (p-cell p-alist)
  21757. (org-element-put-property
  21758. split-ts
  21759. (funcall (if end #'car #'cdr) p-cell)
  21760. (org-element-property
  21761. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21762. ;; Eventually refresh `:raw-value'.
  21763. (org-element-put-property split-ts :raw-value nil)
  21764. (org-element-put-property
  21765. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21766. (defun org-timestamp-translate (timestamp &optional boundary)
  21767. "Translate TIMESTAMP object to custom format.
  21768. Format string is defined in `org-time-stamp-custom-formats',
  21769. which see.
  21770. When optional argument BOUNDARY is non-nil, it is either the
  21771. symbol `start' or `end'. In this case, only translate the
  21772. starting or ending part of TIMESTAMP if it is a date or time
  21773. range. Otherwise, translate both parts.
  21774. Return timestamp as-is if `org-display-custom-times' is nil or if
  21775. it has a `diary' type."
  21776. (let ((type (org-element-property :type timestamp)))
  21777. (if (or (not org-display-custom-times) (eq type 'diary))
  21778. (org-element-interpret-data timestamp)
  21779. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21780. org-time-stamp-custom-formats)))
  21781. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21782. (concat (org-timestamp-format timestamp fmt)
  21783. "--"
  21784. (org-timestamp-format timestamp fmt t))
  21785. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21786. ;;; Other stuff.
  21787. (defvar reftex-docstruct-symbol)
  21788. (defvar reftex-cite-format)
  21789. (defvar org--rds)
  21790. (defun org-reftex-citation ()
  21791. "Use reftex-citation to insert a citation into the buffer.
  21792. This looks for a line like
  21793. #+BIBLIOGRAPHY: foo plain option:-d
  21794. and derives from it that foo.bib is the bibliography file relevant
  21795. for this document. It then installs the necessary environment for RefTeX
  21796. to work in this buffer and calls `reftex-citation' to insert a citation
  21797. into the buffer.
  21798. Export of such citations to both LaTeX and HTML is handled by the contributed
  21799. package ox-bibtex by Taru Karttunen."
  21800. (interactive)
  21801. (let ((reftex-docstruct-symbol 'org--rds)
  21802. (reftex-cite-format "\\cite{%l}")
  21803. org--rds bib)
  21804. (save-excursion
  21805. (save-restriction
  21806. (widen)
  21807. (let ((case-fold-search t)
  21808. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21809. (if (not (save-excursion
  21810. (or (re-search-forward re nil t)
  21811. (re-search-backward re nil t))))
  21812. (user-error "No bibliography defined in file")
  21813. (setq bib (concat (match-string 1) ".bib")
  21814. org--rds (list (list 'bib bib)))))))
  21815. (call-interactively 'reftex-citation)))
  21816. ;;;; Functions extending outline functionality
  21817. (defun org-beginning-of-line (&optional arg)
  21818. "Go to the beginning of the current line. If that is invisible, continue
  21819. to a visible line beginning. This makes the function of C-a more intuitive.
  21820. If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
  21821. first attempt, and only move to after the tags when the cursor is already
  21822. beyond the end of the headline."
  21823. (interactive "P")
  21824. (let ((pos (point))
  21825. (special (if (consp org-special-ctrl-a/e)
  21826. (car org-special-ctrl-a/e)
  21827. org-special-ctrl-a/e))
  21828. deactivate-mark refpos)
  21829. (call-interactively (if (bound-and-true-p visual-line-mode)
  21830. #'beginning-of-visual-line
  21831. #'move-beginning-of-line))
  21832. (cond
  21833. ((or arg (not special)))
  21834. ((and (looking-at org-complex-heading-regexp)
  21835. (eq (char-after (match-end 1)) ?\s))
  21836. (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21837. (point-at-eol)))
  21838. (goto-char
  21839. (if (eq special t)
  21840. (cond ((> pos refpos) refpos)
  21841. ((= pos (point)) refpos)
  21842. (t (point)))
  21843. (cond ((> pos (point)) (point))
  21844. ((not (eq last-command this-command)) (point))
  21845. (t refpos)))))
  21846. ((org-at-item-p)
  21847. ;; Being at an item and not looking at an the item means point
  21848. ;; was previously moved to beginning of a visual line, which
  21849. ;; doesn't contain the item. Therefore, do nothing special,
  21850. ;; just stay here.
  21851. (when (looking-at org-list-full-item-re)
  21852. ;; Set special position at first white space character after
  21853. ;; bullet, and check-box, if any.
  21854. (let ((after-bullet
  21855. (let ((box (match-end 3)))
  21856. (if (not box) (match-end 1)
  21857. (let ((after (char-after box)))
  21858. (if (and after (= after ? )) (1+ box) box))))))
  21859. ;; Special case: Move point to special position when
  21860. ;; currently after it or at beginning of line.
  21861. (if (eq special t)
  21862. (when (or (> pos after-bullet) (= (point) pos))
  21863. (goto-char after-bullet))
  21864. ;; Reversed case: Move point to special position when
  21865. ;; point was already at beginning of line and command is
  21866. ;; repeated.
  21867. (when (and (= (point) pos) (eq last-command this-command))
  21868. (goto-char after-bullet))))))))
  21869. (setq disable-point-adjustment
  21870. (or (not (invisible-p (point)))
  21871. (not (invisible-p (max (point-min) (1- (point))))))))
  21872. (defun org-end-of-line (&optional arg)
  21873. "Go to the end of the line.
  21874. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21875. tags on the first attempt, and only move to after the tags when
  21876. the cursor is already beyond the end of the headline."
  21877. (interactive "P")
  21878. (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
  21879. org-special-ctrl-a/e))
  21880. (move-fun (cond ((bound-and-true-p visual-line-mode)
  21881. 'end-of-visual-line)
  21882. ((fboundp 'move-end-of-line) 'move-end-of-line)
  21883. (t 'end-of-line)))
  21884. deactivate-mark)
  21885. (if (or (not special) arg) (call-interactively move-fun)
  21886. (let* ((element (save-excursion (beginning-of-line)
  21887. (org-element-at-point)))
  21888. (type (org-element-type element)))
  21889. (cond
  21890. ((memq type '(headline inlinetask))
  21891. (let ((pos (point)))
  21892. (beginning-of-line 1)
  21893. (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
  21894. (if (eq special t)
  21895. (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
  21896. (goto-char (match-beginning 1))
  21897. (goto-char (match-end 0)))
  21898. (if (or (< pos (match-end 0))
  21899. (not (eq this-command last-command)))
  21900. (goto-char (match-end 0))
  21901. (goto-char (match-beginning 1))))
  21902. (call-interactively move-fun))))
  21903. ((outline-invisible-p (line-end-position))
  21904. ;; If element is hidden, `move-end-of-line' would put point
  21905. ;; after it. Use `end-of-line' to stay on current line.
  21906. (call-interactively 'end-of-line))
  21907. (t (call-interactively move-fun))))))
  21908. (setq disable-point-adjustment
  21909. (or (not (invisible-p (point)))
  21910. (not (invisible-p (max (point-min) (1- (point))))))))
  21911. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21912. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21913. (defun org-backward-sentence (&optional _arg)
  21914. "Go to beginning of sentence, or beginning of table field.
  21915. This will call `backward-sentence' or `org-table-beginning-of-field',
  21916. depending on context."
  21917. (interactive)
  21918. (let* ((element (org-element-at-point))
  21919. (contents-begin (org-element-property :contents-begin element))
  21920. (table (org-element-lineage element '(table) t)))
  21921. (if (and table
  21922. (> (point) contents-begin)
  21923. (<= (point) (org-element-property :contents-end table)))
  21924. (call-interactively #'org-table-beginning-of-field)
  21925. (save-restriction
  21926. (when (and contents-begin
  21927. (< (point-min) contents-begin)
  21928. (> (point) contents-begin))
  21929. (narrow-to-region contents-begin
  21930. (org-element-property :contents-end element)))
  21931. (call-interactively #'backward-sentence)))))
  21932. (defun org-forward-sentence (&optional _arg)
  21933. "Go to end of sentence, or end of table field.
  21934. This will call `forward-sentence' or `org-table-end-of-field',
  21935. depending on context."
  21936. (interactive)
  21937. (let* ((element (org-element-at-point))
  21938. (contents-end (org-element-property :contents-end element))
  21939. (table (org-element-lineage element '(table) t)))
  21940. (if (and table
  21941. (>= (point) (org-element-property :contents-begin table))
  21942. (< (point) contents-end))
  21943. (call-interactively #'org-table-end-of-field)
  21944. (save-restriction
  21945. (when (and contents-end
  21946. (> (point-max) contents-end)
  21947. ;; Skip blank lines between elements.
  21948. (< (org-element-property :end element)
  21949. (save-excursion (goto-char contents-end)
  21950. (skip-chars-forward " \r\t\n"))))
  21951. (narrow-to-region (org-element-property :contents-begin element)
  21952. contents-end))
  21953. (call-interactively #'forward-sentence)))))
  21954. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21955. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21956. (defun org-kill-line (&optional _arg)
  21957. "Kill line, to tags or end of line."
  21958. (interactive)
  21959. (cond
  21960. ((or (not org-special-ctrl-k)
  21961. (bolp)
  21962. (not (org-at-heading-p)))
  21963. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21964. org-ctrl-k-protect-subtree
  21965. (or (eq org-ctrl-k-protect-subtree 'error)
  21966. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21967. (user-error "C-k aborted as it would kill a hidden subtree"))
  21968. (call-interactively
  21969. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21970. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21971. (kill-region (point) (match-beginning 1))
  21972. (org-set-tags nil t))
  21973. (t (kill-region (point) (point-at-eol)))))
  21974. (define-key org-mode-map "\C-k" 'org-kill-line)
  21975. (defun org-yank (&optional arg)
  21976. "Yank. If the kill is a subtree, treat it specially.
  21977. This command will look at the current kill and check if is a single
  21978. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21979. cursor is at the beginning of a line or after the stars of a currently
  21980. empty headline, then the yank is handled specially. How exactly depends
  21981. on the value of the following variables.
  21982. `org-yank-folded-subtrees'
  21983. By default, this variable is non-nil, which results in subtree(s)
  21984. being folded after insertion, but only if doing so would now
  21985. swallow text after the yanked text.
  21986. `org-yank-adjusted-subtrees'
  21987. When non-nil (the default value is nil), the subtree will be
  21988. promoted or demoted in order to fit into the local outline tree
  21989. structure, which means that the level will be adjusted so that it
  21990. becomes the smaller one of the two *visible* surrounding headings.
  21991. Any prefix to this command will cause `yank' to be called directly with
  21992. no special treatment. In particular, a simple \\[universal-argument] prefix \
  21993. will just
  21994. plainly yank the text as it is.
  21995. \[1] The test checks if the first non-white line is a heading
  21996. and if there are no other headings with fewer stars."
  21997. (interactive "P")
  21998. (org-yank-generic 'yank arg))
  21999. (defun org-yank-generic (command arg)
  22000. "Perform some yank-like command.
  22001. This function implements the behavior described in the `org-yank'
  22002. documentation. However, it has been generalized to work for any
  22003. interactive command with similar behavior."
  22004. ;; pretend to be command COMMAND
  22005. (setq this-command command)
  22006. (if arg
  22007. (call-interactively command)
  22008. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  22009. (and (org-kill-is-subtree-p)
  22010. (or (bolp)
  22011. (and (looking-at "[ \t]*$")
  22012. (string-match
  22013. "\\`\\*+\\'"
  22014. (buffer-substring (point-at-bol) (point)))))))
  22015. swallowp)
  22016. (cond
  22017. ((and subtreep org-yank-folded-subtrees)
  22018. (let ((beg (point))
  22019. end)
  22020. (if (and subtreep org-yank-adjusted-subtrees)
  22021. (org-paste-subtree nil nil 'for-yank)
  22022. (call-interactively command))
  22023. (setq end (point))
  22024. (goto-char beg)
  22025. (when (and (bolp) subtreep
  22026. (not (setq swallowp
  22027. (org-yank-folding-would-swallow-text beg end))))
  22028. (org-with-limited-levels
  22029. (or (looking-at org-outline-regexp)
  22030. (re-search-forward org-outline-regexp-bol end t))
  22031. (while (and (< (point) end) (looking-at org-outline-regexp))
  22032. (outline-hide-subtree)
  22033. (org-cycle-show-empty-lines 'folded)
  22034. (condition-case nil
  22035. (outline-forward-same-level 1)
  22036. (error (goto-char end))))))
  22037. (when swallowp
  22038. (message
  22039. "Inserted text not folded because that would swallow text"))
  22040. (goto-char end)
  22041. (skip-chars-forward " \t\n\r")
  22042. (beginning-of-line 1)
  22043. (push-mark beg 'nomsg)))
  22044. ((and subtreep org-yank-adjusted-subtrees)
  22045. (let ((beg (point-at-bol)))
  22046. (org-paste-subtree nil nil 'for-yank)
  22047. (push-mark beg 'nomsg)))
  22048. (t
  22049. (call-interactively command))))))
  22050. (defun org-yank-folding-would-swallow-text (beg end)
  22051. "Would hide-subtree at BEG swallow any text after END?"
  22052. (let (level)
  22053. (org-with-limited-levels
  22054. (save-excursion
  22055. (goto-char beg)
  22056. (when (or (looking-at org-outline-regexp)
  22057. (re-search-forward org-outline-regexp-bol end t))
  22058. (setq level (org-outline-level)))
  22059. (goto-char end)
  22060. (skip-chars-forward " \t\r\n\v\f")
  22061. (not (or (eobp)
  22062. (and (bolp) (looking-at-p org-outline-regexp)
  22063. (<= (org-outline-level) level))))))))
  22064. (define-key org-mode-map "\C-y" 'org-yank)
  22065. (defun org-truely-invisible-p ()
  22066. "Check if point is at a character currently not visible.
  22067. This version does not only check the character property, but also
  22068. `visible-mode'."
  22069. ;; Early versions of noutline don't have `outline-invisible-p'.
  22070. (unless (bound-and-true-p visible-mode)
  22071. (outline-invisible-p)))
  22072. (defun org-invisible-p2 ()
  22073. "Check if point is at a character currently not visible."
  22074. (save-excursion
  22075. (when (and (eolp) (not (bobp))) (backward-char 1))
  22076. ;; Early versions of noutline don't have `outline-invisible-p'.
  22077. (outline-invisible-p)))
  22078. (defun org-back-to-heading (&optional invisible-ok)
  22079. "Call `outline-back-to-heading', but provide a better error message."
  22080. (condition-case nil
  22081. (outline-back-to-heading invisible-ok)
  22082. (error (error "Before first headline at position %d in buffer %s"
  22083. (point) (current-buffer)))))
  22084. (defun org-before-first-heading-p ()
  22085. "Before first heading?"
  22086. (save-excursion
  22087. (end-of-line)
  22088. (null (re-search-backward org-outline-regexp-bol nil t))))
  22089. (defun org-at-heading-p (&optional ignored)
  22090. (outline-on-heading-p t))
  22091. (defun org-in-commented-heading-p (&optional no-inheritance)
  22092. "Non-nil if point is under a commented heading.
  22093. This function also checks ancestors of the current headline,
  22094. unless optional argument NO-INHERITANCE is non-nil."
  22095. (cond
  22096. ((org-before-first-heading-p) nil)
  22097. ((let ((headline (nth 4 (org-heading-components))))
  22098. (and headline
  22099. (let ((case-fold-search nil))
  22100. (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22101. headline)))))
  22102. (no-inheritance nil)
  22103. (t
  22104. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22105. (defun org-at-comment-p nil
  22106. "Is cursor in a commented line?"
  22107. (save-excursion
  22108. (save-match-data
  22109. (beginning-of-line)
  22110. (looking-at "^[ \t]*# "))))
  22111. (defun org-at-drawer-p nil
  22112. "Is cursor at a drawer keyword?"
  22113. (save-excursion
  22114. (move-beginning-of-line 1)
  22115. (looking-at org-drawer-regexp)))
  22116. (defun org-at-block-p nil
  22117. "Is cursor at a block keyword?"
  22118. (save-excursion
  22119. (move-beginning-of-line 1)
  22120. (looking-at org-block-regexp)))
  22121. (defun org-point-at-end-of-empty-headline ()
  22122. "If point is at the end of an empty headline, return t, else nil.
  22123. If the heading only contains a TODO keyword, it is still still considered
  22124. empty."
  22125. (and (looking-at "[ \t]*$")
  22126. (when org-todo-line-regexp
  22127. (save-excursion
  22128. (beginning-of-line 1)
  22129. (let ((case-fold-search nil))
  22130. (looking-at org-todo-line-regexp)
  22131. (string= (match-string 3) ""))))))
  22132. (defun org-at-heading-or-item-p ()
  22133. (or (org-at-heading-p) (org-at-item-p)))
  22134. (defun org-at-target-p ()
  22135. (or (org-in-regexp org-radio-target-regexp)
  22136. (org-in-regexp org-target-regexp)))
  22137. ;; Compatibility alias with Org versions < 7.8.03
  22138. (defalias 'org-on-target-p 'org-at-target-p)
  22139. (defun org-up-heading-all (arg)
  22140. "Move to the heading line of which the present line is a subheading.
  22141. This function considers both visible and invisible heading lines.
  22142. With argument, move up ARG levels."
  22143. (outline-up-heading arg t))
  22144. (defun org-up-heading-safe ()
  22145. "Move to the heading line of which the present line is a subheading.
  22146. This version will not throw an error. It will return the level of the
  22147. headline found, or nil if no higher level is found.
  22148. Also, this function will be a lot faster than `outline-up-heading',
  22149. because it relies on stars being the outline starters. This can really
  22150. make a significant difference in outlines with very many siblings."
  22151. (when (ignore-errors (org-back-to-heading t))
  22152. (let ((level-up (1- (funcall outline-level))))
  22153. (and (> level-up 0)
  22154. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22155. (funcall outline-level)))))
  22156. (defun org-first-sibling-p ()
  22157. "Is this heading the first child of its parents?"
  22158. (interactive)
  22159. (let ((re org-outline-regexp-bol)
  22160. level l)
  22161. (unless (org-at-heading-p t)
  22162. (user-error "Not at a heading"))
  22163. (setq level (funcall outline-level))
  22164. (save-excursion
  22165. (if (not (re-search-backward re nil t))
  22166. t
  22167. (setq l (funcall outline-level))
  22168. (< l level)))))
  22169. (defun org-goto-sibling (&optional previous)
  22170. "Goto the next sibling, even if it is invisible.
  22171. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22172. when a sibling was found. When none is found, return nil and don't
  22173. move point."
  22174. (let ((fun (if previous 're-search-backward 're-search-forward))
  22175. (pos (point))
  22176. (re org-outline-regexp-bol)
  22177. level l)
  22178. (when (ignore-errors (org-back-to-heading t))
  22179. (setq level (funcall outline-level))
  22180. (catch 'exit
  22181. (or previous (forward-char 1))
  22182. (while (funcall fun re nil t)
  22183. (setq l (funcall outline-level))
  22184. (when (< l level) (goto-char pos) (throw 'exit nil))
  22185. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22186. (goto-char pos)
  22187. nil))))
  22188. (defun org-show-siblings ()
  22189. "Show all siblings of the current headline."
  22190. (save-excursion
  22191. (while (org-goto-sibling) (org-flag-heading nil)))
  22192. (save-excursion
  22193. (while (org-goto-sibling 'previous)
  22194. (org-flag-heading nil))))
  22195. (defun org-goto-first-child ()
  22196. "Goto the first child, even if it is invisible.
  22197. Return t when a child was found. Otherwise don't move point and
  22198. return nil."
  22199. (let (level (pos (point)) (re org-outline-regexp-bol))
  22200. (when (ignore-errors (org-back-to-heading t))
  22201. (setq level (outline-level))
  22202. (forward-char 1)
  22203. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22204. (progn (goto-char (match-beginning 0)) t)
  22205. (goto-char pos) nil))))
  22206. (defun org-show-hidden-entry ()
  22207. "Show an entry where even the heading is hidden."
  22208. (save-excursion
  22209. (org-show-entry)))
  22210. (defun org-flag-heading (flag &optional entry)
  22211. "Flag the current heading. FLAG non-nil means make invisible.
  22212. When ENTRY is non-nil, show the entire entry."
  22213. (save-excursion
  22214. (org-back-to-heading t)
  22215. ;; Check if we should show the entire entry
  22216. (if entry
  22217. (progn
  22218. (org-show-entry)
  22219. (save-excursion
  22220. (and (outline-next-heading)
  22221. (org-flag-heading nil))))
  22222. (outline-flag-region (max (point-min) (1- (point)))
  22223. (save-excursion (outline-end-of-heading) (point))
  22224. flag))))
  22225. (defun org-get-next-sibling ()
  22226. "Move to next heading of the same level, and return point.
  22227. If there is no such heading, return nil.
  22228. This is like outline-next-sibling, but invisible headings are ok."
  22229. (let ((level (funcall outline-level)))
  22230. (outline-next-heading)
  22231. (while (and (not (eobp)) (> (funcall outline-level) level))
  22232. (outline-next-heading))
  22233. (unless (or (eobp) (< (funcall outline-level) level))
  22234. (point))))
  22235. (defun org-get-last-sibling ()
  22236. "Move to previous heading of the same level, and return point.
  22237. If there is no such heading, return nil."
  22238. (let ((opoint (point))
  22239. (level (funcall outline-level)))
  22240. (outline-previous-heading)
  22241. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22242. (while (and (> (funcall outline-level) level)
  22243. (not (bobp)))
  22244. (outline-previous-heading))
  22245. (unless (< (funcall outline-level) level)
  22246. (point)))))
  22247. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22248. "Goto to the end of a subtree."
  22249. ;; This contains an exact copy of the original function, but it uses
  22250. ;; `org-back-to-heading', to make it work also in invisible
  22251. ;; trees. And is uses an invisible-ok argument.
  22252. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22253. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22254. ;; with many children and grandchildren etc, this can be much faster
  22255. ;; than the outline version.
  22256. (org-back-to-heading invisible-ok)
  22257. (let ((first t)
  22258. (level (funcall outline-level)))
  22259. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22260. ;; A true heading (not a plain list item), in Org-mode
  22261. ;; This means we can easily find the end by looking
  22262. ;; only for the right number of stars. Using a regexp to do
  22263. ;; this is so much faster than using a Lisp loop.
  22264. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22265. (forward-char 1)
  22266. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22267. ;; something else, do it the slow way
  22268. (while (and (not (eobp))
  22269. (or first (> (funcall outline-level) level)))
  22270. (setq first nil)
  22271. (outline-next-heading)))
  22272. (unless to-heading
  22273. (when (memq (preceding-char) '(?\n ?\^M))
  22274. ;; Go to end of line before heading
  22275. (forward-char -1)
  22276. (when (memq (preceding-char) '(?\n ?\^M))
  22277. ;; leave blank line before heading
  22278. (forward-char -1)))))
  22279. (point))
  22280. (defun org-end-of-meta-data (&optional full)
  22281. "Skip planning line and properties drawer in current entry.
  22282. When optional argument FULL is non-nil, also skip empty lines,
  22283. clocking lines and regular drawers at the beginning of the
  22284. entry."
  22285. (org-back-to-heading t)
  22286. (forward-line)
  22287. (when (looking-at-p org-planning-line-re) (forward-line))
  22288. (when (looking-at org-property-drawer-re)
  22289. (goto-char (match-end 0))
  22290. (forward-line))
  22291. (when (and full (not (org-at-heading-p)))
  22292. (catch 'exit
  22293. (let ((end (save-excursion (outline-next-heading) (point)))
  22294. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22295. (while (not (eobp))
  22296. (cond ((looking-at-p org-drawer-regexp)
  22297. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22298. (forward-line)
  22299. (throw 'exit t)))
  22300. ((looking-at-p re) (forward-line))
  22301. (t (throw 'exit t))))))))
  22302. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22303. "Move forward to the ARG'th subheading at same level as this one.
  22304. Stop at the first and last subheadings of a superior heading.
  22305. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22306. non-nil it will also look at invisible ones."
  22307. (interactive "p")
  22308. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22309. (if (and arg (< arg 0))
  22310. (goto-char (point-min))
  22311. (outline-next-heading))
  22312. (org-at-heading-p)
  22313. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22314. (f (if (and arg (< arg 0))
  22315. 're-search-backward
  22316. 're-search-forward))
  22317. (count (if arg (abs arg) 1))
  22318. (result (point)))
  22319. (while (and (prog1 (> count 0)
  22320. (forward-char (if (and arg (< arg 0)) -1 1)))
  22321. (funcall f org-outline-regexp-bol nil 'move))
  22322. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22323. (cond ((< l level) (setq count 0))
  22324. ((and (= l level)
  22325. (or invisible-ok
  22326. (progn
  22327. (goto-char (line-beginning-position))
  22328. (not (outline-invisible-p)))))
  22329. (setq count (1- count))
  22330. (when (eq l level)
  22331. (setq result (point)))))))
  22332. (goto-char result))
  22333. (beginning-of-line 1)))
  22334. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22335. "Move backward to the ARG'th subheading at same level as this one.
  22336. Stop at the first and last subheadings of a superior heading."
  22337. (interactive "p")
  22338. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22339. (defun org-next-visible-heading (arg)
  22340. "Move to the next visible heading.
  22341. This function wraps `outline-next-visible-heading' with
  22342. `org-with-limited-levels' in order to skip over inline tasks and
  22343. respect customization of `org-odd-levels-only'."
  22344. (interactive "p")
  22345. (org-with-limited-levels
  22346. (outline-next-visible-heading arg)))
  22347. (defun org-previous-visible-heading (arg)
  22348. "Move to the previous visible heading.
  22349. This function wraps `outline-previous-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-previous-visible-heading arg)))
  22355. (defun org-next-block (arg &optional backward block-regexp)
  22356. "Jump to the next block.
  22357. With a prefix argument ARG, jump forward ARG many blocks.
  22358. When BACKWARD is non-nil, jump to the previous block.
  22359. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22360. Match data is set according to this regexp when the function
  22361. returns.
  22362. Return point at beginning of the opening line of found block.
  22363. Throw an error if no block is found."
  22364. (interactive "p")
  22365. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22366. (case-fold-search t)
  22367. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22368. (count (or arg 1))
  22369. (origin (point))
  22370. last-element)
  22371. (if backward (beginning-of-line) (end-of-line))
  22372. (while (and (> count 0) (funcall search-fn re nil t))
  22373. (let ((element (save-excursion
  22374. (goto-char (match-beginning 0))
  22375. (save-match-data (org-element-at-point)))))
  22376. (when (and (memq (org-element-type element)
  22377. '(center-block comment-block dynamic-block
  22378. example-block export-block quote-block
  22379. special-block src-block verse-block))
  22380. (<= (match-beginning 0)
  22381. (org-element-property :post-affiliated element)))
  22382. (setq last-element element)
  22383. (cl-decf count))))
  22384. (if (= count 0)
  22385. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22386. (save-match-data (org-show-context)))
  22387. (goto-char origin)
  22388. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22389. (defun org-previous-block (arg &optional block-regexp)
  22390. "Jump to the previous block.
  22391. With a prefix argument ARG, jump backward ARG many source blocks.
  22392. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22393. (interactive "p")
  22394. (org-next-block arg t block-regexp))
  22395. (defun org-forward-paragraph ()
  22396. "Move forward to beginning of next paragraph or equivalent.
  22397. The function moves point to the beginning of the next visible
  22398. structural element, which can be a paragraph, a table, a list
  22399. item, etc. It also provides some special moves for convenience:
  22400. - On an affiliated keyword, jump to the beginning of the
  22401. relative element.
  22402. - On an item or a footnote definition, move to the second
  22403. element inside, if any.
  22404. - On a table or a property drawer, jump after it.
  22405. - On a verse or source block, stop after blank lines."
  22406. (interactive)
  22407. (when (eobp) (user-error "Cannot move further down"))
  22408. (let* ((deactivate-mark nil)
  22409. (element (org-element-at-point))
  22410. (type (org-element-type element))
  22411. (post-affiliated (org-element-property :post-affiliated element))
  22412. (contents-begin (org-element-property :contents-begin element))
  22413. (contents-end (org-element-property :contents-end element))
  22414. (end (let ((end (org-element-property :end element)) (parent element))
  22415. (while (and (setq parent (org-element-property :parent parent))
  22416. (= (org-element-property :contents-end parent) end))
  22417. (setq end (org-element-property :end parent)))
  22418. end)))
  22419. (cond ((not element)
  22420. (skip-chars-forward " \r\t\n")
  22421. (or (eobp) (beginning-of-line)))
  22422. ;; On affiliated keywords, move to element's beginning.
  22423. ((< (point) post-affiliated)
  22424. (goto-char post-affiliated))
  22425. ;; At a table row, move to the end of the table. Similarly,
  22426. ;; at a node property, move to the end of the property
  22427. ;; drawer.
  22428. ((memq type '(node-property table-row))
  22429. (goto-char (org-element-property
  22430. :end (org-element-property :parent element))))
  22431. ((memq type '(property-drawer table)) (goto-char end))
  22432. ;; Consider blank lines as separators in verse and source
  22433. ;; blocks to ease editing.
  22434. ((memq type '(src-block verse-block))
  22435. (when (eq type 'src-block)
  22436. (setq contents-end
  22437. (save-excursion (goto-char end)
  22438. (skip-chars-backward " \r\t\n")
  22439. (line-beginning-position))))
  22440. (beginning-of-line)
  22441. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22442. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22443. (goto-char end)
  22444. (skip-chars-forward " \r\t\n")
  22445. (if (= (point) contents-end) (goto-char end)
  22446. (beginning-of-line))))
  22447. ;; With no contents, just skip element.
  22448. ((not contents-begin) (goto-char end))
  22449. ;; If contents are invisible, skip the element altogether.
  22450. ((outline-invisible-p (line-end-position))
  22451. (cl-case type
  22452. (headline
  22453. (org-with-limited-levels (outline-next-visible-heading 1)))
  22454. ;; At a plain list, make sure we move to the next item
  22455. ;; instead of skipping the whole list.
  22456. (plain-list (forward-char)
  22457. (org-forward-paragraph))
  22458. (otherwise (goto-char end))))
  22459. ((>= (point) contents-end) (goto-char end))
  22460. ((>= (point) contents-begin)
  22461. ;; This can only happen on paragraphs and plain lists.
  22462. (cl-case type
  22463. (paragraph (goto-char end))
  22464. ;; At a plain list, try to move to second element in
  22465. ;; first item, if possible.
  22466. (plain-list (end-of-line)
  22467. (org-forward-paragraph))))
  22468. ;; When contents start on the middle of a line (e.g. in
  22469. ;; items and footnote definitions), try to reach first
  22470. ;; element starting after current line.
  22471. ((> (line-end-position) contents-begin)
  22472. (end-of-line)
  22473. (org-forward-paragraph))
  22474. (t (goto-char contents-begin)))))
  22475. (defun org-backward-paragraph ()
  22476. "Move backward to start of previous paragraph or equivalent.
  22477. The function moves point to the beginning of the current
  22478. structural element, which can be a paragraph, a table, a list
  22479. item, etc., or to the beginning of the previous visible one if
  22480. point is already there. It also provides some special moves for
  22481. convenience:
  22482. - On an affiliated keyword, jump to the first one.
  22483. - On a table or a property drawer, move to its beginning.
  22484. - On a verse or source block, stop before blank lines."
  22485. (interactive)
  22486. (when (bobp) (user-error "Cannot move further up"))
  22487. (let* ((deactivate-mark nil)
  22488. (element (org-element-at-point))
  22489. (type (org-element-type element))
  22490. (contents-begin (org-element-property :contents-begin element))
  22491. (contents-end (org-element-property :contents-end element))
  22492. (post-affiliated (org-element-property :post-affiliated element))
  22493. (begin (org-element-property :begin element)))
  22494. (cond
  22495. ((not element) (goto-char (point-min)))
  22496. ((= (point) begin)
  22497. (backward-char)
  22498. (org-backward-paragraph))
  22499. ((<= (point) post-affiliated) (goto-char begin))
  22500. ((memq type '(node-property table-row))
  22501. (goto-char (org-element-property
  22502. :post-affiliated (org-element-property :parent element))))
  22503. ((memq type '(property-drawer table)) (goto-char begin))
  22504. ((memq type '(src-block verse-block))
  22505. (when (eq type 'src-block)
  22506. (setq contents-begin
  22507. (save-excursion (goto-char begin) (forward-line) (point))))
  22508. (if (= (point) contents-begin) (goto-char post-affiliated)
  22509. ;; Inside a verse block, see blank lines as paragraph
  22510. ;; separators.
  22511. (let ((origin (point)))
  22512. (skip-chars-backward " \r\t\n" contents-begin)
  22513. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22514. (skip-chars-forward " \r\t\n" origin)
  22515. (if (= (point) origin) (goto-char contents-begin)
  22516. (beginning-of-line))))))
  22517. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22518. ((eq type 'paragraph)
  22519. (goto-char contents-begin)
  22520. ;; When at first paragraph in an item or a footnote definition,
  22521. ;; move directly to beginning of line.
  22522. (let ((parent-contents
  22523. (org-element-property
  22524. :contents-begin (org-element-property :parent element))))
  22525. (when (and parent-contents (= parent-contents contents-begin))
  22526. (beginning-of-line))))
  22527. ;; At the end of a greater element, move to the beginning of the
  22528. ;; last element within.
  22529. ((>= (point) contents-end)
  22530. (goto-char (1- contents-end))
  22531. (org-backward-paragraph))
  22532. (t (goto-char (or post-affiliated begin))))
  22533. ;; Ensure we never leave point invisible.
  22534. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22535. (defun org-forward-element ()
  22536. "Move forward by one element.
  22537. Move to the next element at the same level, when possible."
  22538. (interactive)
  22539. (cond ((eobp) (user-error "Cannot move further down"))
  22540. ((org-with-limited-levels (org-at-heading-p))
  22541. (let ((origin (point)))
  22542. (goto-char (org-end-of-subtree nil t))
  22543. (unless (org-with-limited-levels (org-at-heading-p))
  22544. (goto-char origin)
  22545. (user-error "Cannot move further down"))))
  22546. (t
  22547. (let* ((elem (org-element-at-point))
  22548. (end (org-element-property :end elem))
  22549. (parent (org-element-property :parent elem)))
  22550. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22551. (goto-char (org-element-property :end parent)))
  22552. ((integer-or-marker-p end) (goto-char end))
  22553. (t (message "No element at point")))))))
  22554. (defun org-backward-element ()
  22555. "Move backward by one element.
  22556. Move to the previous element at the same level, when possible."
  22557. (interactive)
  22558. (cond ((bobp) (user-error "Cannot move further up"))
  22559. ((org-with-limited-levels (org-at-heading-p))
  22560. ;; At a headline, move to the previous one, if any, or stay
  22561. ;; here.
  22562. (let ((origin (point)))
  22563. (org-with-limited-levels (org-backward-heading-same-level 1))
  22564. ;; When current headline has no sibling above, move to its
  22565. ;; parent.
  22566. (when (= (point) origin)
  22567. (or (org-with-limited-levels (org-up-heading-safe))
  22568. (progn (goto-char origin)
  22569. (user-error "Cannot move further up"))))))
  22570. (t
  22571. (let* ((elem (org-element-at-point))
  22572. (beg (org-element-property :begin elem)))
  22573. (cond
  22574. ;; Move to beginning of current element if point isn't
  22575. ;; there already.
  22576. ((null beg) (message "No element at point"))
  22577. ((/= (point) beg) (goto-char beg))
  22578. (t (goto-char beg)
  22579. (skip-chars-backward " \r\t\n")
  22580. (unless (bobp)
  22581. (let ((prev (org-element-at-point)))
  22582. (goto-char (org-element-property :begin prev))
  22583. (while (and (setq prev (org-element-property :parent prev))
  22584. (<= (org-element-property :end prev) beg))
  22585. (goto-char (org-element-property :begin prev)))))))))))
  22586. (defun org-up-element ()
  22587. "Move to upper element."
  22588. (interactive)
  22589. (if (org-with-limited-levels (org-at-heading-p))
  22590. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22591. (let* ((elem (org-element-at-point))
  22592. (parent (org-element-property :parent elem)))
  22593. (if parent (goto-char (org-element-property :begin parent))
  22594. (if (org-with-limited-levels (org-before-first-heading-p))
  22595. (user-error "No surrounding element")
  22596. (org-with-limited-levels (org-back-to-heading)))))))
  22597. (defvar org-element-greater-elements)
  22598. (defun org-down-element ()
  22599. "Move to inner element."
  22600. (interactive)
  22601. (let ((element (org-element-at-point)))
  22602. (cond
  22603. ((memq (org-element-type element) '(plain-list table))
  22604. (goto-char (org-element-property :contents-begin element))
  22605. (forward-char))
  22606. ((memq (org-element-type element) org-element-greater-elements)
  22607. ;; If contents are hidden, first disclose them.
  22608. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22609. (goto-char (or (org-element-property :contents-begin element)
  22610. (user-error "No content for this element"))))
  22611. (t (user-error "No inner element")))))
  22612. (defun org-drag-element-backward ()
  22613. "Move backward element at point."
  22614. (interactive)
  22615. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22616. (let* ((elem (org-element-at-point))
  22617. (prev-elem
  22618. (save-excursion
  22619. (goto-char (org-element-property :begin elem))
  22620. (skip-chars-backward " \r\t\n")
  22621. (unless (bobp)
  22622. (let* ((beg (org-element-property :begin elem))
  22623. (prev (org-element-at-point))
  22624. (up prev))
  22625. (while (and (setq up (org-element-property :parent up))
  22626. (<= (org-element-property :end up) beg))
  22627. (setq prev up))
  22628. prev)))))
  22629. ;; Error out if no previous element or previous element is
  22630. ;; a parent of the current one.
  22631. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22632. (user-error "Cannot drag element backward")
  22633. (let ((pos (point)))
  22634. (org-element-swap-A-B prev-elem elem)
  22635. (goto-char (+ (org-element-property :begin prev-elem)
  22636. (- pos (org-element-property :begin elem)))))))))
  22637. (defun org-drag-element-forward ()
  22638. "Move forward element at point."
  22639. (interactive)
  22640. (let* ((pos (point))
  22641. (elem (org-element-at-point)))
  22642. (when (= (point-max) (org-element-property :end elem))
  22643. (user-error "Cannot drag element forward"))
  22644. (goto-char (org-element-property :end elem))
  22645. (let ((next-elem (org-element-at-point)))
  22646. (when (or (org-element-nested-p elem next-elem)
  22647. (and (eq (org-element-type next-elem) 'headline)
  22648. (not (eq (org-element-type elem) 'headline))))
  22649. (goto-char pos)
  22650. (user-error "Cannot drag element forward"))
  22651. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22652. ;; body's length (without final blanks) and by the length of
  22653. ;; blanks between ELEM and NEXT-ELEM.
  22654. (let ((size-next (- (save-excursion
  22655. (goto-char (org-element-property :end next-elem))
  22656. (skip-chars-backward " \r\t\n")
  22657. (forward-line)
  22658. ;; Small correction if buffer doesn't end
  22659. ;; with a newline character.
  22660. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22661. (org-element-property :begin next-elem)))
  22662. (size-blank (- (org-element-property :end elem)
  22663. (save-excursion
  22664. (goto-char (org-element-property :end elem))
  22665. (skip-chars-backward " \r\t\n")
  22666. (forward-line)
  22667. (point)))))
  22668. (org-element-swap-A-B elem next-elem)
  22669. (goto-char (+ pos size-next size-blank))))))
  22670. (defun org-drag-line-forward (arg)
  22671. "Drag the line at point ARG lines forward."
  22672. (interactive "p")
  22673. (dotimes (_ (abs arg))
  22674. (let ((c (current-column)))
  22675. (if (< 0 arg)
  22676. (progn
  22677. (beginning-of-line 2)
  22678. (transpose-lines 1)
  22679. (beginning-of-line 0))
  22680. (transpose-lines 1)
  22681. (beginning-of-line -1))
  22682. (org-move-to-column c))))
  22683. (defun org-drag-line-backward (arg)
  22684. "Drag the line at point ARG lines backward."
  22685. (interactive "p")
  22686. (org-drag-line-forward (- arg)))
  22687. (defun org-mark-element ()
  22688. "Put point at beginning of this element, mark at end.
  22689. Interactively, if this command is repeated or (in Transient Mark
  22690. mode) if the mark is active, it marks the next element after the
  22691. ones already marked."
  22692. (interactive)
  22693. (let (deactivate-mark)
  22694. (if (and (called-interactively-p 'any)
  22695. (or (and (eq last-command this-command) (mark t))
  22696. (and transient-mark-mode mark-active)))
  22697. (set-mark
  22698. (save-excursion
  22699. (goto-char (mark))
  22700. (goto-char (org-element-property :end (org-element-at-point)))))
  22701. (let ((element (org-element-at-point)))
  22702. (end-of-line)
  22703. (push-mark (org-element-property :end element) t t)
  22704. (goto-char (org-element-property :begin element))))))
  22705. (defun org-narrow-to-element ()
  22706. "Narrow buffer to current element."
  22707. (interactive)
  22708. (let ((elem (org-element-at-point)))
  22709. (cond
  22710. ((eq (car elem) 'headline)
  22711. (narrow-to-region
  22712. (org-element-property :begin elem)
  22713. (org-element-property :end elem)))
  22714. ((memq (car elem) org-element-greater-elements)
  22715. (narrow-to-region
  22716. (org-element-property :contents-begin elem)
  22717. (org-element-property :contents-end elem)))
  22718. (t
  22719. (narrow-to-region
  22720. (org-element-property :begin elem)
  22721. (org-element-property :end elem))))))
  22722. (defun org-transpose-element ()
  22723. "Transpose current and previous elements, keeping blank lines between.
  22724. Point is moved after both elements."
  22725. (interactive)
  22726. (org-skip-whitespace)
  22727. (let ((end (org-element-property :end (org-element-at-point))))
  22728. (org-drag-element-backward)
  22729. (goto-char end)))
  22730. (defun org-unindent-buffer ()
  22731. "Un-indent the visible part of the buffer.
  22732. Relative indentation (between items, inside blocks, etc.) isn't
  22733. modified."
  22734. (interactive)
  22735. (unless (eq major-mode 'org-mode)
  22736. (user-error "Cannot un-indent a buffer not in Org mode"))
  22737. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22738. (unindent-tree
  22739. (lambda (contents)
  22740. (dolist (element (reverse contents))
  22741. (if (memq (org-element-type element) '(headline section))
  22742. (funcall unindent-tree (org-element-contents element))
  22743. (save-excursion
  22744. (save-restriction
  22745. (narrow-to-region
  22746. (org-element-property :begin element)
  22747. (org-element-property :end element))
  22748. (org-do-remove-indentation))))))))
  22749. (funcall unindent-tree (org-element-contents parse-tree))))
  22750. (defun org-show-children (&optional level)
  22751. "Show all direct subheadings of this heading.
  22752. Prefix arg LEVEL is how many levels below the current level
  22753. should be shown. Default is enough to cause the following
  22754. heading to appear."
  22755. (interactive "p")
  22756. ;; If `orgstruct-mode' is active, use the slower version.
  22757. (if orgstruct-mode (call-interactively #'outline-show-children)
  22758. (save-excursion
  22759. (org-back-to-heading t)
  22760. (let* ((current-level (funcall outline-level))
  22761. (max-level (org-get-valid-level
  22762. current-level
  22763. (if level (prefix-numeric-value level) 1)))
  22764. (end (save-excursion (org-end-of-subtree t t)))
  22765. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22766. (past-first-child nil)
  22767. ;; Make sure to skip inlinetasks.
  22768. (re (format regexp-fmt
  22769. current-level
  22770. (cond
  22771. ((not (featurep 'org-inlinetask)) "")
  22772. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22773. 3))
  22774. (t (1- org-inlinetask-min-level))))))
  22775. ;; Display parent heading.
  22776. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22777. (forward-line)
  22778. ;; Display children. First child may be deeper than expected
  22779. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22780. ;; MAX-LEVEL accordingly.
  22781. (while (re-search-forward re end t)
  22782. (unless past-first-child
  22783. (setq re (format regexp-fmt
  22784. current-level
  22785. (max (funcall outline-level) max-level)))
  22786. (setq past-first-child t))
  22787. (outline-flag-region
  22788. (line-end-position 0) (line-end-position) nil))))))
  22789. (defun org-show-subtree ()
  22790. "Show everything after this heading at deeper levels."
  22791. (interactive)
  22792. (outline-flag-region
  22793. (point)
  22794. (save-excursion
  22795. (org-end-of-subtree t t))
  22796. nil))
  22797. (defun org-show-entry ()
  22798. "Show the body directly following this heading.
  22799. Show the heading too, if it is currently invisible."
  22800. (interactive)
  22801. (save-excursion
  22802. (ignore-errors
  22803. (org-back-to-heading t)
  22804. (outline-flag-region
  22805. (max (point-min) (1- (point)))
  22806. (save-excursion
  22807. (if (re-search-forward
  22808. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22809. (match-beginning 1)
  22810. (point-max)))
  22811. nil)
  22812. (org-cycle-hide-drawers 'children))))
  22813. (defun org-make-options-regexp (kwds &optional extra)
  22814. "Make a regular expression for keyword lines.
  22815. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22816. when non-nil, is a regexp matching keywords names."
  22817. (concat "^[ \t]*#\\+\\("
  22818. (regexp-opt kwds)
  22819. (and extra (concat (and kwds "\\|") extra))
  22820. "\\):[ \t]*\\(.*\\)"))
  22821. ;;;; Integration with and fixes for other packages
  22822. ;;; Imenu support
  22823. (defvar-local org-imenu-markers nil
  22824. "All markers currently used by Imenu.")
  22825. (defun org-imenu-new-marker (&optional pos)
  22826. "Return a new marker for use by Imenu, and remember the marker."
  22827. (let ((m (make-marker)))
  22828. (move-marker m (or pos (point)))
  22829. (push m org-imenu-markers)
  22830. m))
  22831. (defun org-imenu-get-tree ()
  22832. "Produce the index for Imenu."
  22833. (dolist (x org-imenu-markers) (move-marker x nil))
  22834. (setq org-imenu-markers nil)
  22835. (let* ((case-fold-search nil)
  22836. (n org-imenu-depth)
  22837. (re (concat "^" (org-get-limited-outline-regexp)))
  22838. (subs (make-vector (1+ n) nil))
  22839. (last-level 0)
  22840. m level head0 head)
  22841. (save-excursion
  22842. (save-restriction
  22843. (widen)
  22844. (goto-char (point-max))
  22845. (while (re-search-backward re nil t)
  22846. (setq level (org-reduced-level (funcall outline-level)))
  22847. (when (and (<= level n)
  22848. (looking-at org-complex-heading-regexp)
  22849. (setq head0 (match-string-no-properties 4)))
  22850. (setq head (org-link-display-format head0)
  22851. m (org-imenu-new-marker))
  22852. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22853. (if (>= level last-level)
  22854. (push (cons head m) (aref subs level))
  22855. (push (cons head (aref subs (1+ level))) (aref subs level))
  22856. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22857. (setq last-level level)))))
  22858. (aref subs 1)))
  22859. (eval-after-load "imenu"
  22860. '(progn
  22861. (add-hook 'imenu-after-jump-hook
  22862. (lambda ()
  22863. (when (derived-mode-p 'org-mode)
  22864. (org-show-context 'org-goto))))))
  22865. (defun org-link-display-format (s)
  22866. "Replace links in string S with their description.
  22867. If there is no description, use the link target."
  22868. (save-match-data
  22869. (replace-regexp-in-string
  22870. org-bracket-link-analytic-regexp
  22871. (lambda (m)
  22872. (if (match-end 5) (match-string 5 m)
  22873. (concat (match-string 1 m) (match-string 3 m))))
  22874. s nil t)))
  22875. (defun org-toggle-link-display ()
  22876. "Toggle the literal or descriptive display of links."
  22877. (interactive)
  22878. (if org-descriptive-links
  22879. (progn (org-remove-from-invisibility-spec '(org-link))
  22880. (org-restart-font-lock)
  22881. (setq org-descriptive-links nil))
  22882. (progn (add-to-invisibility-spec '(org-link))
  22883. (org-restart-font-lock)
  22884. (setq org-descriptive-links t))))
  22885. ;; Speedbar support
  22886. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22887. "Overlay marking the agenda restriction line in speedbar.")
  22888. (overlay-put org-speedbar-restriction-lock-overlay
  22889. 'face 'org-agenda-restriction-lock)
  22890. (overlay-put org-speedbar-restriction-lock-overlay
  22891. 'help-echo "Agendas are currently limited to this item.")
  22892. (delete-overlay org-speedbar-restriction-lock-overlay)
  22893. (defun org-speedbar-set-agenda-restriction ()
  22894. "Restrict future agenda commands to the location at point in speedbar.
  22895. To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
  22896. (interactive)
  22897. (require 'org-agenda)
  22898. (let (p m tp np dir txt)
  22899. (cond
  22900. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22901. 'org-imenu t))
  22902. (setq m (get-text-property p 'org-imenu-marker))
  22903. (with-current-buffer (marker-buffer m)
  22904. (goto-char m)
  22905. (org-agenda-set-restriction-lock 'subtree)))
  22906. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22907. 'speedbar-function 'speedbar-find-file))
  22908. (setq tp (previous-single-property-change
  22909. (1+ p) 'speedbar-function)
  22910. np (next-single-property-change
  22911. tp 'speedbar-function)
  22912. dir (speedbar-line-directory)
  22913. txt (buffer-substring-no-properties (or tp (point-min))
  22914. (or np (point-max))))
  22915. (with-current-buffer (find-file-noselect
  22916. (let ((default-directory dir))
  22917. (expand-file-name txt)))
  22918. (unless (derived-mode-p 'org-mode)
  22919. (user-error "Cannot restrict to non-Org-mode file"))
  22920. (org-agenda-set-restriction-lock 'file)))
  22921. (t (user-error "Don't know how to restrict Org-mode's agenda")))
  22922. (move-overlay org-speedbar-restriction-lock-overlay
  22923. (point-at-bol) (point-at-eol))
  22924. (setq current-prefix-arg nil)
  22925. (org-agenda-maybe-redo)))
  22926. (defvar speedbar-file-key-map)
  22927. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22928. (eval-after-load "speedbar"
  22929. '(progn
  22930. (speedbar-add-supported-extension ".org")
  22931. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22932. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22933. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22934. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22935. (add-hook 'speedbar-visiting-tag-hook
  22936. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22937. ;;; Fixes and Hacks for problems with other packages
  22938. (defun org--flyspell-object-check-p (element)
  22939. "Non-nil when Flyspell can check object at point.
  22940. ELEMENT is the element at point."
  22941. (let ((object (save-excursion
  22942. (when (looking-at-p "\\>") (backward-char))
  22943. (org-element-context element))))
  22944. (cl-case (org-element-type object)
  22945. ;; Prevent checks in links due to keybinding conflict with
  22946. ;; Flyspell.
  22947. ((code entity export-snippet inline-babel-call
  22948. inline-src-block line-break latex-fragment link macro
  22949. statistics-cookie target timestamp verbatim)
  22950. nil)
  22951. (footnote-reference
  22952. ;; Only in inline footnotes, within the definition.
  22953. (and (eq (org-element-property :type object) 'inline)
  22954. (< (save-excursion
  22955. (goto-char (org-element-property :begin object))
  22956. (search-forward ":" nil t 2))
  22957. (point))))
  22958. (otherwise t))))
  22959. (defun org-mode-flyspell-verify ()
  22960. "Function used for `flyspell-generic-check-word-predicate'."
  22961. (if (org-at-heading-p)
  22962. ;; At a headline or an inlinetask, check title only. This is
  22963. ;; faster than relying on `org-element-at-point'.
  22964. (and (save-excursion (beginning-of-line)
  22965. (and (let ((case-fold-search t))
  22966. (not (looking-at "\\*+ END[ \t]*$")))
  22967. (looking-at org-complex-heading-regexp)))
  22968. (match-beginning 4)
  22969. (>= (point) (match-beginning 4))
  22970. (or (not (match-beginning 5))
  22971. (< (point) (match-beginning 5))))
  22972. (let* ((element (org-element-at-point))
  22973. (post-affiliated (org-element-property :post-affiliated element)))
  22974. (cond
  22975. ;; Ignore checks in all affiliated keywords but captions.
  22976. ((< (point) post-affiliated)
  22977. (and (save-excursion
  22978. (beginning-of-line)
  22979. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22980. (> (point) (match-end 0))
  22981. (org--flyspell-object-check-p element)))
  22982. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22983. ((let ((log (org-log-into-drawer)))
  22984. (and log
  22985. (let ((drawer (org-element-lineage element '(drawer))))
  22986. (and drawer
  22987. (eq (compare-strings
  22988. log nil nil
  22989. (org-element-property :drawer-name drawer) nil nil t)
  22990. t)))))
  22991. nil)
  22992. (t
  22993. (cl-case (org-element-type element)
  22994. ((comment quote-section) t)
  22995. (comment-block
  22996. ;; Allow checks between block markers, not on them.
  22997. (and (> (line-beginning-position) post-affiliated)
  22998. (save-excursion
  22999. (end-of-line)
  23000. (skip-chars-forward " \r\t\n")
  23001. (< (point) (org-element-property :end element)))))
  23002. ;; Arbitrary list of keywords where checks are meaningful.
  23003. ;; Make sure point is on the value part of the element.
  23004. (keyword
  23005. (and (member (org-element-property :key element)
  23006. '("DESCRIPTION" "TITLE"))
  23007. (save-excursion
  23008. (search-backward ":" (line-beginning-position) t))))
  23009. ;; Check is globally allowed in paragraphs verse blocks and
  23010. ;; table rows (after affiliated keywords) but some objects
  23011. ;; must not be affected.
  23012. ((paragraph table-row verse-block)
  23013. (let ((cbeg (org-element-property :contents-begin element))
  23014. (cend (org-element-property :contents-end element)))
  23015. (and cbeg (>= (point) cbeg) (< (point) cend)
  23016. (org--flyspell-object-check-p element))))))))))
  23017. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  23018. (defun org-remove-flyspell-overlays-in (beg end)
  23019. "Remove flyspell overlays in region."
  23020. (and (bound-and-true-p flyspell-mode)
  23021. (fboundp 'flyspell-delete-region-overlays)
  23022. (flyspell-delete-region-overlays beg end)))
  23023. (defvar flyspell-delayed-commands)
  23024. (eval-after-load "flyspell"
  23025. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23026. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23027. (eval-after-load "bookmark"
  23028. '(if (boundp 'bookmark-after-jump-hook)
  23029. ;; We can use the hook
  23030. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23031. ;; Hook not available, use advice
  23032. (defadvice bookmark-jump (after org-make-visible activate)
  23033. "Make the position visible."
  23034. (org-bookmark-jump-unhide))))
  23035. ;; Make sure saveplace shows the location if it was hidden
  23036. (eval-after-load "saveplace"
  23037. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23038. "Make the position visible."
  23039. (org-bookmark-jump-unhide)))
  23040. ;; Make sure ecb shows the location if it was hidden
  23041. (eval-after-load "ecb"
  23042. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23043. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23044. (when (derived-mode-p 'org-mode)
  23045. (org-show-context))))
  23046. (defun org-bookmark-jump-unhide ()
  23047. "Unhide the current position, to show the bookmark location."
  23048. (and (derived-mode-p 'org-mode)
  23049. (or (outline-invisible-p)
  23050. (save-excursion (goto-char (max (point-min) (1- (point))))
  23051. (outline-invisible-p)))
  23052. (org-show-context 'bookmark-jump)))
  23053. (defun org-mark-jump-unhide ()
  23054. "Make the point visible with `org-show-context' after jumping to the mark."
  23055. (when (and (derived-mode-p 'org-mode)
  23056. (outline-invisible-p))
  23057. (org-show-context 'mark-goto)))
  23058. (eval-after-load "simple"
  23059. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23060. "Make the point visible with `org-show-context'."
  23061. (org-mark-jump-unhide)))
  23062. (eval-after-load "simple"
  23063. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23064. "Make the point visible with `org-show-context'."
  23065. (org-mark-jump-unhide)))
  23066. (eval-after-load "simple"
  23067. '(defadvice pop-global-mark (after org-make-visible activate)
  23068. "Make the point visible with `org-show-context'."
  23069. (org-mark-jump-unhide)))
  23070. ;; Make session.el ignore our circular variable
  23071. (defvar session-globals-exclude)
  23072. (eval-after-load "session"
  23073. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23074. ;;;; Finish up
  23075. (provide 'org)
  23076. (run-hooks 'org-load-hook)
  23077. ;;; org.el ends here