org.el 951 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173
  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 is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (equal this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda"
  105. (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  108. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  109. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  110. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  111. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  112. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  113. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  114. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  115. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  116. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  117. (declare-function org-clock-update-time-maybe "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  128. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  129. (declare-function org-element-property "org-element" (property element))
  130. (declare-function org-element-put-property "org-element" (element property value))
  131. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  132. (declare-function org-element-type "org-element" (element))
  133. (declare-function org-element-update-syntax "org-element" ())
  134. (declare-function org-id-find-id-file "org-id" (id))
  135. (declare-function org-id-get-create "org-id" (&optional force))
  136. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  137. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  138. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  139. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  140. (declare-function org-table-align "org-table" ())
  141. (declare-function org-table-begin "org-table" (&optional table-type))
  142. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  143. (declare-function org-table-blank-field "org-table" ())
  144. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  145. (declare-function org-table-edit-field "org-table" (arg))
  146. (declare-function org-table-end "org-table" (&optional table-type))
  147. (declare-function org-table-end-of-field "org-table" (&optional n))
  148. (declare-function org-table-insert-row "org-table" (&optional arg))
  149. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  150. (declare-function org-table-maybe-eval-formula "org-table" ())
  151. (declare-function org-table-maybe-recalculate-line "org-table" ())
  152. (declare-function org-table-next-row "org-table" ())
  153. (declare-function org-table-paste-rectangle "org-table" ())
  154. (declare-function org-table-wrap-region "org-table" (arg))
  155. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  156. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  157. (declare-function orgtbl-mode "org-table" (&optional arg))
  158. (defsubst org-uniquify (list)
  159. "Non-destructively remove duplicate elements from LIST."
  160. (let ((res (copy-sequence list))) (delete-dups res)))
  161. (defsubst org-get-at-bol (property)
  162. "Get text property PROPERTY at the beginning of line."
  163. (get-text-property (point-at-bol) property))
  164. (defsubst org-trim (s &optional keep-lead)
  165. "Remove whitespace at the beginning and the end of string S.
  166. When optional argument KEEP-LEAD is non-nil, removing blank lines
  167. at the beginning of the string does not affect leading indentation."
  168. (replace-regexp-in-string
  169. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  170. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  171. ;; load languages based on value of `org-babel-load-languages'
  172. (defvar org-babel-load-languages)
  173. ;;;###autoload
  174. (defun org-babel-do-load-languages (sym value)
  175. "Load the languages defined in `org-babel-load-languages'."
  176. (set-default sym value)
  177. (dolist (pair org-babel-load-languages)
  178. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  179. (if active
  180. (require (intern (concat "ob-" lang)))
  181. (funcall 'fmakunbound
  182. (intern (concat "org-babel-execute:" lang)))
  183. (funcall 'fmakunbound
  184. (intern (concat "org-babel-expand-body:" lang)))))))
  185. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  186. ;;;###autoload
  187. (defun org-babel-load-file (file &optional compile)
  188. "Load Emacs Lisp source code blocks in the Org FILE.
  189. This function exports the source code using `org-babel-tangle'
  190. and then loads the resulting file using `load-file'. With prefix
  191. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  192. file to byte-code before it is loaded."
  193. (interactive "fFile to load: \nP")
  194. (let* ((age (lambda (file)
  195. (float-time
  196. (time-subtract (current-time)
  197. (nth 5 (or (file-attributes (file-truename file))
  198. (file-attributes file)))))))
  199. (base-name (file-name-sans-extension file))
  200. (exported-file (concat base-name ".el")))
  201. ;; tangle if the Org file is newer than the elisp file
  202. (unless (and (file-exists-p exported-file)
  203. (> (funcall age file) (funcall age exported-file)))
  204. ;; Tangle-file traversal returns reversed list of tangled files
  205. ;; and we want to evaluate the first target.
  206. (setq exported-file
  207. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  208. (message "%s %s"
  209. (if compile
  210. (progn (byte-compile-file exported-file 'load)
  211. "Compiled and loaded")
  212. (progn (load-file exported-file) "Loaded"))
  213. exported-file)))
  214. (defcustom org-babel-load-languages '((emacs-lisp . t))
  215. "Languages which can be evaluated in Org buffers.
  216. This list can be used to load support for any of the languages
  217. below, note that each language will depend on a different set of
  218. system executables and/or Emacs modes. When a language is
  219. \"loaded\", then code blocks in that language can be evaluated
  220. with `org-babel-execute-src-block' bound by default to C-c
  221. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  222. be set to remove code block evaluation from the C-c C-c
  223. keybinding. By default only Emacs Lisp (which has no
  224. requirements) is loaded."
  225. :group 'org-babel
  226. :set 'org-babel-do-load-languages
  227. :version "24.1"
  228. :type '(alist :tag "Babel Languages"
  229. :key-type
  230. (choice
  231. (const :tag "Awk" awk)
  232. (const :tag "C" C)
  233. (const :tag "R" R)
  234. (const :tag "Asymptote" asymptote)
  235. (const :tag "Calc" calc)
  236. (const :tag "Clojure" clojure)
  237. (const :tag "CSS" css)
  238. (const :tag "Ditaa" ditaa)
  239. (const :tag "Dot" dot)
  240. (const :tag "Emacs Lisp" emacs-lisp)
  241. (const :tag "Forth" forth)
  242. (const :tag "Fortran" fortran)
  243. (const :tag "Gnuplot" gnuplot)
  244. (const :tag "Haskell" haskell)
  245. (const :tag "IO" io)
  246. (const :tag "J" J)
  247. (const :tag "Java" java)
  248. (const :tag "Javascript" js)
  249. (const :tag "LaTeX" latex)
  250. (const :tag "Ledger" ledger)
  251. (const :tag "Lilypond" lilypond)
  252. (const :tag "Lisp" lisp)
  253. (const :tag "Makefile" makefile)
  254. (const :tag "Maxima" maxima)
  255. (const :tag "Matlab" matlab)
  256. (const :tag "Mscgen" mscgen)
  257. (const :tag "Ocaml" ocaml)
  258. (const :tag "Octave" octave)
  259. (const :tag "Org" org)
  260. (const :tag "Perl" perl)
  261. (const :tag "Pico Lisp" picolisp)
  262. (const :tag "PlantUML" plantuml)
  263. (const :tag "Python" python)
  264. (const :tag "Ruby" ruby)
  265. (const :tag "Sass" sass)
  266. (const :tag "Scala" scala)
  267. (const :tag "Scheme" scheme)
  268. (const :tag "Screen" screen)
  269. (const :tag "Shell Script" shell)
  270. (const :tag "Shen" shen)
  271. (const :tag "Sql" sql)
  272. (const :tag "Sqlite" sqlite)
  273. (const :tag "Stan" stan)
  274. (const :tag "ebnf2ps" ebnf2ps))
  275. :value-type (boolean :tag "Activate" :value t)))
  276. ;;;; Customization variables
  277. (defcustom org-clone-delete-id nil
  278. "Remove ID property of clones of a subtree.
  279. When non-nil, clones of a subtree don't inherit the ID property.
  280. Otherwise they inherit the ID property with a new unique
  281. identifier."
  282. :type 'boolean
  283. :version "24.1"
  284. :group 'org-id)
  285. ;;; Version
  286. (org-check-version)
  287. ;;;###autoload
  288. (defun org-version (&optional here full message)
  289. "Show the Org version.
  290. Interactively, or when MESSAGE is non-nil, show it in echo area.
  291. With prefix argument, or when HERE is non-nil, insert it at point.
  292. In non-interactive uses, a reduced version string is output unless
  293. FULL is given."
  294. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  295. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  296. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  297. (load-suffixes (list ".el"))
  298. (org-install-dir
  299. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  300. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  301. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  302. (let* ((load-suffixes save-load-suffixes)
  303. (release (org-release))
  304. (git-version (org-git-version))
  305. (version (format "Org-mode version %s (%s @ %s)"
  306. release
  307. git-version
  308. (if org-install-dir
  309. (if (string= org-dir org-install-dir)
  310. org-install-dir
  311. (concat "mixed installation! "
  312. org-install-dir
  313. " and "
  314. org-dir))
  315. "org-loaddefs.el can not be found!")))
  316. (version1 (if full version release)))
  317. (when here (insert version1))
  318. (when message (message "%s" version1))
  319. version1)))
  320. (defconst org-version (org-version))
  321. ;;; Syntax Constants
  322. ;;;; Block
  323. (defconst org-block-regexp
  324. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  325. "Regular expression for hiding blocks.")
  326. (defconst org-dblock-start-re
  327. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  328. "Matches the start line of a dynamic block, with parameters.")
  329. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  330. "Matches the end of a dynamic block.")
  331. ;;;; Clock and Planning
  332. (defconst org-clock-string "CLOCK:"
  333. "String used as prefix for timestamps clocking work hours on an item.")
  334. (defvar org-closed-string "CLOSED:"
  335. "String used as the prefix for timestamps logging closing a TODO entry.")
  336. (defvar org-deadline-string "DEADLINE:"
  337. "String to mark deadline entries.
  338. A deadline is this string, followed by a time stamp. Should be a word,
  339. terminated by a colon. You can insert a schedule keyword and
  340. a timestamp with \\[org-deadline].")
  341. (defvar org-scheduled-string "SCHEDULED:"
  342. "String to mark scheduled TODO entries.
  343. A schedule is this string, followed by a time stamp. Should be a word,
  344. terminated by a colon. You can insert a schedule keyword and
  345. a timestamp with \\[org-schedule].")
  346. (defconst org-ds-keyword-length
  347. (+ 2
  348. (apply #'max
  349. (mapcar #'length
  350. (list org-deadline-string org-scheduled-string
  351. org-clock-string org-closed-string))))
  352. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  353. (defconst org-planning-line-re
  354. (concat "^[ \t]*"
  355. (regexp-opt
  356. (list org-closed-string org-deadline-string org-scheduled-string)
  357. t))
  358. "Matches a line with planning info.
  359. Matched keyword is in group 1.")
  360. (defconst org-clock-line-re
  361. (concat "^[ \t]*" org-clock-string)
  362. "Matches a line with clock info.")
  363. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  364. "Matches the DEADLINE keyword.")
  365. (defconst org-deadline-time-regexp
  366. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  367. "Matches the DEADLINE keyword together with a time stamp.")
  368. (defconst org-deadline-time-hour-regexp
  369. (concat "\\<" org-deadline-string
  370. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  371. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  372. (defconst org-deadline-line-regexp
  373. (concat "\\<\\(" org-deadline-string "\\).*")
  374. "Matches the DEADLINE keyword and the rest of the line.")
  375. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  376. "Matches the SCHEDULED keyword.")
  377. (defconst org-scheduled-time-regexp
  378. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  379. "Matches the SCHEDULED keyword together with a time stamp.")
  380. (defconst org-scheduled-time-hour-regexp
  381. (concat "\\<" org-scheduled-string
  382. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  383. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  384. (defconst org-closed-time-regexp
  385. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  386. "Matches the CLOSED keyword together with a time stamp.")
  387. (defconst org-keyword-time-regexp
  388. (concat "\\<"
  389. (regexp-opt
  390. (list org-scheduled-string org-deadline-string org-closed-string
  391. org-clock-string)
  392. t)
  393. " *[[<]\\([^]>]+\\)[]>]")
  394. "Matches any of the 4 keywords, together with the time stamp.")
  395. (defconst org-keyword-time-not-clock-regexp
  396. (concat
  397. "\\<"
  398. (regexp-opt
  399. (list org-scheduled-string org-deadline-string org-closed-string) t)
  400. " *[[<]\\([^]>]+\\)[]>]")
  401. "Matches any of the 3 keywords, together with the time stamp.")
  402. (defconst org-maybe-keyword-time-regexp
  403. (concat "\\(\\<"
  404. (regexp-opt
  405. (list org-scheduled-string org-deadline-string org-closed-string
  406. org-clock-string)
  407. t)
  408. "\\)?"
  409. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  410. "\\|"
  411. "<%%([^\r\n>]*>\\)")
  412. "Matches a timestamp, possibly preceded by a keyword.")
  413. (defconst org-all-time-keywords
  414. (mapcar (lambda (w) (substring w 0 -1))
  415. (list org-scheduled-string org-deadline-string
  416. org-clock-string org-closed-string))
  417. "List of time keywords.")
  418. ;;;; Drawer
  419. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  420. "Matches first or last line of a hidden block.
  421. Group 1 contains drawer's name or \"END\".")
  422. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  423. "Regular expression matching the first line of a property drawer.")
  424. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  425. "Regular expression matching the last line of a property drawer.")
  426. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  427. "Regular expression matching the first line of a clock drawer.")
  428. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  429. "Regular expression matching the last line of a clock drawer.")
  430. (defconst org-property-drawer-re
  431. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  432. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  433. "[ \t]*:END:[ \t]*$")
  434. "Matches an entire property drawer.")
  435. (defconst org-clock-drawer-re
  436. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  437. org-clock-drawer-end-re "\\)\n?")
  438. "Matches an entire clock drawer.")
  439. ;;;; Headline
  440. (defconst org-heading-keyword-regexp-format
  441. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  442. "Printf format for a regexp matching a headline with some keyword.
  443. This regexp will match the headline of any node which has the
  444. exact keyword that is put into the format. The keyword isn't in
  445. any group by default, but the stars and the body are.")
  446. (defconst org-heading-keyword-maybe-regexp-format
  447. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  448. "Printf format for a regexp matching a headline, possibly with some keyword.
  449. This regexp can match any headline with the specified keyword, or
  450. without a keyword. The keyword isn't in any group by default,
  451. but the stars and the body are.")
  452. (defconst org-archive-tag "ARCHIVE"
  453. "The tag that marks a subtree as archived.
  454. An archived subtree does not open during visibility cycling, and does
  455. not contribute to the agenda listings.")
  456. (defconst org-comment-string "COMMENT"
  457. "Entries starting with this keyword will never be exported.
  458. An entry can be toggled between COMMENT and normal with
  459. \\[org-toggle-comment].")
  460. ;;;; LaTeX Environments and Fragments
  461. (defconst org-latex-regexps
  462. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  463. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  464. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  465. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  466. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  467. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  468. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  469. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  470. "Regular expressions for matching embedded LaTeX.")
  471. ;;;; Node Property
  472. (defconst org-effort-property "Effort"
  473. "The property that is being used to keep track of effort estimates.
  474. Effort estimates given in this property need to have the format H:MM.")
  475. ;;;; Table
  476. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  477. "Detect an org-type or table-type table.")
  478. (defconst org-table-line-regexp "^[ \t]*|"
  479. "Detect an org-type table line.")
  480. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  481. "Detect an org-type table line.")
  482. (defconst org-table-hline-regexp "^[ \t]*|-"
  483. "Detect an org-type table hline.")
  484. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  485. "Detect a table-type table hline.")
  486. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  487. "Detect the first line outside a table when searching from within it.
  488. This works for both table types.")
  489. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  490. "Detect a #+TBLFM line.")
  491. ;;;; Timestamp
  492. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  493. "Regular expression for fast time stamp matching.")
  494. (defconst org-ts-regexp-inactive
  495. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  496. "Regular expression for fast inactive time stamp matching.")
  497. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  498. "Regular expression for fast time stamp matching.")
  499. (defconst org-ts-regexp0
  500. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  501. "Regular expression matching time strings for analysis.
  502. This one does not require the space after the date, so it can be used
  503. on a string that terminates immediately after the date.")
  504. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  505. "Regular expression matching time strings for analysis.")
  506. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  507. "Regular expression matching time stamps, with groups.")
  508. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  509. "Regular expression matching time stamps (also [..]), with groups.")
  510. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  511. "Regular expression matching a time stamp range.")
  512. (defconst org-tr-regexp-both
  513. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  514. "Regular expression matching a time stamp range.")
  515. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  516. org-ts-regexp "\\)?")
  517. "Regular expression matching a time stamp or time stamp range.")
  518. (defconst org-tsr-regexp-both
  519. (concat org-ts-regexp-both "\\(--?-?"
  520. org-ts-regexp-both "\\)?")
  521. "Regular expression matching a time stamp or time stamp range.
  522. The time stamps may be either active or inactive.")
  523. (defconst org-repeat-re
  524. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  525. "Regular expression for specifying repeated events.
  526. After a match, group 1 contains the repeat expression.")
  527. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  528. "Formats for `format-time-string' which are used for time stamps.")
  529. ;;; The custom variables
  530. (defgroup org nil
  531. "Outline-based notes management and organizer."
  532. :tag "Org"
  533. :group 'outlines
  534. :group 'calendar)
  535. (defcustom org-mode-hook nil
  536. "Mode hook for Org-mode, run after the mode was turned on."
  537. :group 'org
  538. :type 'hook)
  539. (defcustom org-load-hook nil
  540. "Hook that is run after org.el has been loaded."
  541. :group 'org
  542. :type 'hook)
  543. (defcustom org-log-buffer-setup-hook nil
  544. "Hook that is run after an Org log buffer is created."
  545. :group 'org
  546. :version "24.1"
  547. :type 'hook)
  548. (defvar org-modules) ; defined below
  549. (defvar org-modules-loaded nil
  550. "Have the modules been loaded already?")
  551. (defun org-load-modules-maybe (&optional force)
  552. "Load all extensions listed in `org-modules'."
  553. (when (or force (not org-modules-loaded))
  554. (dolist (ext org-modules)
  555. (condition-case nil (require ext)
  556. (error (message "Problems while trying to load feature `%s'" ext))))
  557. (setq org-modules-loaded t)))
  558. (defun org-set-modules (var value)
  559. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  560. (set var value)
  561. (when (featurep 'org)
  562. (org-load-modules-maybe 'force)
  563. (org-element-cache-reset 'all)))
  564. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  565. "Modules that should always be loaded together with org.el.
  566. If a description starts with <C>, the file is not part of Emacs
  567. and loading it will require that you have downloaded and properly
  568. installed the Org mode distribution.
  569. You can also use this system to load external packages (i.e. neither Org
  570. core modules, nor modules from the CONTRIB directory). Just add symbols
  571. to the end of the list. If the package is called org-xyz.el, then you need
  572. to add the symbol `xyz', and the package must have a call to:
  573. (provide \\='org-xyz)
  574. For export specific modules, see also `org-export-backends'."
  575. :group 'org
  576. :set 'org-set-modules
  577. :version "24.4"
  578. :package-version '(Org . "8.0")
  579. :type
  580. '(set :greedy t
  581. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  582. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  583. (const :tag " crypt: Encryption of subtrees" org-crypt)
  584. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  585. (const :tag " docview: Links to doc-view buffers" org-docview)
  586. (const :tag " eww: Store link to url of eww" org-eww)
  587. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  588. (const :tag " habit: Track your consistency with habits" org-habit)
  589. (const :tag " id: Global IDs for identifying entries" org-id)
  590. (const :tag " info: Links to Info nodes" org-info)
  591. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  592. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  593. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  594. (const :tag " mouse: Additional mouse support" org-mouse)
  595. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  596. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  597. (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
  598. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  599. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  600. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  601. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  602. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  603. (const :tag "C collector: Collect properties into tables" org-collector)
  604. (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  605. (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
  606. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  607. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  608. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  609. (const :tag "C eval: Include command output as text" org-eval)
  610. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  611. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  612. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  613. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  614. (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
  615. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  616. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  617. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  618. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  619. (const :tag "C man: Support for links to manpages in Org-mode" org-man)
  620. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  621. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  622. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  623. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  624. (const :tag "C registry: A registry for Org links" org-registry)
  625. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  626. (const :tag "C secretary: Team management with org-mode" org-secretary)
  627. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  628. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  629. (const :tag "C track: Keep up with Org mode development" org-track)
  630. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  631. (const :tag "C vm: Links to VM folders/messages" org-vm)
  632. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  633. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  634. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  635. (defvar org-export-registered-backends) ; From ox.el.
  636. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  637. (declare-function org-export-backend-name "ox" (backend) t)
  638. (defcustom org-export-backends '(ascii html icalendar latex odt)
  639. "List of export back-ends that should be always available.
  640. If a description starts with <C>, the file is not part of Emacs
  641. and loading it will require that you have downloaded and properly
  642. installed the Org mode distribution.
  643. Unlike to `org-modules', libraries in this list will not be
  644. loaded along with Org, but only once the export framework is
  645. needed.
  646. This variable needs to be set before org.el is loaded. If you
  647. need to make a change while Emacs is running, use the customize
  648. interface or run the following code, where VAL stands for the new
  649. value of the variable, after updating it:
  650. (progn
  651. (setq org-export-registered-backends
  652. (cl-remove-if-not
  653. (lambda (backend)
  654. (let ((name (org-export-backend-name backend)))
  655. (or (memq name val)
  656. (catch \\='parentp
  657. (dolist (b val)
  658. (and (org-export-derived-backend-p b name)
  659. (throw \\='parentp t)))))))
  660. org-export-registered-backends))
  661. (let ((new-list (mapcar #\\='org-export-backend-name
  662. org-export-registered-backends)))
  663. (dolist (backend val)
  664. (cond
  665. ((not (load (format \"ox-%s\" backend) t t))
  666. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  667. backend))
  668. ((not (memq backend new-list)) (push backend new-list))))
  669. (set-default \\='org-export-backends new-list)))
  670. Adding a back-end to this list will also pull the back-end it
  671. depends on, if any."
  672. :group 'org
  673. :group 'org-export
  674. :version "25.1"
  675. :package-version '(Org . "9.0")
  676. :initialize 'custom-initialize-set
  677. :set (lambda (var val)
  678. (if (not (featurep 'ox)) (set-default var val)
  679. ;; Any back-end not required anymore (not present in VAL and not
  680. ;; a parent of any back-end in the new value) is removed from the
  681. ;; list of registered back-ends.
  682. (setq org-export-registered-backends
  683. (cl-remove-if-not
  684. (lambda (backend)
  685. (let ((name (org-export-backend-name backend)))
  686. (or (memq name val)
  687. (catch 'parentp
  688. (dolist (b val)
  689. (and (org-export-derived-backend-p b name)
  690. (throw 'parentp t)))))))
  691. org-export-registered-backends))
  692. ;; Now build NEW-LIST of both new back-ends and required
  693. ;; parents.
  694. (let ((new-list (mapcar #'org-export-backend-name
  695. org-export-registered-backends)))
  696. (dolist (backend val)
  697. (cond
  698. ((not (load (format "ox-%s" backend) t t))
  699. (message "Problems while trying to load export back-end `%s'"
  700. backend))
  701. ((not (memq backend new-list)) (push backend new-list))))
  702. ;; Set VAR to that list with fixed dependencies.
  703. (set-default var new-list))))
  704. :type '(set :greedy t
  705. (const :tag " ascii Export buffer to ASCII format" ascii)
  706. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  707. (const :tag " html Export buffer to HTML format" html)
  708. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  709. (const :tag " latex Export buffer to LaTeX format" latex)
  710. (const :tag " man Export buffer to MAN format" man)
  711. (const :tag " md Export buffer to Markdown format" md)
  712. (const :tag " odt Export buffer to ODT format" odt)
  713. (const :tag " org Export buffer to Org format" org)
  714. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  715. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  716. (const :tag "C deck Export buffer to deck.js presentations" deck)
  717. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  718. (const :tag "C groff Export buffer to Groff format" groff)
  719. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  720. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  721. (const :tag "C s5 Export buffer to s5 presentations" s5)
  722. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  723. (eval-after-load 'ox
  724. '(dolist (backend org-export-backends)
  725. (condition-case nil (require (intern (format "ox-%s" backend)))
  726. (error (message "Problems while trying to load export back-end `%s'"
  727. backend)))))
  728. (defcustom org-support-shift-select nil
  729. "Non-nil means make shift-cursor commands select text when possible.
  730. \\<org-mode-map>\
  731. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  732. start selecting a region, or enlarge regions started in this way.
  733. In Org-mode, in special contexts, these same keys are used for
  734. other purposes, important enough to compete with shift selection.
  735. Org tries to balance these needs by supporting `shift-select-mode'
  736. outside these special contexts, under control of this variable.
  737. The default of this variable is nil, to avoid confusing behavior. Shifted
  738. cursor keys will then execute Org commands in the following contexts:
  739. - on a headline, changing TODO state (left/right) and priority (up/down)
  740. - on a time stamp, changing the time
  741. - in a plain list item, changing the bullet type
  742. - in a property definition line, switching between allowed values
  743. - in the BEGIN line of a clock table (changing the time block).
  744. Outside these contexts, the commands will throw an error.
  745. When this variable is t and the cursor is not in a special
  746. context, Org mode will support shift-selection for making and
  747. enlarging regions. To make this more effective, the bullet
  748. cycling will no longer happen anywhere in an item line, but only
  749. if the cursor is exactly on the bullet.
  750. If you set this variable to the symbol `always', then the keys
  751. will not be special in headlines, property lines, and item lines,
  752. to make shift selection work there as well. If this is what you
  753. want, you can use the following alternative commands:
  754. `\\[org-todo]' and `\\[org-priority]' \
  755. to change TODO state and priority,
  756. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  757. can be used to switch TODO sets,
  758. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  759. and properties can be edited by hand or in column view.
  760. However, when the cursor is on a timestamp, shift-cursor commands
  761. will still edit the time stamp - this is just too good to give up."
  762. :group 'org
  763. :type '(choice
  764. (const :tag "Never" nil)
  765. (const :tag "When outside special context" t)
  766. (const :tag "Everywhere except timestamps" always)))
  767. (defcustom org-loop-over-headlines-in-active-region nil
  768. "Shall some commands act upon headlines in the active region?
  769. When set to t, some commands will be performed in all headlines
  770. within the active region.
  771. When set to `start-level', some commands will be performed in all
  772. headlines within the active region, provided that these headlines
  773. are of the same level than the first one.
  774. When set to a string, those commands will be performed on the
  775. matching headlines within the active region. Such string must be
  776. a tags/property/todo match as it is used in the agenda tags view.
  777. The list of commands is: `org-schedule', `org-deadline',
  778. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  779. `org-archive-to-archive-sibling'. The archiving commands skip
  780. already archived entries."
  781. :type '(choice (const :tag "Don't loop" nil)
  782. (const :tag "All headlines in active region" t)
  783. (const :tag "In active region, headlines at the same level than the first one" start-level)
  784. (string :tag "Tags/Property/Todo matcher"))
  785. :version "24.1"
  786. :group 'org-todo
  787. :group 'org-archive)
  788. (defgroup org-startup nil
  789. "Options concerning startup of Org-mode."
  790. :tag "Org Startup"
  791. :group 'org)
  792. (defcustom org-startup-folded t
  793. "Non-nil means entering Org mode will switch to OVERVIEW.
  794. This can also be configured on a per-file basis by adding one of
  795. the following lines anywhere in the buffer:
  796. #+STARTUP: fold (or `overview', this is equivalent)
  797. #+STARTUP: nofold (or `showall', this is equivalent)
  798. #+STARTUP: content
  799. #+STARTUP: showeverything
  800. By default, this option is ignored when Org opens agenda files
  801. for the first time. If you want the agenda to honor the startup
  802. option, set `org-agenda-inhibit-startup' to nil."
  803. :group 'org-startup
  804. :type '(choice
  805. (const :tag "nofold: show all" nil)
  806. (const :tag "fold: overview" t)
  807. (const :tag "content: all headlines" content)
  808. (const :tag "show everything, even drawers" showeverything)))
  809. (defcustom org-startup-truncated t
  810. "Non-nil means entering Org mode will set `truncate-lines'.
  811. This is useful since some lines containing links can be very long and
  812. uninteresting. Also tables look terrible when wrapped.
  813. The variable `org-startup-truncated' allows to configure
  814. truncation for Org mode different to the other modes that use the
  815. variable `truncate-lines' and as a shortcut instead of putting
  816. the variable `truncate-lines' into the `org-mode-hook'. If one
  817. wants to configure truncation for Org mode not statically but
  818. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  819. the variable `truncate-lines' has to be used because in such a
  820. case it is too late to set the variable `org-startup-truncated'."
  821. :group 'org-startup
  822. :type 'boolean)
  823. (defcustom org-startup-indented nil
  824. "Non-nil means turn on `org-indent-mode' on startup.
  825. This can also be configured on a per-file basis by adding one of
  826. the following lines anywhere in the buffer:
  827. #+STARTUP: indent
  828. #+STARTUP: noindent"
  829. :group 'org-structure
  830. :type '(choice
  831. (const :tag "Not" nil)
  832. (const :tag "Globally (slow on startup in large files)" t)))
  833. (defcustom org-use-sub-superscripts t
  834. "Non-nil means interpret \"_\" and \"^\" for display.
  835. If you want to control how Org exports those characters, see
  836. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  837. used to be an alias for `org-export-with-sub-superscripts' in
  838. Org <8.0, it is not anymore.
  839. When this option is turned on, you can use TeX-like syntax for
  840. sub- and superscripts within the buffer. Several characters after
  841. \"_\" or \"^\" will be considered as a single item - so grouping
  842. with {} is normally not needed. For example, the following things
  843. will be parsed as single sub- or superscripts:
  844. 10^24 or 10^tau several digits will be considered 1 item.
  845. 10^-12 or 10^-tau a leading sign with digits or a word
  846. x^2-y^3 will be read as x^2 - y^3, because items are
  847. terminated by almost any nonword/nondigit char.
  848. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  849. Still, ambiguity is possible. So when in doubt, use {} to enclose
  850. the sub/superscript. If you set this variable to the symbol `{}',
  851. the braces are *required* in order to trigger interpretations as
  852. sub/superscript. This can be helpful in documents that need \"_\"
  853. frequently in plain text."
  854. :group 'org-startup
  855. :version "24.4"
  856. :package-version '(Org . "8.0")
  857. :type '(choice
  858. (const :tag "Always interpret" t)
  859. (const :tag "Only with braces" {})
  860. (const :tag "Never interpret" nil)))
  861. (defcustom org-startup-with-beamer-mode nil
  862. "Non-nil means turn on `org-beamer-mode' on startup.
  863. This can also be configured on a per-file basis by adding one of
  864. the following lines anywhere in the buffer:
  865. #+STARTUP: beamer"
  866. :group 'org-startup
  867. :version "24.1"
  868. :type 'boolean)
  869. (defcustom org-startup-align-all-tables nil
  870. "Non-nil means align all tables when visiting a file.
  871. This is useful when the column width in tables is forced with <N> cookies
  872. in table fields. Such tables will look correct only after the first re-align.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: align
  876. #+STARTUP: noalign"
  877. :group 'org-startup
  878. :type 'boolean)
  879. (defcustom org-startup-with-inline-images nil
  880. "Non-nil means show inline images when loading a new Org file.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: inlineimages
  884. #+STARTUP: noinlineimages"
  885. :group 'org-startup
  886. :version "24.1"
  887. :type 'boolean)
  888. (defcustom org-startup-with-latex-preview nil
  889. "Non-nil means preview LaTeX fragments when loading a new Org file.
  890. This can also be configured on a per-file basis by adding one of
  891. the following lines anywhere in the buffer:
  892. #+STARTUP: latexpreview
  893. #+STARTUP: nolatexpreview"
  894. :group 'org-startup
  895. :version "24.4"
  896. :package-version '(Org . "8.0")
  897. :type 'boolean)
  898. (defcustom org-insert-mode-line-in-empty-file nil
  899. "Non-nil means insert the first line setting Org mode in empty files.
  900. When the function `org-mode' is called interactively in an empty file, this
  901. normally means that the file name does not automatically trigger Org mode.
  902. To ensure that the file will always be in Org mode in the future, a
  903. line enforcing Org mode will be inserted into the buffer, if this option
  904. has been set."
  905. :group 'org-startup
  906. :type 'boolean)
  907. (defcustom org-replace-disputed-keys nil
  908. "Non-nil means use alternative key bindings for some keys.
  909. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  910. These keys are also used by other packages like shift-selection-mode'
  911. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  912. If you want to use Org mode together with one of these other modes,
  913. or more generally if you would like to move some Org mode commands to
  914. other keys, set this variable and configure the keys with the variable
  915. `org-disputed-keys'.
  916. This option is only relevant at load-time of Org-mode, and must be set
  917. *before* org.el is loaded. Changing it requires a restart of Emacs to
  918. become effective."
  919. :group 'org-startup
  920. :type 'boolean)
  921. (defcustom org-use-extra-keys nil
  922. "Non-nil means use extra key sequence definitions for certain commands.
  923. This happens automatically if `window-system' is nil. This
  924. variable lets you do the same manually. You must set it before
  925. loading Org."
  926. :group 'org-startup
  927. :type 'boolean)
  928. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  929. (defcustom org-disputed-keys
  930. '(([(shift up)] . [(meta p)])
  931. ([(shift down)] . [(meta n)])
  932. ([(shift left)] . [(meta -)])
  933. ([(shift right)] . [(meta +)])
  934. ([(control shift right)] . [(meta shift +)])
  935. ([(control shift left)] . [(meta shift -)]))
  936. "Keys for which Org mode and other modes compete.
  937. This is an alist, cars are the default keys, second element specifies
  938. the alternative to use when `org-replace-disputed-keys' is t.
  939. Keys can be specified in any syntax supported by `define-key'.
  940. The value of this option takes effect only at Org-mode's startup,
  941. therefore you'll have to restart Emacs to apply it after changing."
  942. :group 'org-startup
  943. :type 'alist)
  944. (defun org-key (key)
  945. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  946. Or return the original if not disputed."
  947. (when org-replace-disputed-keys
  948. (let* ((nkey (key-description key))
  949. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  950. org-disputed-keys)))
  951. (setq key (if x (cdr x) key))))
  952. key)
  953. (defun org-defkey (keymap key def)
  954. "Define a key, possibly translated, as returned by `org-key'."
  955. (define-key keymap (org-key key) def))
  956. (defcustom org-ellipsis nil
  957. "The ellipsis to use in the Org mode outline.
  958. When nil, just use the standard three dots.
  959. When a string, use that string instead.
  960. When a face, use the standard 3 dots, but with the specified face.
  961. The change affects only Org mode (which will then use its own display table).
  962. Changing this requires executing \\[org-mode] in a buffer to become
  963. effective."
  964. :group 'org-startup
  965. :type '(choice (const :tag "Default" nil)
  966. (face :tag "Face" :value org-warning)
  967. (string :tag "String" :value "...#")))
  968. (defvar org-display-table nil
  969. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  970. (defgroup org-keywords nil
  971. "Keywords in Org-mode."
  972. :tag "Org Keywords"
  973. :group 'org)
  974. (defcustom org-closed-keep-when-no-todo nil
  975. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  976. :group 'org-todo
  977. :group 'org-keywords
  978. :version "24.4"
  979. :package-version '(Org . "8.0")
  980. :type 'boolean)
  981. (defgroup org-structure nil
  982. "Options concerning the general structure of Org files."
  983. :tag "Org Structure"
  984. :group 'org)
  985. (defgroup org-reveal-location nil
  986. "Options about how to make context of a location visible."
  987. :tag "Org Reveal Location"
  988. :group 'org-structure)
  989. (defcustom org-show-context-detail '((agenda . local)
  990. (bookmark-jump . lineage)
  991. (isearch . lineage)
  992. (default . ancestors))
  993. "Alist between context and visibility span when revealing a location.
  994. \\<org-mode-map>Some actions may move point into invisible
  995. locations. As a consequence, Org always expose a neighborhood
  996. around point. How much is shown depends on the initial action,
  997. or context. Valid contexts are
  998. agenda when exposing an entry from the agenda
  999. org-goto when using the command `org-goto' (\\[org-goto])
  1000. occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
  1001. tags-tree when constructing a sparse tree based on tags matches
  1002. link-search when exposing search matches associated with a link
  1003. mark-goto when exposing the jump goal of a mark
  1004. bookmark-jump when exposing a bookmark location
  1005. isearch when exiting from an incremental search
  1006. default default for all contexts not set explicitly
  1007. Allowed visibility spans are
  1008. minimal show current headline; if point is not on headline,
  1009. also show entry
  1010. local show current headline, entry and next headline
  1011. ancestors show current headline and its direct ancestors; if
  1012. point is not on headline, also show entry
  1013. lineage show current headline, its direct ancestors and all
  1014. their children; if point is not on headline, also show
  1015. entry and first child
  1016. tree show current headline, its direct ancestors and all
  1017. their children; if point is not on headline, also show
  1018. entry and all children
  1019. canonical show current headline, its direct ancestors along with
  1020. their entries and children; if point is not located on
  1021. the headline, also show current entry and all children
  1022. As special cases, a nil or t value means show all contexts in
  1023. `minimal' or `canonical' view, respectively.
  1024. Some views can make displayed information very compact, but also
  1025. make it harder to edit the location of the match. In such
  1026. a case, use the command `org-reveal' (\\[org-reveal]) to show
  1027. more context."
  1028. :group 'org-reveal-location
  1029. :version "25.2"
  1030. :package-version '(Org . "9.0")
  1031. :type '(choice
  1032. (const :tag "Canonical" t)
  1033. (const :tag "Minimal" nil)
  1034. (repeat :greedy t :tag "Individual contexts"
  1035. (cons
  1036. (choice :tag "Context"
  1037. (const agenda)
  1038. (const org-goto)
  1039. (const occur-tree)
  1040. (const tags-tree)
  1041. (const link-search)
  1042. (const mark-goto)
  1043. (const bookmark-jump)
  1044. (const isearch)
  1045. (const default))
  1046. (choice :tag "Detail level"
  1047. (const minimal)
  1048. (const local)
  1049. (const ancestors)
  1050. (const lineage)
  1051. (const tree)
  1052. (const canonical))))))
  1053. (defcustom org-indirect-buffer-display 'other-window
  1054. "How should indirect tree buffers be displayed?
  1055. This applies to indirect buffers created with the commands
  1056. \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
  1057. Valid values are:
  1058. current-window Display in the current window
  1059. other-window Just display in another window.
  1060. dedicated-frame Create one new frame, and re-use it each time.
  1061. new-frame Make a new frame each time. Note that in this case
  1062. previously-made indirect buffers are kept, and you need to
  1063. kill these buffers yourself."
  1064. :group 'org-structure
  1065. :group 'org-agenda-windows
  1066. :type '(choice
  1067. (const :tag "In current window" current-window)
  1068. (const :tag "In current frame, other window" other-window)
  1069. (const :tag "Each time a new frame" new-frame)
  1070. (const :tag "One dedicated frame" dedicated-frame)))
  1071. (defcustom org-use-speed-commands nil
  1072. "Non-nil means activate single letter commands at beginning of a headline.
  1073. This may also be a function to test for appropriate locations where speed
  1074. commands should be active.
  1075. For example, to activate speed commands when the point is on any
  1076. star at the beginning of the headline, you can do this:
  1077. (setq org-use-speed-commands
  1078. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1079. :group 'org-structure
  1080. :type '(choice
  1081. (const :tag "Never" nil)
  1082. (const :tag "At beginning of headline stars" t)
  1083. (function)))
  1084. (defcustom org-speed-commands-user nil
  1085. "Alist of additional speed commands.
  1086. This list will be checked before `org-speed-commands-default'
  1087. when the variable `org-use-speed-commands' is non-nil
  1088. and when the cursor is at the beginning of a headline.
  1089. The car if each entry is a string with a single letter, which must
  1090. be assigned to `self-insert-command' in the global map.
  1091. The cdr is either a command to be called interactively, a function
  1092. to be called, or a form to be evaluated.
  1093. An entry that is just a list with a single string will be interpreted
  1094. as a descriptive headline that will be added when listing the speed
  1095. commands in the Help buffer using the `?' speed command."
  1096. :group 'org-structure
  1097. :type '(repeat :value ("k" . ignore)
  1098. (choice :value ("k" . ignore)
  1099. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1100. (cons :tag "Letter and Command"
  1101. (string :tag "Command letter")
  1102. (choice
  1103. (function)
  1104. (sexp))))))
  1105. (defcustom org-bookmark-names-plist
  1106. '(:last-capture "org-capture-last-stored"
  1107. :last-refile "org-refile-last-stored"
  1108. :last-capture-marker "org-capture-last-stored-marker")
  1109. "Names for bookmarks automatically set by some Org commands.
  1110. This can provide strings as names for a number of bookmarks Org sets
  1111. automatically. The following keys are currently implemented:
  1112. :last-capture
  1113. :last-capture-marker
  1114. :last-refile
  1115. When a key does not show up in the property list, the corresponding bookmark
  1116. is not set."
  1117. :group 'org-structure
  1118. :type 'plist)
  1119. (defgroup org-cycle nil
  1120. "Options concerning visibility cycling in Org-mode."
  1121. :tag "Org Cycle"
  1122. :group 'org-structure)
  1123. (defcustom org-cycle-skip-children-state-if-no-children t
  1124. "Non-nil means skip CHILDREN state in entries that don't have any."
  1125. :group 'org-cycle
  1126. :type 'boolean)
  1127. (defcustom org-cycle-max-level nil
  1128. "Maximum level which should still be subject to visibility cycling.
  1129. Levels higher than this will, for cycling, be treated as text, not a headline.
  1130. When `org-odd-levels-only' is set, a value of N in this variable actually
  1131. means 2N-1 stars as the limiting headline.
  1132. When nil, cycle all levels.
  1133. Note that the limiting level of cycling is also influenced by
  1134. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1135. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1136. than its value."
  1137. :group 'org-cycle
  1138. :type '(choice
  1139. (const :tag "No limit" nil)
  1140. (integer :tag "Maximum level")))
  1141. (defcustom org-hide-block-startup nil
  1142. "Non-nil means entering Org mode will fold all blocks.
  1143. This can also be set in on a per-file basis with
  1144. #+STARTUP: hideblocks
  1145. #+STARTUP: showblocks"
  1146. :group 'org-startup
  1147. :group 'org-cycle
  1148. :type 'boolean)
  1149. (defcustom org-cycle-global-at-bob nil
  1150. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1151. This makes it possible to do global cycling without having to use S-TAB or
  1152. \\[universal-argument] TAB. For this special case to work, the first line
  1153. of the buffer must not be a headline -- it may be empty or some other text.
  1154. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1155. sure the cursor stays at the beginning of the buffer. When this option is
  1156. nil, don't do anything special at the beginning of the buffer."
  1157. :group 'org-cycle
  1158. :type 'boolean)
  1159. (defcustom org-cycle-level-after-item/entry-creation t
  1160. "Non-nil means cycle entry level or item indentation in new empty entries.
  1161. When the cursor is at the end of an empty headline, i.e., with only stars
  1162. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1163. and then all possible ancestor states, before returning to the original state.
  1164. This makes data entry extremely fast: M-RET to create a new headline,
  1165. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1166. When the cursor is at the end of an empty plain list item, one TAB will
  1167. make it a subitem, two or more tabs will back up to make this an item
  1168. higher up in the item hierarchy."
  1169. :group 'org-cycle
  1170. :type 'boolean)
  1171. (defcustom org-cycle-emulate-tab t
  1172. "Where should `org-cycle' emulate TAB.
  1173. nil Never
  1174. white Only in completely white lines
  1175. whitestart Only at the beginning of lines, before the first non-white char
  1176. t Everywhere except in headlines
  1177. exc-hl-bol Everywhere except at the start of a headline
  1178. If TAB is used in a place where it does not emulate TAB, the current subtree
  1179. visibility is cycled."
  1180. :group 'org-cycle
  1181. :type '(choice (const :tag "Never" nil)
  1182. (const :tag "Only in completely white lines" white)
  1183. (const :tag "Before first char in a line" whitestart)
  1184. (const :tag "Everywhere except in headlines" t)
  1185. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1186. (defcustom org-cycle-separator-lines 2
  1187. "Number of empty lines needed to keep an empty line between collapsed trees.
  1188. If you leave an empty line between the end of a subtree and the following
  1189. headline, this empty line is hidden when the subtree is folded.
  1190. Org mode will leave (exactly) one empty line visible if the number of
  1191. empty lines is equal or larger to the number given in this variable.
  1192. So the default 2 means at least 2 empty lines after the end of a subtree
  1193. are needed to produce free space between a collapsed subtree and the
  1194. following headline.
  1195. If the number is negative, and the number of empty lines is at least -N,
  1196. all empty lines are shown.
  1197. Special case: when 0, never leave empty lines in collapsed view."
  1198. :group 'org-cycle
  1199. :type 'integer)
  1200. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1201. (defcustom org-pre-cycle-hook nil
  1202. "Hook that is run before visibility cycling is happening.
  1203. The function(s) in this hook must accept a single argument which indicates
  1204. the new state that will be set right after running this hook. The
  1205. argument is a symbol. Before a global state change, it can have the values
  1206. `overview', `content', or `all'. Before a local state change, it can have
  1207. the values `folded', `children', or `subtree'."
  1208. :group 'org-cycle
  1209. :type 'hook)
  1210. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1211. org-cycle-hide-drawers
  1212. org-cycle-show-empty-lines
  1213. org-optimize-window-after-visibility-change)
  1214. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1215. The function(s) in this hook must accept a single argument which indicates
  1216. the new state that was set by the most recent `org-cycle' command. The
  1217. argument is a symbol. After a global state change, it can have the values
  1218. `overview', `contents', or `all'. After a local state change, it can have
  1219. the values `folded', `children', or `subtree'."
  1220. :group 'org-cycle
  1221. :type 'hook
  1222. :version "25.1"
  1223. :package-version '(Org . "8.3"))
  1224. (defgroup org-edit-structure nil
  1225. "Options concerning structure editing in Org-mode."
  1226. :tag "Org Edit Structure"
  1227. :group 'org-structure)
  1228. (defcustom org-odd-levels-only nil
  1229. "Non-nil means skip even levels and only use odd levels for the outline.
  1230. This has the effect that two stars are being added/taken away in
  1231. promotion/demotion commands. It also influences how levels are
  1232. handled by the exporters.
  1233. Changing it requires restart of `font-lock-mode' to become effective
  1234. for fontification also in regions already fontified.
  1235. You may also set this on a per-file basis by adding one of the following
  1236. lines to the buffer:
  1237. #+STARTUP: odd
  1238. #+STARTUP: oddeven"
  1239. :group 'org-edit-structure
  1240. :group 'org-appearance
  1241. :type 'boolean)
  1242. (defcustom org-adapt-indentation t
  1243. "Non-nil means adapt indentation to outline node level.
  1244. When this variable is set, Org assumes that you write outlines by
  1245. indenting text in each node to align with the headline (after the
  1246. stars). The following issues are influenced by this variable:
  1247. - The indentation is increased by one space in a demotion
  1248. command, and decreased by one in a promotion command. However,
  1249. in the latter case, if shifting some line in the entry body
  1250. would alter document structure (e.g., insert a new headline),
  1251. indentation is not changed at all.
  1252. - Property drawers and planning information is inserted indented
  1253. when this variable is set. When nil, they will not be indented.
  1254. - TAB indents a line relative to current level. The lines below
  1255. a headline will be indented when this variable is set.
  1256. Note that this is all about true indentation, by adding and
  1257. removing space characters. See also `org-indent.el' which does
  1258. level-dependent indentation in a virtual way, i.e. at display
  1259. time in Emacs."
  1260. :group 'org-edit-structure
  1261. :type 'boolean)
  1262. (defcustom org-special-ctrl-a/e nil
  1263. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1264. When t, `C-a' will bring back the cursor to the beginning of the
  1265. headline text, i.e. after the stars and after a possible TODO
  1266. keyword. In an item, this will be the position after bullet and
  1267. check-box, if any. When the cursor is already at that position,
  1268. another `C-a' will bring it to the beginning of the line.
  1269. `C-e' will jump to the end of the headline, ignoring the presence
  1270. of tags in the headline. A second `C-e' will then jump to the
  1271. true end of the line, after any tags. This also means that, when
  1272. this variable is non-nil, `C-e' also will never jump beyond the
  1273. end of the heading of a folded section, i.e. not after the
  1274. ellipses.
  1275. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1276. normally, going to the true line boundary first. Only a directly
  1277. following, identical keypress will bring the cursor to the
  1278. special positions.
  1279. This may also be a cons cell where the behavior for `C-a' and
  1280. `C-e' is set separately."
  1281. :group 'org-edit-structure
  1282. :type '(choice
  1283. (const :tag "off" nil)
  1284. (const :tag "on: after stars/bullet and before tags first" t)
  1285. (const :tag "reversed: true line boundary first" reversed)
  1286. (cons :tag "Set C-a and C-e separately"
  1287. (choice :tag "Special C-a"
  1288. (const :tag "off" nil)
  1289. (const :tag "on: after stars/bullet first" t)
  1290. (const :tag "reversed: before stars/bullet first" reversed))
  1291. (choice :tag "Special C-e"
  1292. (const :tag "off" nil)
  1293. (const :tag "on: before tags first" t)
  1294. (const :tag "reversed: after tags first" reversed)))))
  1295. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1296. (defcustom org-special-ctrl-k nil
  1297. "Non-nil means `C-k' will behave specially in headlines.
  1298. When nil, `C-k' will call the default `kill-line' command.
  1299. When t, the following will happen while the cursor is in the headline:
  1300. - When the cursor is at the beginning of a headline, kill the entire
  1301. line and possible the folded subtree below the line.
  1302. - When in the middle of the headline text, kill the headline up to the tags.
  1303. - When after the headline text, kill the tags."
  1304. :group 'org-edit-structure
  1305. :type 'boolean)
  1306. (defcustom org-ctrl-k-protect-subtree nil
  1307. "Non-nil means, do not delete a hidden subtree with C-k.
  1308. When set to the symbol `error', simply throw an error when C-k is
  1309. used to kill (part-of) a headline that has hidden text behind it.
  1310. Any other non-nil value will result in a query to the user, if it is
  1311. OK to kill that hidden subtree. When nil, kill without remorse."
  1312. :group 'org-edit-structure
  1313. :version "24.1"
  1314. :type '(choice
  1315. (const :tag "Do not protect hidden subtrees" nil)
  1316. (const :tag "Protect hidden subtrees with a security query" t)
  1317. (const :tag "Never kill a hidden subtree with C-k" error)))
  1318. (defcustom org-special-ctrl-o t
  1319. "Non-nil means, make `C-o' insert a row in tables."
  1320. :group 'org-edit-structure
  1321. :type 'boolean)
  1322. (defcustom org-catch-invisible-edits nil
  1323. "Check if in invisible region before inserting or deleting a character.
  1324. Valid values are:
  1325. nil Do not check, so just do invisible edits.
  1326. error Throw an error and do nothing.
  1327. show Make point visible, and do the requested edit.
  1328. show-and-error Make point visible, then throw an error and abort the edit.
  1329. smart Make point visible, and do insertion/deletion if it is
  1330. adjacent to visible text and the change feels predictable.
  1331. Never delete a previously invisible character or add in the
  1332. middle or right after an invisible region. Basically, this
  1333. allows insertion and backward-delete right before ellipses.
  1334. FIXME: maybe in this case we should not even show?"
  1335. :group 'org-edit-structure
  1336. :version "24.1"
  1337. :type '(choice
  1338. (const :tag "Do not check" nil)
  1339. (const :tag "Throw error when trying to edit" error)
  1340. (const :tag "Unhide, but do not do the edit" show-and-error)
  1341. (const :tag "Show invisible part and do the edit" show)
  1342. (const :tag "Be smart and do the right thing" smart)))
  1343. (defcustom org-yank-folded-subtrees t
  1344. "Non-nil means when yanking subtrees, fold them.
  1345. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1346. it starts with a heading and all other headings in it are either children
  1347. or siblings, then fold all the subtrees. However, do this only if no
  1348. text after the yank would be swallowed into a folded tree by this action."
  1349. :group 'org-edit-structure
  1350. :type 'boolean)
  1351. (defcustom org-yank-adjusted-subtrees nil
  1352. "Non-nil means when yanking subtrees, adjust the level.
  1353. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1354. this function for details."
  1355. :group 'org-edit-structure
  1356. :type 'boolean)
  1357. (defcustom org-M-RET-may-split-line '((default . t))
  1358. "Non-nil means M-RET will split the line at the cursor position.
  1359. When nil, it will go to the end of the line before making a
  1360. new line.
  1361. You may also set this option in a different way for different
  1362. contexts. Valid contexts are:
  1363. headline when creating a new headline
  1364. item when creating a new item
  1365. table in a table field
  1366. default the value to be used for all contexts not explicitly
  1367. customized"
  1368. :group 'org-structure
  1369. :group 'org-table
  1370. :type '(choice
  1371. (const :tag "Always" t)
  1372. (const :tag "Never" nil)
  1373. (repeat :greedy t :tag "Individual contexts"
  1374. (cons
  1375. (choice :tag "Context"
  1376. (const headline)
  1377. (const item)
  1378. (const table)
  1379. (const default))
  1380. (boolean)))))
  1381. (defcustom org-insert-heading-respect-content nil
  1382. "Non-nil means insert new headings after the current subtree.
  1383. When nil, the new heading is created directly after the current line.
  1384. The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
  1385. this variable on for the duration of the command."
  1386. :group 'org-structure
  1387. :type 'boolean)
  1388. (defcustom org-blank-before-new-entry '((heading . auto)
  1389. (plain-list-item . auto))
  1390. "Should `org-insert-heading' leave a blank line before new heading/item?
  1391. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1392. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1393. which case Org will look at the surrounding headings/items and try to
  1394. make an intelligent decision whether to insert a blank line or not."
  1395. :group 'org-edit-structure
  1396. :type '(list
  1397. (cons (const heading)
  1398. (choice (const :tag "Never" nil)
  1399. (const :tag "Always" t)
  1400. (const :tag "Auto" auto)))
  1401. (cons (const plain-list-item)
  1402. (choice (const :tag "Never" nil)
  1403. (const :tag "Always" t)
  1404. (const :tag "Auto" auto)))))
  1405. (defcustom org-insert-heading-hook nil
  1406. "Hook being run after inserting a new heading."
  1407. :group 'org-edit-structure
  1408. :type 'hook)
  1409. (defcustom org-enable-fixed-width-editor t
  1410. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1411. This currently only means they are never auto-wrapped.
  1412. When nil, such lines will be treated like ordinary lines."
  1413. :group 'org-edit-structure
  1414. :type 'boolean)
  1415. (defcustom org-goto-auto-isearch t
  1416. "Non-nil means typing characters in `org-goto' starts incremental search.
  1417. When nil, you can use these keybindings to navigate the buffer:
  1418. q Quit the org-goto interface
  1419. n Go to the next visible heading
  1420. p Go to the previous visible heading
  1421. f Go one heading forward on same level
  1422. b Go one heading backward on same level
  1423. u Go one heading up"
  1424. :group 'org-edit-structure
  1425. :type 'boolean)
  1426. (defgroup org-sparse-trees nil
  1427. "Options concerning sparse trees in Org-mode."
  1428. :tag "Org Sparse Trees"
  1429. :group 'org-structure)
  1430. (defcustom org-highlight-sparse-tree-matches t
  1431. "Non-nil means highlight all matches that define a sparse tree.
  1432. The highlights will automatically disappear the next time the buffer is
  1433. changed by an edit command."
  1434. :group 'org-sparse-trees
  1435. :type 'boolean)
  1436. (defcustom org-remove-highlights-with-change t
  1437. "Non-nil means any change to the buffer will remove temporary highlights.
  1438. \\<org-mode-map>\
  1439. Such highlights are created by `org-occur' and `org-clock-display'.
  1440. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1441. to get rid of the highlights.
  1442. The highlights created by `org-toggle-latex-fragment' always need
  1443. `\\[org-toggle-latex-fragment]' to be removed."
  1444. :group 'org-sparse-trees
  1445. :group 'org-time
  1446. :type 'boolean)
  1447. (defcustom org-occur-case-fold-search t
  1448. "Non-nil means `org-occur' should be case-insensitive.
  1449. If set to `smart' the search will be case-insensitive only if it
  1450. doesn't specify any upper case character."
  1451. :group 'org-sparse-trees
  1452. :version "25.1"
  1453. :type '(choice
  1454. (const :tag "Case-sensitive" nil)
  1455. (const :tag "Case-insensitive" t)
  1456. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1457. (defcustom org-occur-hook '(org-first-headline-recenter)
  1458. "Hook that is run after `org-occur' has constructed a sparse tree.
  1459. This can be used to recenter the window to show as much of the structure
  1460. as possible."
  1461. :group 'org-sparse-trees
  1462. :type 'hook)
  1463. (defgroup org-imenu-and-speedbar nil
  1464. "Options concerning imenu and speedbar in Org-mode."
  1465. :tag "Org Imenu and Speedbar"
  1466. :group 'org-structure)
  1467. (defcustom org-imenu-depth 2
  1468. "The maximum level for Imenu access to Org headlines.
  1469. This also applied for speedbar access."
  1470. :group 'org-imenu-and-speedbar
  1471. :type 'integer)
  1472. (defgroup org-table nil
  1473. "Options concerning tables in Org-mode."
  1474. :tag "Org Table"
  1475. :group 'org)
  1476. (defcustom org-enable-table-editor 'optimized
  1477. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1478. When nil, such lines will be treated like ordinary lines.
  1479. When equal to the symbol `optimized', the table editor will be optimized to
  1480. do the following:
  1481. - Automatic overwrite mode in front of whitespace in table fields.
  1482. This makes the structure of the table stay in tact as long as the edited
  1483. field does not exceed the column width.
  1484. - Minimize the number of realigns. Normally, the table is aligned each time
  1485. TAB or RET are pressed to move to another field. With optimization this
  1486. happens only if changes to a field might have changed the column width.
  1487. Optimization requires replacing the functions `self-insert-command',
  1488. `delete-char', and `backward-delete-char' in Org buffers, with a
  1489. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1490. good at guessing when a re-align will be necessary, but you can always
  1491. force one with \\[org-ctrl-c-ctrl-c].
  1492. If you would like to use the optimized version in Org-mode, but the
  1493. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1494. This variable can be used to turn on and off the table editor during a session,
  1495. but in order to toggle optimization, a restart is required.
  1496. See also the variable `org-table-auto-blank-field'."
  1497. :group 'org-table
  1498. :type '(choice
  1499. (const :tag "off" nil)
  1500. (const :tag "on" t)
  1501. (const :tag "on, optimized" optimized)))
  1502. (defcustom org-self-insert-cluster-for-undo nil
  1503. "Non-nil means cluster self-insert commands for undo when possible.
  1504. If this is set, then, like in the Emacs command loop, 20 consecutive
  1505. characters will be undone together.
  1506. This is configurable, because there is some impact on typing performance."
  1507. :group 'org-table
  1508. :type 'boolean)
  1509. (defcustom org-table-tab-recognizes-table.el t
  1510. "Non-nil means TAB will automatically notice a table.el table.
  1511. When it sees such a table, it moves point into it and - if necessary -
  1512. calls `table-recognize-table'."
  1513. :group 'org-table-editing
  1514. :type 'boolean)
  1515. (defgroup org-link nil
  1516. "Options concerning links in Org-mode."
  1517. :tag "Org Link"
  1518. :group 'org)
  1519. (defvar-local org-link-abbrev-alist-local nil
  1520. "Buffer-local version of `org-link-abbrev-alist', which see.
  1521. The value of this is taken from the #+LINK lines.")
  1522. (defcustom org-link-parameters
  1523. '(("doi" :follow org--open-doi-link)
  1524. ("elisp" :follow org--open-elisp-link)
  1525. ("file" :complete org-file-complete-link)
  1526. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1527. ("help" :follow org--open-help-link)
  1528. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1529. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1530. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1531. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1532. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1533. ("shell" :follow org--open-shell-link))
  1534. "An alist of properties that defines all the links in Org mode.
  1535. The key in each association is a string of the link type.
  1536. Subsequent optional elements make up a p-list of link properties.
  1537. :follow - A function that takes the link path as an argument.
  1538. :export - A function that takes the link path, description and
  1539. export-backend as arguments.
  1540. :store - A function responsible for storing the link. See the
  1541. function `org-store-link-functions'.
  1542. :complete - A function that inserts a link with completion. The
  1543. function takes one optional prefix arg.
  1544. :face - A face for the link, or a function that returns a face.
  1545. The function takes one argument which is the link path. The
  1546. default face is `org-link'.
  1547. :mouse-face - The mouse-face. The default is `highlight'.
  1548. :display - `full' will not fold the link in descriptive
  1549. display. Default is `org-link'.
  1550. :help-echo - A string or function that takes (window object position)
  1551. as arguments and returns a string.
  1552. :keymap - A keymap that is active on the link. The default is
  1553. `org-mouse-map'.
  1554. :htmlize-link - A function for the htmlize-link. Defaults
  1555. to (list :uri \"type:path\")
  1556. :activate-func - A function to run at the end of font-lock
  1557. activation. The function must accept (link-start link-end path bracketp)
  1558. as arguments."
  1559. :group 'org-link
  1560. :type '(alist :tag "Link display parameters"
  1561. :value-type plist))
  1562. (defun org-link-get-parameter (type key)
  1563. "Get TYPE link property for KEY.
  1564. TYPE is a string and KEY is a plist keyword."
  1565. (plist-get
  1566. (cdr (assoc type org-link-parameters))
  1567. key))
  1568. (defun org-link-set-parameters (type &rest parameters)
  1569. "Set link TYPE properties to PARAMETERS.
  1570. PARAMETERS should be :key val pairs."
  1571. (let ((data (assoc type org-link-parameters)))
  1572. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1573. (push (cons type parameters) org-link-parameters)
  1574. (org-make-link-regexps)
  1575. (org-element-update-syntax))))
  1576. (defun org-link-types ()
  1577. "Return a list of known link types."
  1578. (mapcar #'car org-link-parameters))
  1579. (defcustom org-link-abbrev-alist nil
  1580. "Alist of link abbreviations.
  1581. The car of each element is a string, to be replaced at the start of a link.
  1582. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1583. links in Org buffers can have an optional tag after a double colon, e.g.,
  1584. [[linkkey:tag][description]]
  1585. The `linkkey' must be a single word, starting with a letter, followed
  1586. by letters, numbers, `-' or `_'.
  1587. If REPLACE is a string, the tag will simply be appended to create the link.
  1588. If the string contains \"%s\", the tag will be inserted there. If the string
  1589. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1590. at that point (see the function `url-hexify-string'). If the string contains
  1591. the specifier \"%(my-function)\", then the custom function `my-function' will
  1592. be invoked: this function takes the tag as its only argument and must return
  1593. a string.
  1594. REPLACE may also be a function that will be called with the tag as the
  1595. only argument to create the link, which should be returned as a string.
  1596. See the manual for examples."
  1597. :group 'org-link
  1598. :type '(repeat
  1599. (cons
  1600. (string :tag "Protocol")
  1601. (choice
  1602. (string :tag "Format")
  1603. (function)))))
  1604. (defcustom org-descriptive-links t
  1605. "Non-nil means Org will display descriptive links.
  1606. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1607. \"Org Website\", hiding the link itself and just displaying its
  1608. description. When set to nil, Org will display the full links
  1609. literally.
  1610. You can interactively set the value of this variable by calling
  1611. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1612. :group 'org-link
  1613. :type 'boolean)
  1614. (defcustom org-link-file-path-type 'adaptive
  1615. "How the path name in file links should be stored.
  1616. Valid values are:
  1617. relative Relative to the current directory, i.e. the directory of the file
  1618. into which the link is being inserted.
  1619. absolute Absolute path, if possible with ~ for home directory.
  1620. noabbrev Absolute path, no abbreviation of home directory.
  1621. adaptive Use relative path for files in the current directory and sub-
  1622. directories of it. For other files, use an absolute path."
  1623. :group 'org-link
  1624. :type '(choice
  1625. (const relative)
  1626. (const absolute)
  1627. (const noabbrev)
  1628. (const adaptive)))
  1629. (defvaralias 'org-activate-links 'org-highlight-links)
  1630. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1631. "Types of links that should be highlighted in Org files.
  1632. This is a list of symbols, each one of them leading to the
  1633. highlighting of a certain link type.
  1634. You can still open links that are not highlighted.
  1635. In principle, it does not hurt to turn on highlighting for all
  1636. link types. There may be a small gain when turning off unused
  1637. link types. The types are:
  1638. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1639. angle Links in angular brackets that may contain whitespace like
  1640. <bbdb:Carsten Dominik>.
  1641. plain Plain links in normal text, no whitespace, like http://google.com.
  1642. radio Text that is matched by a radio target, see manual for details.
  1643. tag Tag settings in a headline (link to tag search).
  1644. date Time stamps (link to calendar).
  1645. footnote Footnote labels.
  1646. If you set this variable during an Emacs session, use `org-mode-restart'
  1647. in the Org buffer so that the change takes effect."
  1648. :group 'org-link
  1649. :group 'org-appearance
  1650. :type '(set :greedy t
  1651. (const :tag "Double bracket links" bracket)
  1652. (const :tag "Angular bracket links" angle)
  1653. (const :tag "Plain text links" plain)
  1654. (const :tag "Radio target matches" radio)
  1655. (const :tag "Tags" tag)
  1656. (const :tag "Timestamps" date)
  1657. (const :tag "Footnotes" footnote)))
  1658. (defcustom org-make-link-description-function nil
  1659. "Function to use for generating link descriptions from links.
  1660. When nil, the link location will be used. This function must take
  1661. two parameters: the first one is the link, the second one is the
  1662. description generated by `org-insert-link'. The function should
  1663. return the description to use."
  1664. :group 'org-link
  1665. :type '(choice (const nil) (function)))
  1666. (defgroup org-link-store nil
  1667. "Options concerning storing links in Org-mode."
  1668. :tag "Org Store Link"
  1669. :group 'org-link)
  1670. (defcustom org-url-hexify-p t
  1671. "When non-nil, hexify URL when creating a link."
  1672. :type 'boolean
  1673. :version "24.3"
  1674. :group 'org-link-store)
  1675. (defcustom org-email-link-description-format "Email %c: %.30s"
  1676. "Format of the description part of a link to an email or usenet message.
  1677. The following %-escapes will be replaced by corresponding information:
  1678. %F full \"From\" field
  1679. %f name, taken from \"From\" field, address if no name
  1680. %T full \"To\" field
  1681. %t first name in \"To\" field, address if no name
  1682. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1683. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1684. %s subject
  1685. %d date
  1686. %m message-id.
  1687. You may use normal field width specification between the % and the letter.
  1688. This is for example useful to limit the length of the subject.
  1689. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1690. :group 'org-link-store
  1691. :type 'string)
  1692. (defcustom org-from-is-user-regexp
  1693. (let (r1 r2)
  1694. (when (and user-mail-address (not (string= user-mail-address "")))
  1695. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1696. (when (and user-full-name (not (string= user-full-name "")))
  1697. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1698. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1699. "Regexp matched against the \"From:\" header of an email or usenet message.
  1700. It should match if the message is from the user him/herself."
  1701. :group 'org-link-store
  1702. :type 'regexp)
  1703. (defcustom org-context-in-file-links t
  1704. "Non-nil means file links from `org-store-link' contain context.
  1705. A search string will be added to the file name with :: as separator and
  1706. used to find the context when the link is activated by the command
  1707. `org-open-at-point'. When this option is t, the entire active region
  1708. will be placed in the search string of the file link. If set to a
  1709. positive integer, only the first n lines of context will be stored.
  1710. Using a prefix arg to the command \\[org-store-link] (`org-store-link')
  1711. negates this setting for the duration of the command."
  1712. :group 'org-link-store
  1713. :type '(choice boolean integer))
  1714. (defcustom org-keep-stored-link-after-insertion nil
  1715. "Non-nil means keep link in list for entire session.
  1716. The command `org-store-link' adds a link pointing to the current
  1717. location to an internal list. These links accumulate during a session.
  1718. The command `org-insert-link' can be used to insert links into any
  1719. Org file (offering completion for all stored links). When this option
  1720. is nil, every link which has been inserted once using \\[org-insert-link]
  1721. will be removed from the list, to make completing the unused links
  1722. more efficient."
  1723. :group 'org-link-store
  1724. :type 'boolean)
  1725. (defgroup org-link-follow nil
  1726. "Options concerning following links in Org-mode."
  1727. :tag "Org Follow Link"
  1728. :group 'org-link)
  1729. (defcustom org-link-translation-function nil
  1730. "Function to translate links with different syntax to Org syntax.
  1731. This can be used to translate links created for example by the Planner
  1732. or emacs-wiki packages to Org syntax.
  1733. The function must accept two parameters, a TYPE containing the link
  1734. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1735. which is everything after the link protocol. It should return a cons
  1736. with possibly modified values of type and path.
  1737. Org contains a function for this, so if you set this variable to
  1738. `org-translate-link-from-planner', you should be able follow many
  1739. links created by planner."
  1740. :group 'org-link-follow
  1741. :type '(choice (const nil) (function)))
  1742. (defcustom org-follow-link-hook nil
  1743. "Hook that is run after a link has been followed."
  1744. :group 'org-link-follow
  1745. :type 'hook)
  1746. (defcustom org-tab-follows-link nil
  1747. "Non-nil means on links TAB will follow the link.
  1748. Needs to be set before org.el is loaded.
  1749. This really should not be used, it does not make sense, and the
  1750. implementation is bad."
  1751. :group 'org-link-follow
  1752. :type 'boolean)
  1753. (defcustom org-return-follows-link nil
  1754. "Non-nil means on links RET will follow the link.
  1755. In tables, the special behavior of RET has precedence."
  1756. :group 'org-link-follow
  1757. :type 'boolean)
  1758. (defcustom org-mouse-1-follows-link
  1759. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1760. "Non-nil means mouse-1 on a link will follow the link.
  1761. A longer mouse click will still set point. Needs to be set
  1762. before org.el is loaded."
  1763. :group 'org-link-follow
  1764. :version "24.4"
  1765. :package-version '(Org . "8.3")
  1766. :type '(choice
  1767. (const :tag "A double click follows the link" double)
  1768. (const :tag "Unconditionally follow the link with mouse-1" t)
  1769. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1770. (defcustom org-mark-ring-length 4
  1771. "Number of different positions to be recorded in the ring.
  1772. Changing this requires a restart of Emacs to work correctly."
  1773. :group 'org-link-follow
  1774. :type 'integer)
  1775. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1776. "Non-nil means internal links in Org files must exactly match a headline.
  1777. When nil, the link search tries to match a phrase with all words
  1778. in the search text."
  1779. :group 'org-link-follow
  1780. :version "24.1"
  1781. :type '(choice
  1782. (const :tag "Use fuzzy text search" nil)
  1783. (const :tag "Match only exact headline" t)
  1784. (const :tag "Match exact headline or query to create it"
  1785. query-to-create)))
  1786. (defcustom org-link-frame-setup
  1787. '((vm . vm-visit-folder-other-frame)
  1788. (vm-imap . vm-visit-imap-folder-other-frame)
  1789. (gnus . org-gnus-no-new-news)
  1790. (file . find-file-other-window)
  1791. (wl . wl-other-frame))
  1792. "Setup the frame configuration for following links.
  1793. When following a link with Emacs, it may often be useful to display
  1794. this link in another window or frame. This variable can be used to
  1795. set this up for the different types of links.
  1796. For VM, use any of
  1797. `vm-visit-folder'
  1798. `vm-visit-folder-other-window'
  1799. `vm-visit-folder-other-frame'
  1800. For Gnus, use any of
  1801. `gnus'
  1802. `gnus-other-frame'
  1803. `org-gnus-no-new-news'
  1804. For FILE, use any of
  1805. `find-file'
  1806. `find-file-other-window'
  1807. `find-file-other-frame'
  1808. For Wanderlust use any of
  1809. `wl'
  1810. `wl-other-frame'
  1811. For the calendar, use the variable `calendar-setup'.
  1812. For BBDB, it is currently only possible to display the matches in
  1813. another window."
  1814. :group 'org-link-follow
  1815. :type '(list
  1816. (cons (const vm)
  1817. (choice
  1818. (const vm-visit-folder)
  1819. (const vm-visit-folder-other-window)
  1820. (const vm-visit-folder-other-frame)))
  1821. (cons (const vm-imap)
  1822. (choice
  1823. (const vm-visit-imap-folder)
  1824. (const vm-visit-imap-folder-other-window)
  1825. (const vm-visit-imap-folder-other-frame)))
  1826. (cons (const gnus)
  1827. (choice
  1828. (const gnus)
  1829. (const gnus-other-frame)
  1830. (const org-gnus-no-new-news)))
  1831. (cons (const file)
  1832. (choice
  1833. (const find-file)
  1834. (const find-file-other-window)
  1835. (const find-file-other-frame)))
  1836. (cons (const wl)
  1837. (choice
  1838. (const wl)
  1839. (const wl-other-frame)))))
  1840. (defcustom org-display-internal-link-with-indirect-buffer nil
  1841. "Non-nil means use indirect buffer to display infile links.
  1842. Activating internal links (from one location in a file to another location
  1843. in the same file) normally just jumps to the location. When the link is
  1844. activated with a \\[universal-argument] prefix (or with mouse-3), the link \
  1845. is displayed in
  1846. another window. When this option is set, the other window actually displays
  1847. an indirect buffer clone of the current buffer, to avoid any visibility
  1848. changes to the current buffer."
  1849. :group 'org-link-follow
  1850. :type 'boolean)
  1851. (defcustom org-open-non-existing-files nil
  1852. "Non-nil means `org-open-file' will open non-existing files.
  1853. When nil, an error will be generated.
  1854. This variable applies only to external applications because they
  1855. might choke on non-existing files. If the link is to a file that
  1856. will be opened in Emacs, the variable is ignored."
  1857. :group 'org-link-follow
  1858. :type 'boolean)
  1859. (defcustom org-open-directory-means-index-dot-org nil
  1860. "Non-nil means a link to a directory really means to index.org.
  1861. When nil, following a directory link will run dired or open a finder/explorer
  1862. window on that directory."
  1863. :group 'org-link-follow
  1864. :type 'boolean)
  1865. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1866. "Non-nil means ask for confirmation before executing shell links.
  1867. Shell links can be dangerous: just think about a link
  1868. [[shell:rm -rf ~/*][Google Search]]
  1869. This link would show up in your Org document as \"Google Search\",
  1870. but really it would remove your entire home directory.
  1871. Therefore we advise against setting this variable to nil.
  1872. Just change it to `y-or-n-p' if you want to confirm with a
  1873. single keystroke rather than having to type \"yes\"."
  1874. :group 'org-link-follow
  1875. :type '(choice
  1876. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1877. (const :tag "with y-or-n (faster)" y-or-n-p)
  1878. (const :tag "no confirmation (dangerous)" nil)))
  1879. (put 'org-confirm-shell-link-function
  1880. 'safe-local-variable
  1881. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1882. (defcustom org-confirm-shell-link-not-regexp ""
  1883. "A regexp to skip confirmation for shell links."
  1884. :group 'org-link-follow
  1885. :version "24.1"
  1886. :type 'regexp)
  1887. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1888. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1889. Elisp links can be dangerous: just think about a link
  1890. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1891. This link would show up in your Org document as \"Google Search\",
  1892. but really it would remove your entire home directory.
  1893. Therefore we advise against setting this variable to nil.
  1894. Just change it to `y-or-n-p' if you want to confirm with a
  1895. single keystroke rather than having to type \"yes\"."
  1896. :group 'org-link-follow
  1897. :type '(choice
  1898. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1899. (const :tag "with y-or-n (faster)" y-or-n-p)
  1900. (const :tag "no confirmation (dangerous)" nil)))
  1901. (put 'org-confirm-shell-link-function
  1902. 'safe-local-variable
  1903. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1904. (defcustom org-confirm-elisp-link-not-regexp ""
  1905. "A regexp to skip confirmation for Elisp links."
  1906. :group 'org-link-follow
  1907. :version "24.1"
  1908. :type 'regexp)
  1909. (defconst org-file-apps-defaults-gnu
  1910. '((remote . emacs)
  1911. (system . mailcap)
  1912. (t . mailcap))
  1913. "Default file applications on a UNIX or GNU/Linux system.
  1914. See `org-file-apps'.")
  1915. (defconst org-file-apps-defaults-macosx
  1916. '((remote . emacs)
  1917. (system . "open %s")
  1918. ("ps.gz" . "gv %s")
  1919. ("eps.gz" . "gv %s")
  1920. ("dvi" . "xdvi %s")
  1921. ("fig" . "xfig %s")
  1922. (t . "open %s"))
  1923. "Default file applications on a MacOS X system.
  1924. The system \"open\" is known as a default, but we use X11 applications
  1925. for some files for which the OS does not have a good default.
  1926. See `org-file-apps'.")
  1927. (defconst org-file-apps-defaults-windowsnt
  1928. (list '(remote . emacs)
  1929. (cons 'system (lambda (file _path)
  1930. (with-no-warnings (w32-shell-execute "open" file))))
  1931. (cons t (lambda (file _path)
  1932. (with-no-warnings (w32-shell-execute "open" file)))))
  1933. "Default file applications on a Windows NT system.
  1934. The system \"open\" is used for most files.
  1935. See `org-file-apps'.")
  1936. (defcustom org-file-apps
  1937. '((auto-mode . emacs)
  1938. ("\\.mm\\'" . default)
  1939. ("\\.x?html?\\'" . default)
  1940. ("\\.pdf\\'" . default))
  1941. "External applications for opening `file:path' items in a document.
  1942. \\<org-mode-map>\
  1943. Org mode uses system defaults for different file types, but
  1944. you can use this variable to set the application for a given file
  1945. extension. The entries in this list are cons cells where the car identifies
  1946. files and the cdr the corresponding command.
  1947. Possible values for the file identifier are:
  1948. \"string\" A string as a file identifier can be interpreted in different
  1949. ways, depending on its contents:
  1950. - Alphanumeric characters only:
  1951. Match links with this file extension.
  1952. Example: (\"pdf\" . \"evince %s\")
  1953. to open PDFs with evince.
  1954. - Regular expression: Match links where the
  1955. filename matches the regexp. If you want to
  1956. use groups here, use shy groups.
  1957. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1958. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1959. to open *.html and *.xhtml with firefox.
  1960. - Regular expression which contains (non-shy) groups:
  1961. Match links where the whole link, including \"::\", and
  1962. anything after that, matches the regexp.
  1963. In a custom command string, %1, %2, etc. are replaced with
  1964. the parts of the link that were matched by the groups.
  1965. For backwards compatibility, if a command string is given
  1966. that does not use any of the group matches, this case is
  1967. handled identically to the second one (i.e. match against
  1968. file name only).
  1969. In a custom function, you can access the group matches with
  1970. \(match-string n link).
  1971. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1972. \"evince -p %1 %s\")
  1973. to open [[file:document.pdf::5]] with evince at page 5.
  1974. `directory' Matches a directory
  1975. `remote' Matches a remote file, accessible through tramp or efs.
  1976. Remote files most likely should be visited through Emacs
  1977. because external applications cannot handle such paths.
  1978. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1979. so all files Emacs knows how to handle. Using this with
  1980. command `emacs' will open most files in Emacs. Beware that this
  1981. will also open html files inside Emacs, unless you add
  1982. \(\"html\" . default) to the list as well.
  1983. `system' The system command to open files, like `open' on Windows
  1984. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1985. that will be selected if you call \\[org-open-at-point] with a double
  1986. \\[universal-argument] \\[universal-argument] prefix.
  1987. t Default for files not matched by any of the other options.
  1988. Possible values for the command are:
  1989. `emacs' The file will be visited by the current Emacs process.
  1990. `default' Use the default application for this file type, which is the
  1991. association for t in the list, most likely in the system-specific
  1992. part. This can be used to overrule an unwanted setting in the
  1993. system-specific variable.
  1994. `system' Use the system command for opening files, like \"open\".
  1995. This command is specified by the entry whose car is `system'.
  1996. Most likely, the system-specific version of this variable
  1997. does define this command, but you can overrule/replace it
  1998. here.
  1999. `mailcap' Use command specified in the mailcaps.
  2000. string A command to be executed by a shell; %s will be replaced
  2001. by the path to the file.
  2002. function A Lisp function, which will be called with two arguments:
  2003. the file path and the original link string, without the
  2004. \"file:\" prefix.
  2005. For more examples, see the system specific constants
  2006. `org-file-apps-defaults-macosx'
  2007. `org-file-apps-defaults-windowsnt'
  2008. `org-file-apps-defaults-gnu'."
  2009. :group 'org-link-follow
  2010. :type '(repeat
  2011. (cons (choice :value ""
  2012. (string :tag "Extension")
  2013. (const :tag "System command to open files" system)
  2014. (const :tag "Default for unrecognized files" t)
  2015. (const :tag "Remote file" remote)
  2016. (const :tag "Links to a directory" directory)
  2017. (const :tag "Any files that have Emacs modes"
  2018. auto-mode))
  2019. (choice :value ""
  2020. (const :tag "Visit with Emacs" emacs)
  2021. (const :tag "Use default" default)
  2022. (const :tag "Use the system command" system)
  2023. (string :tag "Command")
  2024. (function :tag "Function")))))
  2025. (defcustom org-doi-server-url "http://dx.doi.org/"
  2026. "The URL of the DOI server."
  2027. :type 'string
  2028. :version "24.3"
  2029. :group 'org-link-follow)
  2030. (defgroup org-refile nil
  2031. "Options concerning refiling entries in Org-mode."
  2032. :tag "Org Refile"
  2033. :group 'org)
  2034. (defcustom org-directory "~/org"
  2035. "Directory with Org files.
  2036. This is just a default location to look for Org files. There is no need
  2037. at all to put your files into this directory. It is used in the
  2038. following situations:
  2039. 1. When a capture template specifies a target file that is not an
  2040. absolute path. The path will then be interpreted relative to
  2041. `org-directory'
  2042. 2. When the value of variable `org-agenda-files' is a single file, any
  2043. relative paths in this file will be taken as relative to
  2044. `org-directory'."
  2045. :group 'org-refile
  2046. :group 'org-capture
  2047. :type 'directory)
  2048. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2049. "Default target for storing notes.
  2050. Used as a fall back file for org-capture.el, for templates that
  2051. do not specify a target file."
  2052. :group 'org-refile
  2053. :group 'org-capture
  2054. :type 'file)
  2055. (defcustom org-goto-interface 'outline
  2056. "The default interface to be used for `org-goto'.
  2057. Allowed values are:
  2058. outline The interface shows an outline of the relevant file
  2059. and the correct heading is found by moving through
  2060. the outline or by searching with incremental search.
  2061. outline-path-completion Headlines in the current buffer are offered via
  2062. completion. This is the interface also used by
  2063. the refile command."
  2064. :group 'org-refile
  2065. :type '(choice
  2066. (const :tag "Outline" outline)
  2067. (const :tag "Outline-path-completion" outline-path-completion)))
  2068. (defcustom org-goto-max-level 5
  2069. "Maximum target level when running `org-goto' with refile interface."
  2070. :group 'org-refile
  2071. :type 'integer)
  2072. (defcustom org-reverse-note-order nil
  2073. "Non-nil means store new notes at the beginning of a file or entry.
  2074. When nil, new notes will be filed to the end of a file or entry.
  2075. This can also be a list with cons cells of regular expressions that
  2076. are matched against file names, and values."
  2077. :group 'org-capture
  2078. :group 'org-refile
  2079. :type '(choice
  2080. (const :tag "Reverse always" t)
  2081. (const :tag "Reverse never" nil)
  2082. (repeat :tag "By file name regexp"
  2083. (cons regexp boolean))))
  2084. (defcustom org-log-refile nil
  2085. "Information to record when a task is refiled.
  2086. Possible values are:
  2087. nil Don't add anything
  2088. time Add a time stamp to the task
  2089. note Prompt for a note and add it with template `org-log-note-headings'
  2090. This option can also be set with on a per-file-basis with
  2091. #+STARTUP: nologrefile
  2092. #+STARTUP: logrefile
  2093. #+STARTUP: lognoterefile
  2094. You can have local logging settings for a subtree by setting the LOGGING
  2095. property to one or more of these keywords.
  2096. When bulk-refiling from the agenda, the value `note' is forbidden and
  2097. will temporarily be changed to `time'."
  2098. :group 'org-refile
  2099. :group 'org-progress
  2100. :version "24.1"
  2101. :type '(choice
  2102. (const :tag "No logging" nil)
  2103. (const :tag "Record timestamp" time)
  2104. (const :tag "Record timestamp with note." note)))
  2105. (defcustom org-refile-targets nil
  2106. "Targets for refiling entries with \\[org-refile].
  2107. This is a list of cons cells. Each cell contains:
  2108. - a specification of the files to be considered, either a list of files,
  2109. or a symbol whose function or variable value will be used to retrieve
  2110. a file name or a list of file names. If you use `org-agenda-files' for
  2111. that, all agenda files will be scanned for targets. Nil means consider
  2112. headings in the current buffer.
  2113. - A specification of how to find candidate refile targets. This may be
  2114. any of:
  2115. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2116. This tag has to be present in all target headlines, inheritance will
  2117. not be considered.
  2118. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2119. todo keyword.
  2120. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2121. headlines that are refiling targets.
  2122. - a cons cell (:level . N). Any headline of level N is considered a target.
  2123. Note that, when `org-odd-levels-only' is set, level corresponds to
  2124. order in hierarchy, not to the number of stars.
  2125. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2126. Note that, when `org-odd-levels-only' is set, level corresponds to
  2127. order in hierarchy, not to the number of stars.
  2128. Each element of this list generates a set of possible targets.
  2129. The union of these sets is presented (with completion) to
  2130. the user by `org-refile'.
  2131. You can set the variable `org-refile-target-verify-function' to a function
  2132. to verify each headline found by the simple criteria above.
  2133. When this variable is nil, all top-level headlines in the current buffer
  2134. are used, equivalent to the value `((nil . (:level . 1))'."
  2135. :group 'org-refile
  2136. :type '(repeat
  2137. (cons
  2138. (choice :value org-agenda-files
  2139. (const :tag "All agenda files" org-agenda-files)
  2140. (const :tag "Current buffer" nil)
  2141. (function) (variable) (file))
  2142. (choice :tag "Identify target headline by"
  2143. (cons :tag "Specific tag" (const :value :tag) (string))
  2144. (cons :tag "TODO keyword" (const :value :todo) (string))
  2145. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2146. (cons :tag "Level number" (const :value :level) (integer))
  2147. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2148. (defcustom org-refile-target-verify-function nil
  2149. "Function to verify if the headline at point should be a refile target.
  2150. The function will be called without arguments, with point at the
  2151. beginning of the headline. It should return t and leave point
  2152. where it is if the headline is a valid target for refiling.
  2153. If the target should not be selected, the function must return nil.
  2154. In addition to this, it may move point to a place from where the search
  2155. should be continued. For example, the function may decide that the entire
  2156. subtree of the current entry should be excluded and move point to the end
  2157. of the subtree."
  2158. :group 'org-refile
  2159. :type '(choice
  2160. (const nil)
  2161. (function)))
  2162. (defcustom org-refile-use-cache nil
  2163. "Non-nil means cache refile targets to speed up the process.
  2164. \\<org-mode-map>\
  2165. The cache for a particular file will be updated automatically when
  2166. the buffer has been killed, or when any of the marker used for flagging
  2167. refile targets no longer points at a live buffer.
  2168. If you have added new entries to a buffer that might themselves be targets,
  2169. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2170. if you find that easier, \
  2171. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2172. \\[org-refile]'."
  2173. :group 'org-refile
  2174. :version "24.1"
  2175. :type 'boolean)
  2176. (defcustom org-refile-use-outline-path nil
  2177. "Non-nil means provide refile targets as paths.
  2178. So a level 3 headline will be available as level1/level2/level3.
  2179. When the value is `file', also include the file name (without directory)
  2180. into the path. In this case, you can also stop the completion after
  2181. the file name, to get entries inserted as top level in the file.
  2182. When `full-file-path', include the full file path."
  2183. :group 'org-refile
  2184. :type '(choice
  2185. (const :tag "Not" nil)
  2186. (const :tag "Yes" t)
  2187. (const :tag "Start with file name" file)
  2188. (const :tag "Start with full file path" full-file-path)))
  2189. (defcustom org-outline-path-complete-in-steps t
  2190. "Non-nil means complete the outline path in hierarchical steps.
  2191. When Org uses the refile interface to select an outline path (see
  2192. `org-refile-use-outline-path'), the completion of the path can be
  2193. done in a single go, or it can be done in steps down the headline
  2194. hierarchy. Going in steps is probably the best if you do not use
  2195. a special completion package like `ido' or `icicles'. However,
  2196. when using these packages, going in one step can be very fast,
  2197. while still showing the whole path to the entry."
  2198. :group 'org-refile
  2199. :type 'boolean)
  2200. (defcustom org-refile-allow-creating-parent-nodes nil
  2201. "Non-nil means allow the creation of new nodes as refile targets.
  2202. New nodes are then created by adding \"/new node name\" to the completion
  2203. of an existing node. When the value of this variable is `confirm',
  2204. new node creation must be confirmed by the user (recommended).
  2205. When nil, the completion must match an existing entry.
  2206. Note that, if the new heading is not seen by the criteria
  2207. listed in `org-refile-targets', multiple instances of the same
  2208. heading would be created by trying again to file under the new
  2209. heading."
  2210. :group 'org-refile
  2211. :type '(choice
  2212. (const :tag "Never" nil)
  2213. (const :tag "Always" t)
  2214. (const :tag "Prompt for confirmation" confirm)))
  2215. (defcustom org-refile-active-region-within-subtree nil
  2216. "Non-nil means also refile active region within a subtree.
  2217. By default `org-refile' doesn't allow refiling regions if they
  2218. don't contain a set of subtrees, but it might be convenient to
  2219. do so sometimes: in that case, the first line of the region is
  2220. converted to a headline before refiling."
  2221. :group 'org-refile
  2222. :version "24.1"
  2223. :type 'boolean)
  2224. (defgroup org-todo nil
  2225. "Options concerning TODO items in Org-mode."
  2226. :tag "Org TODO"
  2227. :group 'org)
  2228. (defgroup org-progress nil
  2229. "Options concerning Progress logging in Org-mode."
  2230. :tag "Org Progress"
  2231. :group 'org-time)
  2232. (defvar org-todo-interpretation-widgets
  2233. '((:tag "Sequence (cycling hits every state)" sequence)
  2234. (:tag "Type (cycling directly to DONE)" type))
  2235. "The available interpretation symbols for customizing `org-todo-keywords'.
  2236. Interested libraries should add to this list.")
  2237. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2238. "List of TODO entry keyword sequences and their interpretation.
  2239. \\<org-mode-map>This is a list of sequences.
  2240. Each sequence starts with a symbol, either `sequence' or `type',
  2241. indicating if the keywords should be interpreted as a sequence of
  2242. action steps, or as different types of TODO items. The first
  2243. keywords are states requiring action - these states will select a headline
  2244. for inclusion into the global TODO list Org produces. If one of the
  2245. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2246. signify that no further action is necessary. If \"|\" is not found,
  2247. the last keyword is treated as the only DONE state of the sequence.
  2248. The command \\[org-todo] cycles an entry through these states, and one
  2249. additional state where no keyword is present. For details about this
  2250. cycling, see the manual.
  2251. TODO keywords and interpretation can also be set on a per-file basis with
  2252. the special #+SEQ_TODO and #+TYP_TODO lines.
  2253. Each keyword can optionally specify a character for fast state selection
  2254. \(in combination with the variable `org-use-fast-todo-selection')
  2255. and specifiers for state change logging, using the same syntax that
  2256. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2257. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2258. indicates to record a time stamp each time this state is selected.
  2259. Each keyword may also specify if a timestamp or a note should be
  2260. recorded when entering or leaving the state, by adding additional
  2261. characters in the parenthesis after the keyword. This looks like this:
  2262. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2263. record only the time of the state change. With X and Y being either
  2264. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2265. Y when leaving the state if and only if the *target* state does not
  2266. define X. You may omit any of the fast-selection key or X or /Y,
  2267. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2268. For backward compatibility, this variable may also be just a list
  2269. of keywords. In this case the interpretation (sequence or type) will be
  2270. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2271. :group 'org-todo
  2272. :group 'org-keywords
  2273. :type '(choice
  2274. (repeat :tag "Old syntax, just keywords"
  2275. (string :tag "Keyword"))
  2276. (repeat :tag "New syntax"
  2277. (cons
  2278. (choice
  2279. :tag "Interpretation"
  2280. ;;Quick and dirty way to see
  2281. ;;`org-todo-interpretations'. This takes the
  2282. ;;place of item arguments
  2283. :convert-widget
  2284. (lambda (widget)
  2285. (widget-put widget
  2286. :args (mapcar
  2287. (lambda (x)
  2288. (widget-convert
  2289. (cons 'const x)))
  2290. org-todo-interpretation-widgets))
  2291. widget))
  2292. (repeat
  2293. (string :tag "Keyword"))))))
  2294. (defvar-local org-todo-keywords-1 nil
  2295. "All TODO and DONE keywords active in a buffer.")
  2296. (defvar org-todo-keywords-for-agenda nil)
  2297. (defvar org-done-keywords-for-agenda nil)
  2298. (defvar org-todo-keyword-alist-for-agenda nil)
  2299. (defvar org-tag-alist-for-agenda nil
  2300. "Alist of all tags from all agenda files.")
  2301. (defvar org-tag-groups-alist-for-agenda nil
  2302. "Alist of all groups tags from all current agenda files.")
  2303. (defvar-local org-tag-groups-alist nil)
  2304. (defvar org-agenda-contributing-files nil)
  2305. (defvar-local org-current-tag-alist nil
  2306. "Alist of all tag groups in current buffer.
  2307. This variable takes into consideration `org-tag-alist',
  2308. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2309. (defvar-local org-not-done-keywords nil)
  2310. (defvar-local org-done-keywords nil)
  2311. (defvar-local org-todo-heads nil)
  2312. (defvar-local org-todo-sets nil)
  2313. (defvar-local org-todo-log-states nil)
  2314. (defvar-local org-todo-kwd-alist nil)
  2315. (defvar-local org-todo-key-alist nil)
  2316. (defvar-local org-todo-key-trigger nil)
  2317. (defcustom org-todo-interpretation 'sequence
  2318. "Controls how TODO keywords are interpreted.
  2319. This variable is in principle obsolete and is only used for
  2320. backward compatibility, if the interpretation of todo keywords is
  2321. not given already in `org-todo-keywords'. See that variable for
  2322. more information."
  2323. :group 'org-todo
  2324. :group 'org-keywords
  2325. :type '(choice (const sequence)
  2326. (const type)))
  2327. (defcustom org-use-fast-todo-selection t
  2328. "\\<org-mode-map>\
  2329. Non-nil means use the fast todo selection scheme with \\[org-todo].
  2330. This variable describes if and under what circumstances the cycling
  2331. mechanism for TODO keywords will be replaced by a single-key, direct
  2332. selection scheme.
  2333. When nil, fast selection is never used.
  2334. When the symbol `prefix', it will be used when `org-todo' is called
  2335. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2336. in an Org buffer, and
  2337. `\\[universal-argument] t' in an agenda buffer.
  2338. When t, fast selection is used by default. In this case, the prefix
  2339. argument forces cycling instead.
  2340. In all cases, the special interface is only used if access keys have
  2341. actually been assigned by the user, i.e. if keywords in the configuration
  2342. are followed by a letter in parenthesis, like TODO(t)."
  2343. :group 'org-todo
  2344. :type '(choice
  2345. (const :tag "Never" nil)
  2346. (const :tag "By default" t)
  2347. (const :tag "Only with C-u C-c C-t" prefix)))
  2348. (defcustom org-provide-todo-statistics t
  2349. "Non-nil means update todo statistics after insert and toggle.
  2350. ALL-HEADLINES means update todo statistics by including headlines
  2351. with no TODO keyword as well, counting them as not done.
  2352. A list of TODO keywords means the same, but skip keywords that are
  2353. not in this list.
  2354. When set to a list of two lists, the first list contains keywords
  2355. to consider as TODO keywords, the second list contains keywords
  2356. to consider as DONE keywords.
  2357. When this is set, todo statistics is updated in the parent of the
  2358. current entry each time a todo state is changed."
  2359. :group 'org-todo
  2360. :type '(choice
  2361. (const :tag "Yes, only for TODO entries" t)
  2362. (const :tag "Yes, including all entries" all-headlines)
  2363. (repeat :tag "Yes, for TODOs in this list"
  2364. (string :tag "TODO keyword"))
  2365. (list :tag "Yes, for TODOs and DONEs in these lists"
  2366. (repeat (string :tag "TODO keyword"))
  2367. (repeat (string :tag "DONE keyword")))
  2368. (other :tag "No TODO statistics" nil)))
  2369. (defcustom org-hierarchical-todo-statistics t
  2370. "Non-nil means TODO statistics covers just direct children.
  2371. When nil, all entries in the subtree are considered.
  2372. This has only an effect if `org-provide-todo-statistics' is set.
  2373. To set this to nil for only a single subtree, use a COOKIE_DATA
  2374. property and include the word \"recursive\" into the value."
  2375. :group 'org-todo
  2376. :type 'boolean)
  2377. (defcustom org-after-todo-state-change-hook nil
  2378. "Hook which is run after the state of a TODO item was changed.
  2379. The new state (a string with a TODO keyword, or nil) is available in the
  2380. Lisp variable `org-state'."
  2381. :group 'org-todo
  2382. :type 'hook)
  2383. (defvar org-blocker-hook nil
  2384. "Hook for functions that are allowed to block a state change.
  2385. Functions in this hook should not modify the buffer.
  2386. Each function gets as its single argument a property list,
  2387. see `org-trigger-hook' for more information about this list.
  2388. If any of the functions in this hook returns nil, the state change
  2389. is blocked.")
  2390. (defvar org-trigger-hook nil
  2391. "Hook for functions that are triggered by a state change.
  2392. Each function gets as its single argument a property list with at
  2393. least the following elements:
  2394. (:type type-of-change :position pos-at-entry-start
  2395. :from old-state :to new-state)
  2396. Depending on the type, more properties may be present.
  2397. This mechanism is currently implemented for:
  2398. TODO state changes
  2399. ------------------
  2400. :type todo-state-change
  2401. :from previous state (keyword as a string), or nil, or a symbol
  2402. `todo' or `done', to indicate the general type of state.
  2403. :to new state, like in :from")
  2404. (defcustom org-enforce-todo-dependencies nil
  2405. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2406. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2407. be blocked if any prior sibling is not yet done.
  2408. Finally, if the parent is blocked because of ordered siblings of its own,
  2409. the child will also be blocked."
  2410. :set (lambda (var val)
  2411. (set var val)
  2412. (if val
  2413. (add-hook 'org-blocker-hook
  2414. 'org-block-todo-from-children-or-siblings-or-parent)
  2415. (remove-hook 'org-blocker-hook
  2416. 'org-block-todo-from-children-or-siblings-or-parent)))
  2417. :group 'org-todo
  2418. :type 'boolean)
  2419. (defcustom org-enforce-todo-checkbox-dependencies nil
  2420. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2421. When this is nil, checkboxes have no influence on switching TODO states.
  2422. When non-nil, you first need to check off all check boxes before the TODO
  2423. entry can be switched to DONE.
  2424. This variable needs to be set before org.el is loaded, and you need to
  2425. restart Emacs after a change to make the change effective. The only way
  2426. to change is while Emacs is running is through the customize interface."
  2427. :set (lambda (var val)
  2428. (set var val)
  2429. (if val
  2430. (add-hook 'org-blocker-hook
  2431. 'org-block-todo-from-checkboxes)
  2432. (remove-hook 'org-blocker-hook
  2433. 'org-block-todo-from-checkboxes)))
  2434. :group 'org-todo
  2435. :type 'boolean)
  2436. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2437. "Non-nil means inserting a TODO heading is treated as state change.
  2438. So when the command \\[org-insert-todo-heading] is used, state change
  2439. logging will apply if appropriate. When nil, the new TODO item will
  2440. be inserted directly, and no logging will take place."
  2441. :group 'org-todo
  2442. :type 'boolean)
  2443. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2444. "Non-nil means switching TODO states with S-cursor counts as state change.
  2445. This is the default behavior. However, setting this to nil allows a
  2446. convenient way to select a TODO state and bypass any logging associated
  2447. with that."
  2448. :group 'org-todo
  2449. :type 'boolean)
  2450. (defcustom org-todo-state-tags-triggers nil
  2451. "Tag changes that should be triggered by TODO state changes.
  2452. This is a list. Each entry is
  2453. (state-change (tag . flag) .......)
  2454. State-change can be a string with a state, and empty string to indicate the
  2455. state that has no TODO keyword, or it can be one of the symbols `todo'
  2456. or `done', meaning any not-done or done state, respectively."
  2457. :group 'org-todo
  2458. :group 'org-tags
  2459. :type '(repeat
  2460. (cons (choice :tag "When changing to"
  2461. (const :tag "Not-done state" todo)
  2462. (const :tag "Done state" done)
  2463. (string :tag "State"))
  2464. (repeat
  2465. (cons :tag "Tag action"
  2466. (string :tag "Tag")
  2467. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2468. (defcustom org-log-done nil
  2469. "Information to record when a task moves to the DONE state.
  2470. Possible values are:
  2471. nil Don't add anything, just change the keyword
  2472. time Add a time stamp to the task
  2473. note Prompt for a note and add it with template `org-log-note-headings'
  2474. This option can also be set with on a per-file-basis with
  2475. #+STARTUP: nologdone
  2476. #+STARTUP: logdone
  2477. #+STARTUP: lognotedone
  2478. You can have local logging settings for a subtree by setting the LOGGING
  2479. property to one or more of these keywords."
  2480. :group 'org-todo
  2481. :group 'org-progress
  2482. :type '(choice
  2483. (const :tag "No logging" nil)
  2484. (const :tag "Record CLOSED timestamp" time)
  2485. (const :tag "Record CLOSED timestamp with note." note)))
  2486. ;; Normalize old uses of org-log-done.
  2487. (cond
  2488. ((eq org-log-done t) (setq org-log-done 'time))
  2489. ((and (listp org-log-done) (memq 'done org-log-done))
  2490. (setq org-log-done 'note)))
  2491. (defcustom org-log-reschedule nil
  2492. "Information to record when the scheduling date of a tasks is modified.
  2493. Possible values are:
  2494. nil Don't add anything, just change the date
  2495. time Add a time stamp to the task
  2496. note Prompt for a note and add it with template `org-log-note-headings'
  2497. This option can also be set with on a per-file-basis with
  2498. #+STARTUP: nologreschedule
  2499. #+STARTUP: logreschedule
  2500. #+STARTUP: lognotereschedule"
  2501. :group 'org-todo
  2502. :group 'org-progress
  2503. :type '(choice
  2504. (const :tag "No logging" nil)
  2505. (const :tag "Record timestamp" time)
  2506. (const :tag "Record timestamp with note." note)))
  2507. (defcustom org-log-redeadline nil
  2508. "Information to record when the deadline date of a tasks is modified.
  2509. Possible values are:
  2510. nil Don't add anything, just change the date
  2511. time Add a time stamp to the task
  2512. note Prompt for a note and add it with template `org-log-note-headings'
  2513. This option can also be set with on a per-file-basis with
  2514. #+STARTUP: nologredeadline
  2515. #+STARTUP: logredeadline
  2516. #+STARTUP: lognoteredeadline
  2517. You can have local logging settings for a subtree by setting the LOGGING
  2518. property to one or more of these keywords."
  2519. :group 'org-todo
  2520. :group 'org-progress
  2521. :type '(choice
  2522. (const :tag "No logging" nil)
  2523. (const :tag "Record timestamp" time)
  2524. (const :tag "Record timestamp with note." note)))
  2525. (defcustom org-log-note-clock-out nil
  2526. "Non-nil means record a note when clocking out of an item.
  2527. This can also be configured on a per-file basis by adding one of
  2528. the following lines anywhere in the buffer:
  2529. #+STARTUP: lognoteclock-out
  2530. #+STARTUP: nolognoteclock-out"
  2531. :group 'org-todo
  2532. :group 'org-progress
  2533. :type 'boolean)
  2534. (defcustom org-log-done-with-time t
  2535. "Non-nil means the CLOSED time stamp will contain date and time.
  2536. When nil, only the date will be recorded."
  2537. :group 'org-progress
  2538. :type 'boolean)
  2539. (defcustom org-log-note-headings
  2540. '((done . "CLOSING NOTE %t")
  2541. (state . "State %-12s from %-12S %t")
  2542. (note . "Note taken on %t")
  2543. (reschedule . "Rescheduled from %S on %t")
  2544. (delschedule . "Not scheduled, was %S on %t")
  2545. (redeadline . "New deadline from %S on %t")
  2546. (deldeadline . "Removed deadline, was %S on %t")
  2547. (refile . "Refiled on %t")
  2548. (clock-out . ""))
  2549. "Headings for notes added to entries.
  2550. The value is an alist, with the car being a symbol indicating the
  2551. note context, and the cdr is the heading to be used. The heading
  2552. may also be the empty string. The following placeholders can be
  2553. used:
  2554. %t a time stamp.
  2555. %T an active time stamp instead the default inactive one
  2556. %d a short-format time stamp.
  2557. %D an active short-format time stamp.
  2558. %s the new TODO state or time stamp (inactive), in double quotes.
  2559. %S the old TODO state or time stamp (inactive), in double quotes.
  2560. %u the user name.
  2561. %U full user name.
  2562. In fact, it is not a good idea to change the `state' entry,
  2563. because Agenda Log mode depends on the format of these entries."
  2564. :group 'org-todo
  2565. :group 'org-progress
  2566. :type '(list :greedy t
  2567. (cons (const :tag "Heading when closing an item" done) string)
  2568. (cons (const :tag
  2569. "Heading when changing todo state (todo sequence only)"
  2570. state) string)
  2571. (cons (const :tag "Heading when just taking a note" note) string)
  2572. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2573. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2574. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2575. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2576. (cons (const :tag "Heading when refiling" refile) string)
  2577. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2578. (unless (assq 'note org-log-note-headings)
  2579. (push '(note . "%t") org-log-note-headings))
  2580. (defcustom org-log-into-drawer nil
  2581. "Non-nil means insert state change notes and time stamps into a drawer.
  2582. When nil, state changes notes will be inserted after the headline and
  2583. any scheduling and clock lines, but not inside a drawer.
  2584. The value of this variable should be the name of the drawer to use.
  2585. LOGBOOK is proposed as the default drawer for this purpose, you can
  2586. also set this to a string to define the drawer of your choice.
  2587. A value of t is also allowed, representing \"LOGBOOK\".
  2588. A value of t or nil can also be set with on a per-file-basis with
  2589. #+STARTUP: logdrawer
  2590. #+STARTUP: nologdrawer
  2591. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2592. will be ignored.
  2593. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2594. a subtree.
  2595. Do not check directly this variable in a Lisp program. Call
  2596. function `org-log-into-drawer' instead."
  2597. :group 'org-todo
  2598. :group 'org-progress
  2599. :type '(choice
  2600. (const :tag "Not into a drawer" nil)
  2601. (const :tag "LOGBOOK" t)
  2602. (string :tag "Other")))
  2603. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2604. (defun org-log-into-drawer ()
  2605. "Name of the log drawer, as a string, or nil.
  2606. This is the value of `org-log-into-drawer'. However, if the
  2607. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2608. be used instead of the default value."
  2609. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2610. (cond ((equal p "nil") nil)
  2611. ((equal p "t") "LOGBOOK")
  2612. ((stringp p) p)
  2613. (p "LOGBOOK")
  2614. ((stringp org-log-into-drawer) org-log-into-drawer)
  2615. (org-log-into-drawer "LOGBOOK"))))
  2616. (defcustom org-log-state-notes-insert-after-drawers nil
  2617. "Non-nil means insert state change notes after any drawers in entry.
  2618. Only the drawers that *immediately* follow the headline and the
  2619. deadline/scheduled line are skipped.
  2620. When nil, insert notes right after the heading and perhaps the line
  2621. with deadline/scheduling if present.
  2622. This variable will have no effect if `org-log-into-drawer' is
  2623. set."
  2624. :group 'org-todo
  2625. :group 'org-progress
  2626. :type 'boolean)
  2627. (defcustom org-log-states-order-reversed t
  2628. "Non-nil means the latest state note will be directly after heading.
  2629. When nil, the state change notes will be ordered according to time.
  2630. This option can also be set with on a per-file-basis with
  2631. #+STARTUP: logstatesreversed
  2632. #+STARTUP: nologstatesreversed"
  2633. :group 'org-todo
  2634. :group 'org-progress
  2635. :type 'boolean)
  2636. (defcustom org-todo-repeat-to-state nil
  2637. "The TODO state to which a repeater should return the repeating task.
  2638. By default this is the first task in a TODO sequence, or the previous state
  2639. in a TODO_TYP set. But you can specify another task here.
  2640. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2641. :group 'org-todo
  2642. :version "24.1"
  2643. :type '(choice (const :tag "Head of sequence" nil)
  2644. (string :tag "Specific state")))
  2645. (defcustom org-log-repeat 'time
  2646. "Non-nil means record moving through the DONE state when triggering repeat.
  2647. An auto-repeating task is immediately switched back to TODO when
  2648. marked DONE. If you are not logging state changes (by adding \"@\"
  2649. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2650. record a closing note, there will be no record of the task moving
  2651. through DONE. This variable forces taking a note anyway.
  2652. nil Don't force a record
  2653. time Record a time stamp
  2654. note Prompt for a note and add it with template `org-log-note-headings'
  2655. This option can also be set with on a per-file-basis with
  2656. #+STARTUP: nologrepeat
  2657. #+STARTUP: logrepeat
  2658. #+STARTUP: lognoterepeat
  2659. You can have local logging settings for a subtree by setting the LOGGING
  2660. property to one or more of these keywords."
  2661. :group 'org-todo
  2662. :group 'org-progress
  2663. :type '(choice
  2664. (const :tag "Don't force a record" nil)
  2665. (const :tag "Force recording the DONE state" time)
  2666. (const :tag "Force recording a note with the DONE state" note)))
  2667. (defgroup org-priorities nil
  2668. "Priorities in Org-mode."
  2669. :tag "Org Priorities"
  2670. :group 'org-todo)
  2671. (defcustom org-enable-priority-commands t
  2672. "Non-nil means priority commands are active.
  2673. When nil, these commands will be disabled, so that you never accidentally
  2674. set a priority."
  2675. :group 'org-priorities
  2676. :type 'boolean)
  2677. (defcustom org-highest-priority ?A
  2678. "The highest priority of TODO items. A character like ?A, ?B etc.
  2679. Must have a smaller ASCII number than `org-lowest-priority'."
  2680. :group 'org-priorities
  2681. :type 'character)
  2682. (defcustom org-lowest-priority ?C
  2683. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2684. Must have a larger ASCII number than `org-highest-priority'."
  2685. :group 'org-priorities
  2686. :type 'character)
  2687. (defcustom org-default-priority ?B
  2688. "The default priority of TODO items.
  2689. This is the priority an item gets if no explicit priority is given.
  2690. When starting to cycle on an empty priority the first step in the cycle
  2691. depends on `org-priority-start-cycle-with-default'. The resulting first
  2692. step priority must not exceed the range from `org-highest-priority' to
  2693. `org-lowest-priority' which means that `org-default-priority' has to be
  2694. in this range exclusive or inclusive the range boundaries. Else the
  2695. first step refuses to set the default and the second will fall back
  2696. to (depending on the command used) the highest or lowest priority."
  2697. :group 'org-priorities
  2698. :type 'character)
  2699. (defcustom org-priority-start-cycle-with-default t
  2700. "Non-nil means start with default priority when starting to cycle.
  2701. When this is nil, the first step in the cycle will be (depending on the
  2702. command used) one higher or lower than the default priority.
  2703. See also `org-default-priority'."
  2704. :group 'org-priorities
  2705. :type 'boolean)
  2706. (defcustom org-get-priority-function nil
  2707. "Function to extract the priority from a string.
  2708. The string is normally the headline. If this is nil Org computes the
  2709. priority from the priority cookie like [#A] in the headline. It returns
  2710. an integer, increasing by 1000 for each priority level.
  2711. The user can set a different function here, which should take a string
  2712. as an argument and return the numeric priority."
  2713. :group 'org-priorities
  2714. :version "24.1"
  2715. :type '(choice
  2716. (const nil)
  2717. (function)))
  2718. (defgroup org-time nil
  2719. "Options concerning time stamps and deadlines in Org-mode."
  2720. :tag "Org Time"
  2721. :group 'org)
  2722. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2723. "Number of minutes to round time stamps to.
  2724. \\<org-mode-map>\
  2725. These are two values, the first applies when first creating a time stamp.
  2726. The second applies when changing it with the commands `S-up' and `S-down'.
  2727. When changing the time stamp, this means that it will change in steps
  2728. of N minutes, as given by the second value.
  2729. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2730. numbers should be factors of 60, so for example 5, 10, 15.
  2731. When this is larger than 1, you can still force an exact time stamp by using
  2732. a double prefix argument to a time stamp command like \
  2733. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2734. and by using a prefix arg to `S-up/down' to specify the exact number
  2735. of minutes to shift."
  2736. :group 'org-time
  2737. :get (lambda (var) ; Make sure both elements are there
  2738. (if (integerp (default-value var))
  2739. (list (default-value var) 5)
  2740. (default-value var)))
  2741. :type '(list
  2742. (integer :tag "when inserting times")
  2743. (integer :tag "when modifying times")))
  2744. ;; Normalize old customizations of this variable.
  2745. (when (integerp org-time-stamp-rounding-minutes)
  2746. (setq org-time-stamp-rounding-minutes
  2747. (list org-time-stamp-rounding-minutes
  2748. org-time-stamp-rounding-minutes)))
  2749. (defcustom org-display-custom-times nil
  2750. "Non-nil means overlay custom formats over all time stamps.
  2751. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2752. To turn this on on a per-file basis, insert anywhere in the file:
  2753. #+STARTUP: customtime"
  2754. :group 'org-time
  2755. :set 'set-default
  2756. :type 'sexp)
  2757. (make-variable-buffer-local 'org-display-custom-times)
  2758. (defcustom org-time-stamp-custom-formats
  2759. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2760. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2761. These are overlaid over the default ISO format if the variable
  2762. `org-display-custom-times' is set. Time like %H:%M should be at the
  2763. end of the second format. The custom formats are also honored by export
  2764. commands, if custom time display is turned on at the time of export."
  2765. :group 'org-time
  2766. :type 'sexp)
  2767. (defun org-time-stamp-format (&optional long inactive)
  2768. "Get the right format for a time string."
  2769. (let ((f (if long (cdr org-time-stamp-formats)
  2770. (car org-time-stamp-formats))))
  2771. (if inactive
  2772. (concat "[" (substring f 1 -1) "]")
  2773. f)))
  2774. (defcustom org-time-clocksum-format
  2775. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2776. "The format string used when creating CLOCKSUM lines.
  2777. This is also used when Org mode generates a time duration.
  2778. The value can be a single format string containing two
  2779. %-sequences, which will be filled with the number of hours and
  2780. minutes in that order.
  2781. Alternatively, the value can be a plist associating any of the
  2782. keys :years, :months, :weeks, :days, :hours or :minutes with
  2783. format strings. The time duration is formatted using only the
  2784. time components that are needed and concatenating the results.
  2785. If a time unit in absent, it falls back to the next smallest
  2786. unit.
  2787. The keys :require-years, :require-months, :require-days,
  2788. :require-weeks, :require-hours, :require-minutes are also
  2789. meaningful. A non-nil value for these keys indicates that the
  2790. corresponding time component should always be included, even if
  2791. its value is 0.
  2792. For example,
  2793. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2794. :require-minutes t)
  2795. means durations longer than a day will be expressed in days,
  2796. hours and minutes, and durations less than a day will always be
  2797. expressed in hours and minutes (even for durations less than an
  2798. hour).
  2799. The value
  2800. (:days \"%dd\" :minutes \"%dm\")
  2801. means durations longer than a day will be expressed in days and
  2802. minutes, and durations less than a day will be expressed entirely
  2803. in minutes (even for durations longer than an hour)."
  2804. :group 'org-time
  2805. :group 'org-clock
  2806. :version "24.4"
  2807. :package-version '(Org . "8.0")
  2808. :type '(choice (string :tag "Format string")
  2809. (set :tag "Plist"
  2810. (group :inline t (const :tag "Years" :years)
  2811. (string :tag "Format string"))
  2812. (group :inline t
  2813. (const :tag "Always show years" :require-years)
  2814. (const t))
  2815. (group :inline t (const :tag "Months" :months)
  2816. (string :tag "Format string"))
  2817. (group :inline t
  2818. (const :tag "Always show months" :require-months)
  2819. (const t))
  2820. (group :inline t (const :tag "Weeks" :weeks)
  2821. (string :tag "Format string"))
  2822. (group :inline t
  2823. (const :tag "Always show weeks" :require-weeks)
  2824. (const t))
  2825. (group :inline t (const :tag "Days" :days)
  2826. (string :tag "Format string"))
  2827. (group :inline t
  2828. (const :tag "Always show days" :require-days)
  2829. (const t))
  2830. (group :inline t (const :tag "Hours" :hours)
  2831. (string :tag "Format string"))
  2832. (group :inline t
  2833. (const :tag "Always show hours" :require-hours)
  2834. (const t))
  2835. (group :inline t (const :tag "Minutes" :minutes)
  2836. (string :tag "Format string"))
  2837. (group :inline t
  2838. (const :tag "Always show minutes" :require-minutes)
  2839. (const t)))))
  2840. (defcustom org-time-clocksum-use-fractional nil
  2841. "When non-nil, \\[org-clock-display] uses fractional times.
  2842. See `org-time-clocksum-format' for more on time clock formats."
  2843. :group 'org-time
  2844. :group 'org-clock
  2845. :version "24.3"
  2846. :type 'boolean)
  2847. (defcustom org-time-clocksum-use-effort-durations nil
  2848. "When non-nil, \\[org-clock-display] uses effort durations.
  2849. E.g. by default, one day is considered to be a 8 hours effort,
  2850. so a task that has been clocked for 16 hours will be displayed
  2851. as during 2 days in the clock display or in the clocktable.
  2852. See `org-effort-durations' on how to set effort durations
  2853. and `org-time-clocksum-format' for more on time clock formats."
  2854. :group 'org-time
  2855. :group 'org-clock
  2856. :version "24.4"
  2857. :package-version '(Org . "8.0")
  2858. :type 'boolean)
  2859. (defcustom org-time-clocksum-fractional-format "%.2f"
  2860. "The format string used when creating CLOCKSUM lines,
  2861. or when Org mode generates a time duration, if
  2862. `org-time-clocksum-use-fractional' is enabled.
  2863. The value can be a single format string containing one
  2864. %-sequence, which will be filled with the number of hours as
  2865. a float.
  2866. Alternatively, the value can be a plist associating any of the
  2867. keys :years, :months, :weeks, :days, :hours or :minutes with
  2868. a format string. The time duration is formatted using the
  2869. largest time unit which gives a non-zero integer part. If all
  2870. specified formats have zero integer part, the smallest time unit
  2871. is used."
  2872. :group 'org-time
  2873. :type '(choice (string :tag "Format string")
  2874. (set (group :inline t (const :tag "Years" :years)
  2875. (string :tag "Format string"))
  2876. (group :inline t (const :tag "Months" :months)
  2877. (string :tag "Format string"))
  2878. (group :inline t (const :tag "Weeks" :weeks)
  2879. (string :tag "Format string"))
  2880. (group :inline t (const :tag "Days" :days)
  2881. (string :tag "Format string"))
  2882. (group :inline t (const :tag "Hours" :hours)
  2883. (string :tag "Format string"))
  2884. (group :inline t (const :tag "Minutes" :minutes)
  2885. (string :tag "Format string")))))
  2886. (defcustom org-deadline-warning-days 14
  2887. "Number of days before expiration during which a deadline becomes active.
  2888. This variable governs the display in sparse trees and in the agenda.
  2889. When 0 or negative, it means use this number (the absolute value of it)
  2890. even if a deadline has a different individual lead time specified.
  2891. Custom commands can set this variable in the options section."
  2892. :group 'org-time
  2893. :group 'org-agenda-daily/weekly
  2894. :type 'integer)
  2895. (defcustom org-scheduled-delay-days 0
  2896. "Number of days before a scheduled item becomes active.
  2897. This variable governs the display in sparse trees and in the agenda.
  2898. The default value (i.e. 0) means: don't delay scheduled item.
  2899. When negative, it means use this number (the absolute value of it)
  2900. even if a scheduled item has a different individual delay time
  2901. specified.
  2902. Custom commands can set this variable in the options section."
  2903. :group 'org-time
  2904. :group 'org-agenda-daily/weekly
  2905. :version "24.4"
  2906. :package-version '(Org . "8.0")
  2907. :type 'integer)
  2908. (defcustom org-read-date-prefer-future t
  2909. "Non-nil means assume future for incomplete date input from user.
  2910. This affects the following situations:
  2911. 1. The user gives a month but not a year.
  2912. For example, if it is April and you enter \"feb 2\", this will be read
  2913. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2914. 2. The user gives a day, but no month.
  2915. For example, if today is the 15th, and you enter \"3\", Org will read
  2916. this as the third of *next* month. However, if you enter \"17\",
  2917. it will be considered as *this* month.
  2918. If you set this variable to the symbol `time', then also the following
  2919. will work:
  2920. 3. If the user gives a time.
  2921. If the time is before now, it will be interpreted as tomorrow.
  2922. Currently none of this works for ISO week specifications.
  2923. When this option is nil, the current day, month and year will always be
  2924. used as defaults.
  2925. See also `org-agenda-jump-prefer-future'."
  2926. :group 'org-time
  2927. :type '(choice
  2928. (const :tag "Never" nil)
  2929. (const :tag "Check month and day" t)
  2930. (const :tag "Check month, day, and time" time)))
  2931. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2932. "Should the agenda jump command prefer the future for incomplete dates?
  2933. The default is to do the same as configured in `org-read-date-prefer-future'.
  2934. But you can also set a deviating value here.
  2935. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2936. :group 'org-agenda
  2937. :group 'org-time
  2938. :version "24.1"
  2939. :type '(choice
  2940. (const :tag "Use org-read-date-prefer-future"
  2941. org-read-date-prefer-future)
  2942. (const :tag "Never" nil)
  2943. (const :tag "Always" t)))
  2944. (defcustom org-read-date-force-compatible-dates t
  2945. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2946. Depending on the system Emacs is running on, certain dates cannot
  2947. be represented with the type used internally to represent time.
  2948. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2949. correctly. Some systems allow for earlier dates, some for later,
  2950. some for both. One way to find out it to insert any date into an
  2951. Org buffer, putting the cursor on the year and hitting S-up and
  2952. S-down to test the range.
  2953. When this variable is set to t, the date/time prompt will not let
  2954. you specify dates outside the 1970-2037 range, so it is certain that
  2955. these dates will work in whatever version of Emacs you are
  2956. running, and also that you can move a file from one Emacs implementation
  2957. to another. WHenever Org is forcing the year for you, it will display
  2958. a message and beep.
  2959. When this variable is nil, Org will check if the date is
  2960. representable in the specific Emacs implementation you are using.
  2961. If not, it will force a year, usually the current year, and beep
  2962. to remind you. Currently this setting is not recommended because
  2963. the likelihood that you will open your Org files in an Emacs that
  2964. has limited date range is not negligible.
  2965. A workaround for this problem is to use diary sexp dates for time
  2966. stamps outside of this range."
  2967. :group 'org-time
  2968. :version "24.1"
  2969. :type 'boolean)
  2970. (defcustom org-read-date-display-live t
  2971. "Non-nil means display current interpretation of date prompt live.
  2972. This display will be in an overlay, in the minibuffer."
  2973. :group 'org-time
  2974. :type 'boolean)
  2975. (defcustom org-read-date-popup-calendar t
  2976. "Non-nil means pop up a calendar when prompting for a date.
  2977. In the calendar, the date can be selected with mouse-1. However, the
  2978. minibuffer will also be active, and you can simply enter the date as well.
  2979. When nil, only the minibuffer will be available."
  2980. :group 'org-time
  2981. :type 'boolean)
  2982. (defvaralias 'org-popup-calendar-for-date-prompt
  2983. 'org-read-date-popup-calendar)
  2984. (defcustom org-extend-today-until 0
  2985. "The hour when your day really ends. Must be an integer.
  2986. This has influence for the following applications:
  2987. - When switching the agenda to \"today\". It it is still earlier than
  2988. the time given here, the day recognized as TODAY is actually yesterday.
  2989. - When a date is read from the user and it is still before the time given
  2990. here, the current date and time will be assumed to be yesterday, 23:59.
  2991. Also, timestamps inserted in capture templates follow this rule.
  2992. IMPORTANT: This is a feature whose implementation is and likely will
  2993. remain incomplete. Really, it is only here because past midnight seems to
  2994. be the favorite working time of John Wiegley :-)"
  2995. :group 'org-time
  2996. :type 'integer)
  2997. (defcustom org-use-effective-time nil
  2998. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2999. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3000. \"effective time\" of any timestamps between midnight and 8am will be
  3001. 23:59 of the previous day."
  3002. :group 'org-time
  3003. :version "24.1"
  3004. :type 'boolean)
  3005. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3006. "When non-nil, use the last clock out time for `org-todo'.
  3007. Note that this option has precedence over the combined use of
  3008. `org-use-effective-time' and `org-extend-today-until'."
  3009. :group 'org-time
  3010. :version "24.4"
  3011. :package-version '(Org . "8.0")
  3012. :type 'boolean)
  3013. (defcustom org-edit-timestamp-down-means-later nil
  3014. "Non-nil means S-down will increase the time in a time stamp.
  3015. When nil, S-up will increase."
  3016. :group 'org-time
  3017. :type 'boolean)
  3018. (defcustom org-calendar-follow-timestamp-change t
  3019. "Non-nil means make the calendar window follow timestamp changes.
  3020. When a timestamp is modified and the calendar window is visible, it will be
  3021. moved to the new date."
  3022. :group 'org-time
  3023. :type 'boolean)
  3024. (defgroup org-tags nil
  3025. "Options concerning tags in Org-mode."
  3026. :tag "Org Tags"
  3027. :group 'org)
  3028. (defcustom org-tag-alist nil
  3029. "Default tags available in Org files.
  3030. The value of this variable is an alist. Associations either:
  3031. (TAG)
  3032. (TAG . SELECT)
  3033. (SPECIAL)
  3034. where TAG is a tag as a string, SELECT is a character, used to
  3035. select that tag through the fast tag selection interface, and
  3036. SPECIAL is one of the following keywords: `:startgroup',
  3037. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3038. `:newline'. These keywords are used to define a hierarchy of
  3039. tags. See manual for details.
  3040. When this variable is nil, Org mode bases tag input on what is
  3041. already in the buffer. The value can be overridden locally by
  3042. using a TAGS keyword, e.g.,
  3043. #+TAGS: tag1 tag2
  3044. See also `org-tag-persistent-alist' to sidestep this behavior."
  3045. :group 'org-tags
  3046. :type '(repeat
  3047. (choice
  3048. (cons (string :tag "Tag name")
  3049. (character :tag "Access char"))
  3050. (const :tag "Start radio group" (:startgroup))
  3051. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3052. (const :tag "Group tags delimiter" (:grouptags))
  3053. (const :tag "End radio group" (:endgroup))
  3054. (const :tag "End tag group, non distinct" (:endgrouptag))
  3055. (const :tag "New line" (:newline)))))
  3056. (defcustom org-tag-persistent-alist nil
  3057. "Tags always available in Org files.
  3058. The value of this variable is an alist. Associations either:
  3059. (TAG)
  3060. (TAG . SELECT)
  3061. (SPECIAL)
  3062. where TAG is a tag as a string, SELECT is a character, used to
  3063. select that tag through the fast tag selection interface, and
  3064. SPECIAL is one of the following keywords: `:startgroup',
  3065. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3066. `:newline'. These keywords are used to define a hierarchy of
  3067. tags. See manual for details.
  3068. Unlike to `org-tag-alist', tags defined in this variable do not
  3069. depend on a local TAGS keyword. Instead, to disable these tags
  3070. on a per-file basis, insert anywhere in the file:
  3071. #+STARTUP: noptag"
  3072. :group 'org-tags
  3073. :type '(repeat
  3074. (choice
  3075. (cons (string :tag "Tag name")
  3076. (character :tag "Access char"))
  3077. (const :tag "Start radio group" (:startgroup))
  3078. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3079. (const :tag "Group tags delimiter" (:grouptags))
  3080. (const :tag "End radio group" (:endgroup))
  3081. (const :tag "End tag group, non distinct" (:endgrouptag))
  3082. (const :tag "New line" (:newline)))))
  3083. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3084. "If non-nil, always offer completion for all tags of all agenda files.
  3085. Instead of customizing this variable directly, you might want to
  3086. set it locally for capture buffers, because there no list of
  3087. tags in that file can be created dynamically (there are none).
  3088. (add-hook \\='org-capture-mode-hook
  3089. (lambda ()
  3090. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3091. :group 'org-tags
  3092. :version "24.1"
  3093. :type 'boolean)
  3094. (defvar org-file-tags nil
  3095. "List of tags that can be inherited by all entries in the file.
  3096. The tags will be inherited if the variable `org-use-tag-inheritance'
  3097. says they should be.
  3098. This variable is populated from #+FILETAGS lines.")
  3099. (defcustom org-use-fast-tag-selection 'auto
  3100. "Non-nil means use fast tag selection scheme.
  3101. This is a special interface to select and deselect tags with single keys.
  3102. When nil, fast selection is never used.
  3103. When the symbol `auto', fast selection is used if and only if selection
  3104. characters for tags have been configured, either through the variable
  3105. `org-tag-alist' or through a #+TAGS line in the buffer.
  3106. When t, fast selection is always used and selection keys are assigned
  3107. automatically if necessary."
  3108. :group 'org-tags
  3109. :type '(choice
  3110. (const :tag "Always" t)
  3111. (const :tag "Never" nil)
  3112. (const :tag "When selection characters are configured" auto)))
  3113. (defcustom org-fast-tag-selection-single-key nil
  3114. "Non-nil means fast tag selection exits after first change.
  3115. When nil, you have to press RET to exit it.
  3116. During fast tag selection, you can toggle this flag with `C-c'.
  3117. This variable can also have the value `expert'. In this case, the window
  3118. displaying the tags menu is not even shown, until you press C-c again."
  3119. :group 'org-tags
  3120. :type '(choice
  3121. (const :tag "No" nil)
  3122. (const :tag "Yes" t)
  3123. (const :tag "Expert" expert)))
  3124. (defvar org-fast-tag-selection-include-todo nil
  3125. "Non-nil means fast tags selection interface will also offer TODO states.
  3126. This is an undocumented feature, you should not rely on it.")
  3127. (defcustom org-tags-column -77
  3128. "The column to which tags should be indented in a headline.
  3129. If this number is positive, it specifies the column. If it is negative,
  3130. it means that the tags should be flushright to that column. For example,
  3131. -80 works well for a normal 80 character screen.
  3132. When 0, place tags directly after headline text, with only one space in
  3133. between."
  3134. :group 'org-tags
  3135. :type 'integer)
  3136. (defcustom org-auto-align-tags t
  3137. "Non-nil keeps tags aligned when modifying headlines.
  3138. Some operations (i.e. demoting) change the length of a headline and
  3139. therefore shift the tags around. With this option turned on, after
  3140. each such operation the tags are again aligned to `org-tags-column'."
  3141. :group 'org-tags
  3142. :type 'boolean)
  3143. (defcustom org-use-tag-inheritance t
  3144. "Non-nil means tags in levels apply also for sublevels.
  3145. When nil, only the tags directly given in a specific line apply there.
  3146. This may also be a list of tags that should be inherited, or a regexp that
  3147. matches tags that should be inherited. Additional control is possible
  3148. with the variable `org-tags-exclude-from-inheritance' which gives an
  3149. explicit list of tags to be excluded from inheritance, even if the value of
  3150. `org-use-tag-inheritance' would select it for inheritance.
  3151. If this option is t, a match early-on in a tree can lead to a large
  3152. number of matches in the subtree when constructing the agenda or creating
  3153. a sparse tree. If you only want to see the first match in a tree during
  3154. a search, check out the variable `org-tags-match-list-sublevels'."
  3155. :group 'org-tags
  3156. :type '(choice
  3157. (const :tag "Not" nil)
  3158. (const :tag "Always" t)
  3159. (repeat :tag "Specific tags" (string :tag "Tag"))
  3160. (regexp :tag "Tags matched by regexp")))
  3161. (defcustom org-tags-exclude-from-inheritance nil
  3162. "List of tags that should never be inherited.
  3163. This is a way to exclude a few tags from inheritance. For way to do
  3164. the opposite, to actively allow inheritance for selected tags,
  3165. see the variable `org-use-tag-inheritance'."
  3166. :group 'org-tags
  3167. :type '(repeat (string :tag "Tag")))
  3168. (defun org-tag-inherit-p (tag)
  3169. "Check if TAG is one that should be inherited."
  3170. (cond
  3171. ((member tag org-tags-exclude-from-inheritance) nil)
  3172. ((eq org-use-tag-inheritance t) t)
  3173. ((not org-use-tag-inheritance) nil)
  3174. ((stringp org-use-tag-inheritance)
  3175. (string-match org-use-tag-inheritance tag))
  3176. ((listp org-use-tag-inheritance)
  3177. (member tag org-use-tag-inheritance))
  3178. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3179. (defcustom org-tags-match-list-sublevels t
  3180. "Non-nil means list also sublevels of headlines matching a search.
  3181. This variable applies to tags/property searches, and also to stuck
  3182. projects because this search is based on a tags match as well.
  3183. When set to the symbol `indented', sublevels are indented with
  3184. leading dots.
  3185. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3186. the sublevels of a headline matching a tag search often also match
  3187. the same search. Listing all of them can create very long lists.
  3188. Setting this variable to nil causes subtrees of a match to be skipped.
  3189. This variable is semi-obsolete and probably should always be true. It
  3190. is better to limit inheritance to certain tags using the variables
  3191. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3192. :group 'org-tags
  3193. :type '(choice
  3194. (const :tag "No, don't list them" nil)
  3195. (const :tag "Yes, do list them" t)
  3196. (const :tag "List them, indented with leading dots" indented)))
  3197. (defcustom org-tags-sort-function nil
  3198. "When set, tags are sorted using this function as a comparator."
  3199. :group 'org-tags
  3200. :type '(choice
  3201. (const :tag "No sorting" nil)
  3202. (const :tag "Alphabetical" string<)
  3203. (const :tag "Reverse alphabetical" string>)
  3204. (function :tag "Custom function" nil)))
  3205. (defvar org-tags-history nil
  3206. "History of minibuffer reads for tags.")
  3207. (defvar org-last-tags-completion-table nil
  3208. "The last used completion table for tags.")
  3209. (defvar org-after-tags-change-hook nil
  3210. "Hook that is run after the tags in a line have changed.")
  3211. (defgroup org-properties nil
  3212. "Options concerning properties in Org-mode."
  3213. :tag "Org Properties"
  3214. :group 'org)
  3215. (defcustom org-property-format "%-10s %s"
  3216. "How property key/value pairs should be formatted by `indent-line'.
  3217. When `indent-line' hits a property definition, it will format the line
  3218. according to this format, mainly to make sure that the values are
  3219. lined-up with respect to each other."
  3220. :group 'org-properties
  3221. :type 'string)
  3222. (defcustom org-properties-postprocess-alist nil
  3223. "Alist of properties and functions to adjust inserted values.
  3224. Elements of this alist must be of the form
  3225. ([string] [function])
  3226. where [string] must be a property name and [function] must be a
  3227. lambda expression: this lambda expression must take one argument,
  3228. the value to adjust, and return the new value as a string.
  3229. For example, this element will allow the property \"Remaining\"
  3230. to be updated wrt the relation between the \"Effort\" property
  3231. and the clock summary:
  3232. ((\"Remaining\" (lambda(value)
  3233. (let ((clocksum (org-clock-sum-current-item))
  3234. (effort (org-duration-string-to-minutes
  3235. (org-entry-get (point) \"Effort\"))))
  3236. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3237. :group 'org-properties
  3238. :version "24.1"
  3239. :type '(alist :key-type (string :tag "Property")
  3240. :value-type (function :tag "Function")))
  3241. (defcustom org-use-property-inheritance nil
  3242. "Non-nil means properties apply also for sublevels.
  3243. This setting is chiefly used during property searches. Turning it on can
  3244. cause significant overhead when doing a search, which is why it is not
  3245. on by default.
  3246. When nil, only the properties directly given in the current entry count.
  3247. When t, every property is inherited. The value may also be a list of
  3248. properties that should have inheritance, or a regular expression matching
  3249. properties that should be inherited.
  3250. However, note that some special properties use inheritance under special
  3251. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3252. and the properties ending in \"_ALL\" when they are used as descriptor
  3253. for valid values of a property.
  3254. Note for programmers:
  3255. When querying an entry with `org-entry-get', you can control if inheritance
  3256. should be used. By default, `org-entry-get' looks only at the local
  3257. properties. You can request inheritance by setting the inherit argument
  3258. to t (to force inheritance) or to `selective' (to respect the setting
  3259. in this variable)."
  3260. :group 'org-properties
  3261. :type '(choice
  3262. (const :tag "Not" nil)
  3263. (const :tag "Always" t)
  3264. (repeat :tag "Specific properties" (string :tag "Property"))
  3265. (regexp :tag "Properties matched by regexp")))
  3266. (defun org-property-inherit-p (property)
  3267. "Check if PROPERTY is one that should be inherited."
  3268. (cond
  3269. ((eq org-use-property-inheritance t) t)
  3270. ((not org-use-property-inheritance) nil)
  3271. ((stringp org-use-property-inheritance)
  3272. (string-match org-use-property-inheritance property))
  3273. ((listp org-use-property-inheritance)
  3274. (member property org-use-property-inheritance))
  3275. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3276. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3277. "The default column format, if no other format has been defined.
  3278. This variable can be set on the per-file basis by inserting a line
  3279. #+COLUMNS: %25ITEM ....."
  3280. :group 'org-properties
  3281. :type 'string)
  3282. (defcustom org-columns-ellipses ".."
  3283. "The ellipses to be used when a field in column view is truncated.
  3284. When this is the empty string, as many characters as possible are shown,
  3285. but then there will be no visual indication that the field has been truncated.
  3286. When this is a string of length N, the last N characters of a truncated
  3287. field are replaced by this string. If the column is narrower than the
  3288. ellipses string, only part of the ellipses string will be shown."
  3289. :group 'org-properties
  3290. :type 'string)
  3291. (defconst org-global-properties-fixed
  3292. '(("VISIBILITY_ALL" . "folded children content all")
  3293. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3294. "List of property/value pairs that can be inherited by any entry.
  3295. These are fixed values, for the preset properties. The user variable
  3296. that can be used to add to this list is `org-global-properties'.
  3297. The entries in this list are cons cells where the car is a property
  3298. name and cdr is a string with the value. If the value represents
  3299. multiple items like an \"_ALL\" property, separate the items by
  3300. spaces.")
  3301. (defcustom org-global-properties nil
  3302. "List of property/value pairs that can be inherited by any entry.
  3303. This list will be combined with the constant `org-global-properties-fixed'.
  3304. The entries in this list are cons cells where the car is a property
  3305. name and cdr is a string with the value.
  3306. You can set buffer-local values for the same purpose in the variable
  3307. `org-file-properties' this by adding lines like
  3308. #+PROPERTY: NAME VALUE"
  3309. :group 'org-properties
  3310. :type '(repeat
  3311. (cons (string :tag "Property")
  3312. (string :tag "Value"))))
  3313. (defvar-local org-file-properties nil
  3314. "List of property/value pairs that can be inherited by any entry.
  3315. Valid for the current buffer.
  3316. This variable is populated from #+PROPERTY lines.")
  3317. (defgroup org-agenda nil
  3318. "Options concerning agenda views in Org-mode."
  3319. :tag "Org Agenda"
  3320. :group 'org)
  3321. (defvar-local org-category nil
  3322. "Variable used by org files to set a category for agenda display.
  3323. Such files should use a file variable to set it, for example
  3324. # -*- mode: org; org-category: \"ELisp\"
  3325. or contain a special line
  3326. #+CATEGORY: ELisp
  3327. If the file does not specify a category, then file's base name
  3328. is used instead.")
  3329. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3330. (defcustom org-agenda-files nil
  3331. "The files to be used for agenda display.
  3332. Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
  3333. \\[org-remove-file]. You can also use customize to edit the list.
  3334. If an entry is a directory, all files in that directory that are matched by
  3335. `org-agenda-file-regexp' will be part of the file list.
  3336. If the value of the variable is not a list but a single file name, then
  3337. the list of agenda files is actually stored and maintained in that file, one
  3338. agenda file per line. In this file paths can be given relative to
  3339. `org-directory'. Tilde expansion and environment variable substitution
  3340. are also made."
  3341. :group 'org-agenda
  3342. :type '(choice
  3343. (repeat :tag "List of files and directories" file)
  3344. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3345. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3346. "Regular expression to match files for `org-agenda-files'.
  3347. If any element in the list in that variable contains a directory instead
  3348. of a normal file, all files in that directory that are matched by this
  3349. regular expression will be included."
  3350. :group 'org-agenda
  3351. :type 'regexp)
  3352. (defcustom org-agenda-text-search-extra-files nil
  3353. "List of extra files to be searched by text search commands.
  3354. These files will be searched in addition to the agenda files by the
  3355. commands `org-search-view' (`\\[org-agenda] s') \
  3356. and `org-occur-in-agenda-files'.
  3357. Note that these files will only be searched for text search commands,
  3358. not for the other agenda views like todo lists, tag searches or the weekly
  3359. agenda. This variable is intended to list notes and possibly archive files
  3360. that should also be searched by these two commands.
  3361. In fact, if the first element in the list is the symbol `agenda-archives',
  3362. then all archive files of all agenda files will be added to the search
  3363. scope."
  3364. :group 'org-agenda
  3365. :type '(set :greedy t
  3366. (const :tag "Agenda Archives" agenda-archives)
  3367. (repeat :inline t (file))))
  3368. (defvaralias 'org-agenda-multi-occur-extra-files
  3369. 'org-agenda-text-search-extra-files)
  3370. (defcustom org-agenda-skip-unavailable-files nil
  3371. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3372. A nil value means to remove them, after a query, from the list."
  3373. :group 'org-agenda
  3374. :type 'boolean)
  3375. (defcustom org-calendar-to-agenda-key [?c]
  3376. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3377. The command `org-calendar-goto-agenda' will be bound to this key. The
  3378. default is the character `c' because then `c' can be used to switch back and
  3379. forth between agenda and calendar."
  3380. :group 'org-agenda
  3381. :type 'sexp)
  3382. (defcustom org-calendar-insert-diary-entry-key [?i]
  3383. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3384. This option is irrelevant until `org-agenda-diary-file' has been configured
  3385. to point to an Org file. When that is the case, the command
  3386. `org-agenda-diary-entry' will be bound to the key given here, by default
  3387. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3388. if you want to continue doing this, you need to change this to a different
  3389. key."
  3390. :group 'org-agenda
  3391. :type 'sexp)
  3392. (defcustom org-agenda-diary-file 'diary-file
  3393. "File to which to add new entries with the `i' key in agenda and calendar.
  3394. When this is the symbol `diary-file', the functionality in the Emacs
  3395. calendar will be used to add entries to the `diary-file'. But when this
  3396. points to a file, `org-agenda-diary-entry' will be used instead."
  3397. :group 'org-agenda
  3398. :type '(choice
  3399. (const :tag "The standard Emacs diary file" diary-file)
  3400. (file :tag "Special Org file diary entries")))
  3401. (eval-after-load "calendar"
  3402. '(progn
  3403. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3404. 'org-calendar-goto-agenda)
  3405. (add-hook 'calendar-mode-hook
  3406. (lambda ()
  3407. (unless (eq org-agenda-diary-file 'diary-file)
  3408. (define-key calendar-mode-map
  3409. org-calendar-insert-diary-entry-key
  3410. 'org-agenda-diary-entry))))))
  3411. (defgroup org-latex nil
  3412. "Options for embedding LaTeX code into Org-mode."
  3413. :tag "Org LaTeX"
  3414. :group 'org)
  3415. (defcustom org-format-latex-options
  3416. '(:foreground default :background default :scale 1.0
  3417. :html-foreground "Black" :html-background "Transparent"
  3418. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3419. "Options for creating images from LaTeX fragments.
  3420. This is a property list with the following properties:
  3421. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3422. `default' means use the foreground of the default face.
  3423. `auto' means use the foreground from the text face.
  3424. :background the background color, or \"Transparent\".
  3425. `default' means use the background of the default face.
  3426. `auto' means use the background from the text face.
  3427. :scale a scaling factor for the size of the images, to get more pixels
  3428. :html-foreground, :html-background, :html-scale
  3429. the same numbers for HTML export.
  3430. :matchers a list indicating which matchers should be used to
  3431. find LaTeX fragments. Valid members of this list are:
  3432. \"begin\" find environments
  3433. \"$1\" find single characters surrounded by $.$
  3434. \"$\" find math expressions surrounded by $...$
  3435. \"$$\" find math expressions surrounded by $$....$$
  3436. \"\\(\" find math expressions surrounded by \\(...\\)
  3437. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3438. :group 'org-latex
  3439. :type 'plist)
  3440. (defcustom org-format-latex-signal-error t
  3441. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3442. When nil, just push out a message."
  3443. :group 'org-latex
  3444. :version "24.1"
  3445. :type 'boolean)
  3446. (defcustom org-latex-to-mathml-jar-file nil
  3447. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3448. Use this to specify additional executable file say a jar file.
  3449. When using MathToWeb as the converter, specify the full-path to
  3450. your mathtoweb.jar file."
  3451. :group 'org-latex
  3452. :version "24.1"
  3453. :type '(choice
  3454. (const :tag "None" nil)
  3455. (file :tag "JAR file" :must-match t)))
  3456. (defcustom org-latex-to-mathml-convert-command nil
  3457. "Command to convert LaTeX fragments to MathML.
  3458. Replace format-specifiers in the command as noted below and use
  3459. `shell-command' to convert LaTeX to MathML.
  3460. %j: Executable file in fully expanded form as specified by
  3461. `org-latex-to-mathml-jar-file'.
  3462. %I: Input LaTeX file in fully expanded form.
  3463. %i: The latex fragment to be converted.
  3464. %o: Output MathML file.
  3465. This command is used by `org-create-math-formula'.
  3466. When using MathToWeb as the converter, set this option to
  3467. \"java -jar %j -unicode -force -df %o %I\".
  3468. When using LaTeXML set this option to
  3469. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3470. :group 'org-latex
  3471. :version "24.1"
  3472. :type '(choice
  3473. (const :tag "None" nil)
  3474. (string :tag "\nShell command")))
  3475. (defcustom org-preview-latex-default-process 'dvipng
  3476. "The default process to convert LaTeX fragments to image files.
  3477. All available processes and theirs documents can be found in
  3478. `org-preview-latex-process-alist', which see."
  3479. :group 'org-latex
  3480. :version "25.2"
  3481. :package-version '(Org . "9.0")
  3482. :type 'symbol)
  3483. (defcustom org-preview-latex-process-alist
  3484. '((dvipng
  3485. :programs ("latex" "dvipng" "gs")
  3486. :description "dvi > png"
  3487. :message "you need to install the programs: latex, dvipng and ghostscript."
  3488. :image-input-type "dvi"
  3489. :image-output-type "png"
  3490. :image-size-adjust (1.0 . 1.0)
  3491. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3492. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
  3493. (dvisvgm
  3494. :programs ("latex" "dvisvgm" "gs")
  3495. :description "dvi > svg"
  3496. :message "you need to install the programs: latex, dvisvgm and ghostscript."
  3497. :use-xcolor t
  3498. :image-input-type "dvi"
  3499. :image-output-type "svg"
  3500. :image-size-adjust (1.7 . 1.5)
  3501. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3502. :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
  3503. (imagemagick
  3504. :programs ("latex" "convert" "gs")
  3505. :description "pdf > png"
  3506. :message
  3507. "you need to install the programs: latex, imagemagick and ghostscript."
  3508. :use-xcolor t
  3509. :image-input-type "pdf"
  3510. :image-output-type "png"
  3511. :image-size-adjust (1.0 . 1.0)
  3512. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3513. :image-converter
  3514. ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
  3515. "Definitions of external processes for LaTeX previewing.
  3516. Org mode can use some external commands to generate TeX snippet's images for
  3517. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3518. `org-create-formula-image' how to call them.
  3519. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3520. PROPERTIES accepts the following attributes:
  3521. :programs list of strings, required programs.
  3522. :description string, describe the process.
  3523. :message string, message it when required programs cannot be found.
  3524. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3525. :image-output-type string, output file type of image converter (e.g., \"png\").
  3526. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3527. deal with background and foreground color of image.
  3528. Otherwise, dvipng style background and foregroud color
  3529. format are generated. You may then refer to them in
  3530. command options with \"%F\" and \"%B\".
  3531. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3532. image size showed in buffer and the cdr element is for
  3533. HTML file. This option is only useful for process
  3534. developers, users should use variable
  3535. `org-format-latex-options' instead.
  3536. :post-clean list of strings, files matched are to be cleaned up once
  3537. the image is generated. When nil, the files with \".dvi\",
  3538. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3539. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3540. be cleaned up.
  3541. :latex-header list of strings, the LaTeX header of the snippet file.
  3542. When nil, the fallback value is used instead, which is
  3543. controlled by `org-format-latex-header',
  3544. `org-latex-default-packages-alist' and
  3545. `org-latex-packages-alist', which see.
  3546. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3547. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3548. replaced with values defined below.
  3549. :image-converter list of image converter commands strings. Each of them is
  3550. given to the shell and supports any of the following
  3551. place-holders defined below.
  3552. Place-holders used by `:image-converter' and `:latex-compiler':
  3553. %f input file name.
  3554. %b base name of input file.
  3555. %o base directory of input file.
  3556. Place-holders only used by `:image-converter':
  3557. %F foreground of image
  3558. %B background of image
  3559. %D dpi, which is used to adjust image size by some processing commands.
  3560. %S the image size scale ratio, which is used to adjust image size by some
  3561. processing commands."
  3562. :group 'org-latex
  3563. :version "25.2"
  3564. :package-version '(Org . "9.0")
  3565. :type '(alist :tag "LaTeX to image backends"
  3566. :value-type (plist)))
  3567. (defcustom org-preview-latex-image-directory "ltximg/"
  3568. "Path to store latex preview images.
  3569. A relative path here creates many directories relative to the
  3570. processed org files paths. An absolute path puts all preview
  3571. images at the same place."
  3572. :group 'org-latex
  3573. :version "25.1"
  3574. :package-version '(Org . "9.0")
  3575. :type 'string)
  3576. (defun org-format-latex-mathml-available-p ()
  3577. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3578. (save-match-data
  3579. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3580. org-latex-to-mathml-convert-command)
  3581. (let ((executable (car (split-string
  3582. org-latex-to-mathml-convert-command))))
  3583. (when (executable-find executable)
  3584. (if (string-match
  3585. "%j" org-latex-to-mathml-convert-command)
  3586. (file-readable-p org-latex-to-mathml-jar-file)
  3587. t))))))
  3588. (defcustom org-format-latex-header "\\documentclass{article}
  3589. \\usepackage[usenames]{color}
  3590. \[PACKAGES]
  3591. \[DEFAULT-PACKAGES]
  3592. \\pagestyle{empty} % do not remove
  3593. % The settings below are copied from fullpage.sty
  3594. \\setlength{\\textwidth}{\\paperwidth}
  3595. \\addtolength{\\textwidth}{-3cm}
  3596. \\setlength{\\oddsidemargin}{1.5cm}
  3597. \\addtolength{\\oddsidemargin}{-2.54cm}
  3598. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3599. \\setlength{\\textheight}{\\paperheight}
  3600. \\addtolength{\\textheight}{-\\headheight}
  3601. \\addtolength{\\textheight}{-\\headsep}
  3602. \\addtolength{\\textheight}{-\\footskip}
  3603. \\addtolength{\\textheight}{-3cm}
  3604. \\setlength{\\topmargin}{1.5cm}
  3605. \\addtolength{\\topmargin}{-2.54cm}"
  3606. "The document header used for processing LaTeX fragments.
  3607. It is imperative that this header make sure that no page number
  3608. appears on the page. The package defined in the variables
  3609. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3610. will either replace the placeholder \"[PACKAGES]\" in this
  3611. header, or they will be appended."
  3612. :group 'org-latex
  3613. :type 'string)
  3614. (defun org-set-packages-alist (var val)
  3615. "Set the packages alist and make sure it has 3 elements per entry."
  3616. (set var (mapcar (lambda (x)
  3617. (if (and (consp x) (= (length x) 2))
  3618. (list (car x) (nth 1 x) t)
  3619. x))
  3620. val)))
  3621. (defun org-get-packages-alist (var)
  3622. "Get the packages alist and make sure it has 3 elements per entry."
  3623. (mapcar (lambda (x)
  3624. (if (and (consp x) (= (length x) 2))
  3625. (list (car x) (nth 1 x) t)
  3626. x))
  3627. (default-value var)))
  3628. (defcustom org-latex-default-packages-alist
  3629. '(("AUTO" "inputenc" t ("pdflatex"))
  3630. ("T1" "fontenc" t ("pdflatex"))
  3631. ("" "graphicx" t)
  3632. ("" "grffile" t)
  3633. ("" "longtable" nil)
  3634. ("" "wrapfig" nil)
  3635. ("" "rotating" nil)
  3636. ("normalem" "ulem" t)
  3637. ("" "amsmath" t)
  3638. ("" "textcomp" t)
  3639. ("" "amssymb" t)
  3640. ("" "capt-of" nil)
  3641. ("" "hyperref" nil))
  3642. "Alist of default packages to be inserted in the header.
  3643. Change this only if one of the packages here causes an
  3644. incompatibility with another package you are using.
  3645. The packages in this list are needed by one part or another of
  3646. Org mode to function properly:
  3647. - inputenc, fontenc: for basic font and character selection
  3648. - graphicx: for including images
  3649. - grffile: allow periods and spaces in graphics file names
  3650. - longtable: For multipage tables
  3651. - wrapfig: for figure placement
  3652. - rotating: for sideways figures and tables
  3653. - ulem: for underline and strike-through
  3654. - amsmath: for subscript and superscript and math environments
  3655. - textcomp, amssymb: for various symbols used
  3656. for interpreting the entities in `org-entities'. You can skip
  3657. some of these packages if you don't use any of their symbols.
  3658. - capt-of: for captions outside of floats
  3659. - hyperref: for cross references
  3660. Therefore you should not modify this variable unless you know
  3661. what you are doing. The one reason to change it anyway is that
  3662. you might be loading some other package that conflicts with one
  3663. of the default packages. Each element is either a cell or
  3664. a string.
  3665. A cell is of the format
  3666. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3667. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3668. when compiling LaTeX snippets into images for inclusion into
  3669. non-LaTeX output. COMPILERS is a list of compilers that should
  3670. include the package, see `org-latex-compiler'. If the document
  3671. compiler is not in the list, and the list is non-nil, the package
  3672. will not be inserted in the final document.
  3673. A string will be inserted as-is in the header of the document."
  3674. :group 'org-latex
  3675. :group 'org-export-latex
  3676. :set 'org-set-packages-alist
  3677. :get 'org-get-packages-alist
  3678. :version "25.1"
  3679. :package-version '(Org . "8.3")
  3680. :type '(repeat
  3681. (choice
  3682. (list :tag "options/package pair"
  3683. (string :tag "options")
  3684. (string :tag "package")
  3685. (boolean :tag "Snippet"))
  3686. (string :tag "A line of LaTeX"))))
  3687. (defcustom org-latex-packages-alist nil
  3688. "Alist of packages to be inserted in every LaTeX header.
  3689. These will be inserted after `org-latex-default-packages-alist'.
  3690. Each element is either a cell or a string.
  3691. A cell is of the format:
  3692. (\"options\" \"package\" SNIPPET-FLAG)
  3693. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3694. needed when turning LaTeX snippets into images for inclusion into
  3695. non-LaTeX output.
  3696. A string will be inserted as-is in the header of the document.
  3697. Make sure that you only list packages here which:
  3698. - you want in every file;
  3699. - do not conflict with the setup in `org-format-latex-header';
  3700. - do not conflict with the default packages in
  3701. `org-latex-default-packages-alist'."
  3702. :group 'org-latex
  3703. :group 'org-export-latex
  3704. :set 'org-set-packages-alist
  3705. :get 'org-get-packages-alist
  3706. :type '(repeat
  3707. (choice
  3708. (list :tag "options/package pair"
  3709. (string :tag "options")
  3710. (string :tag "package")
  3711. (boolean :tag "Snippet"))
  3712. (string :tag "A line of LaTeX"))))
  3713. (defgroup org-appearance nil
  3714. "Settings for Org mode appearance."
  3715. :tag "Org Appearance"
  3716. :group 'org)
  3717. (defcustom org-level-color-stars-only nil
  3718. "Non-nil means fontify only the stars in each headline.
  3719. When nil, the entire headline is fontified.
  3720. Changing it requires restart of `font-lock-mode' to become effective
  3721. also in regions already fontified."
  3722. :group 'org-appearance
  3723. :type 'boolean)
  3724. (defcustom org-hide-leading-stars nil
  3725. "Non-nil means hide the first N-1 stars in a headline.
  3726. This works by using the face `org-hide' for these stars. This
  3727. face is white for a light background, and black for a dark
  3728. background. You may have to customize the face `org-hide' to
  3729. make this work.
  3730. Changing it requires restart of `font-lock-mode' to become effective
  3731. also in regions already fontified.
  3732. You may also set this on a per-file basis by adding one of the following
  3733. lines to the buffer:
  3734. #+STARTUP: hidestars
  3735. #+STARTUP: showstars"
  3736. :group 'org-appearance
  3737. :type 'boolean)
  3738. (defcustom org-hidden-keywords nil
  3739. "List of symbols corresponding to keywords to be hidden the org buffer.
  3740. For example, a value \\='(title) for this list will make the document's title
  3741. appear in the buffer without the initial #+TITLE: keyword."
  3742. :group 'org-appearance
  3743. :version "24.1"
  3744. :type '(set (const :tag "#+AUTHOR" author)
  3745. (const :tag "#+DATE" date)
  3746. (const :tag "#+EMAIL" email)
  3747. (const :tag "#+TITLE" title)))
  3748. (defcustom org-custom-properties nil
  3749. "List of properties (as strings) with a special meaning.
  3750. The default use of these custom properties is to let the user
  3751. hide them with `org-toggle-custom-properties-visibility'."
  3752. :group 'org-properties
  3753. :group 'org-appearance
  3754. :version "24.3"
  3755. :type '(repeat (string :tag "Property Name")))
  3756. (defcustom org-fontify-done-headline nil
  3757. "Non-nil means change the face of a headline if it is marked DONE.
  3758. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3759. When this is non-nil, the headline after the keyword is set to the
  3760. `org-headline-done' as an additional indication."
  3761. :group 'org-appearance
  3762. :type 'boolean)
  3763. (defcustom org-fontify-emphasized-text t
  3764. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3765. Changing this variable requires a restart of Emacs to take effect."
  3766. :group 'org-appearance
  3767. :type 'boolean)
  3768. (defcustom org-fontify-whole-heading-line nil
  3769. "Non-nil means fontify the whole line for headings.
  3770. This is useful when setting a background color for the
  3771. org-level-* faces."
  3772. :group 'org-appearance
  3773. :type 'boolean)
  3774. (defcustom org-highlight-latex-and-related nil
  3775. "Non-nil means highlight LaTeX related syntax in the buffer.
  3776. When non nil, the value should be a list containing any of the
  3777. following symbols:
  3778. `latex' Highlight LaTeX snippets and environments.
  3779. `script' Highlight subscript and superscript.
  3780. `entities' Highlight entities."
  3781. :group 'org-appearance
  3782. :version "24.4"
  3783. :package-version '(Org . "8.0")
  3784. :type '(choice
  3785. (const :tag "No highlighting" nil)
  3786. (set :greedy t :tag "Highlight"
  3787. (const :tag "LaTeX snippets and environments" latex)
  3788. (const :tag "Subscript and superscript" script)
  3789. (const :tag "Entities" entities))))
  3790. (defcustom org-hide-emphasis-markers nil
  3791. "Non-nil mean font-lock should hide the emphasis marker characters."
  3792. :group 'org-appearance
  3793. :type 'boolean)
  3794. (defcustom org-hide-macro-markers nil
  3795. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3796. :group 'org-appearance
  3797. :type 'boolean)
  3798. (defcustom org-pretty-entities nil
  3799. "Non-nil means show entities as UTF8 characters.
  3800. When nil, the \\name form remains in the buffer."
  3801. :group 'org-appearance
  3802. :version "24.1"
  3803. :type 'boolean)
  3804. (defcustom org-pretty-entities-include-sub-superscripts t
  3805. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3806. :group 'org-appearance
  3807. :version "24.1"
  3808. :type 'boolean)
  3809. (defvar org-emph-re nil
  3810. "Regular expression for matching emphasis.
  3811. After a match, the match groups contain these elements:
  3812. 0 The match of the full regular expression, including the characters
  3813. before and after the proper match
  3814. 1 The character before the proper match, or empty at beginning of line
  3815. 2 The proper match, including the leading and trailing markers
  3816. 3 The leading marker like * or /, indicating the type of highlighting
  3817. 4 The text between the emphasis markers, not including the markers
  3818. 5 The character after the match, empty at the end of a line")
  3819. (defvar org-verbatim-re nil
  3820. "Regular expression for matching verbatim text.")
  3821. (defvar org-emphasis-regexp-components) ; defined just below
  3822. (defvar org-emphasis-alist) ; defined just below
  3823. (defun org-set-emph-re (var val)
  3824. "Set variable and compute the emphasis regular expression."
  3825. (set var val)
  3826. (when (and (boundp 'org-emphasis-alist)
  3827. (boundp 'org-emphasis-regexp-components)
  3828. org-emphasis-alist org-emphasis-regexp-components)
  3829. (let* ((e org-emphasis-regexp-components)
  3830. (pre (car e))
  3831. (post (nth 1 e))
  3832. (border (nth 2 e))
  3833. (body (nth 3 e))
  3834. (nl (nth 4 e))
  3835. (body1 (concat body "*?"))
  3836. (markers (mapconcat 'car org-emphasis-alist ""))
  3837. (vmarkers (mapconcat
  3838. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3839. org-emphasis-alist "")))
  3840. ;; make sure special characters appear at the right position in the class
  3841. (if (string-match "\\^" markers)
  3842. (setq markers (concat (replace-match "" t t markers) "^")))
  3843. (if (string-match "-" markers)
  3844. (setq markers (concat (replace-match "" t t markers) "-")))
  3845. (if (string-match "\\^" vmarkers)
  3846. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3847. (if (string-match "-" vmarkers)
  3848. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3849. (if (> nl 0)
  3850. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3851. (int-to-string nl) "\\}")))
  3852. ;; Make the regexp
  3853. (setq org-emph-re
  3854. (concat "\\([" pre "]\\|^\\)"
  3855. "\\("
  3856. "\\([" markers "]\\)"
  3857. "\\("
  3858. "[^" border "]\\|"
  3859. "[^" border "]"
  3860. body1
  3861. "[^" border "]"
  3862. "\\)"
  3863. "\\3\\)"
  3864. "\\([" post "]\\|$\\)"))
  3865. (setq org-verbatim-re
  3866. (concat "\\([" pre "]\\|^\\)"
  3867. "\\("
  3868. "\\([" vmarkers "]\\)"
  3869. "\\("
  3870. "[^" border "]\\|"
  3871. "[^" border "]"
  3872. body1
  3873. "[^" border "]"
  3874. "\\)"
  3875. "\\3\\)"
  3876. "\\([" post "]\\|$\\)")))))
  3877. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3878. ;; set this option proved cumbersome. See this message/thread:
  3879. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3880. (defvar org-emphasis-regexp-components
  3881. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3882. "Components used to build the regular expression for emphasis.
  3883. This is a list with five entries. Terminology: In an emphasis string
  3884. like \" *strong word* \", we call the initial space PREMATCH, the final
  3885. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3886. and \"trong wor\" is the body. The different components in this variable
  3887. specify what is allowed/forbidden in each part:
  3888. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3889. post Chars allowed as postmatch. End of line will be allowed too.
  3890. border The chars *forbidden* as border characters.
  3891. body-regexp A regexp like \".\" to match a body character. Don't use
  3892. non-shy groups here, and don't allow newline here.
  3893. newline The maximum number of newlines allowed in an emphasis exp.
  3894. You need to reload Org or to restart Emacs after customizing this.")
  3895. (defcustom org-emphasis-alist
  3896. '(("*" bold)
  3897. ("/" italic)
  3898. ("_" underline)
  3899. ("=" org-verbatim verbatim)
  3900. ("~" org-code verbatim)
  3901. ("+" (:strike-through t)))
  3902. "Alist of characters and faces to emphasize text.
  3903. Text starting and ending with a special character will be emphasized,
  3904. for example *bold*, _underlined_ and /italic/. This variable sets the
  3905. marker characters and the face to be used by font-lock for highlighting
  3906. in Org buffers.
  3907. You need to reload Org or to restart Emacs after customizing this."
  3908. :group 'org-appearance
  3909. :set 'org-set-emph-re
  3910. :version "24.4"
  3911. :package-version '(Org . "8.0")
  3912. :type '(repeat
  3913. (list
  3914. (string :tag "Marker character")
  3915. (choice
  3916. (face :tag "Font-lock-face")
  3917. (plist :tag "Face property list"))
  3918. (option (const verbatim)))))
  3919. (defvar org-protecting-blocks '("src" "example" "export")
  3920. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3921. This is needed for font-lock setup.")
  3922. ;;; Functions and variables from their packages
  3923. ;; Declared here to avoid compiler warnings
  3924. (defvar mark-active)
  3925. ;; Various packages
  3926. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3927. (declare-function calendar-forward-day "cal-move" (arg))
  3928. (declare-function calendar-goto-date "cal-move" (date))
  3929. (declare-function calendar-goto-today "cal-move" ())
  3930. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3931. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3932. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3933. (declare-function cdlatex-tab "ext:cdlatex" ())
  3934. (declare-function dired-get-filename
  3935. "dired"
  3936. (&optional localp no-error-if-not-filep))
  3937. (declare-function iswitchb-read-buffer
  3938. "iswitchb"
  3939. (prompt &optional
  3940. default require-match _predicate start matches-set))
  3941. (declare-function org-agenda-change-all-lines
  3942. "org-agenda"
  3943. (newhead hdmarker &optional fixface just-this))
  3944. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3945. "org-agenda"
  3946. (&optional end))
  3947. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3948. (declare-function org-agenda-format-item
  3949. "org-agenda"
  3950. (extra txt &optional level category tags dotime
  3951. remove-re habitp))
  3952. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3953. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3954. (declare-function org-agenda-save-markers-for-cut-and-paste
  3955. "org-agenda"
  3956. (beg end))
  3957. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3958. (declare-function org-agenda-skip "org-agenda" ())
  3959. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3960. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3961. (declare-function org-indent-mode "org-indent" (&optional arg))
  3962. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3963. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3964. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3965. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3966. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3967. (declare-function parse-time-string "parse-time" (string))
  3968. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3969. (declare-function table--at-cell-p
  3970. "table"
  3971. (position &optional object at-column))
  3972. (defvar align-mode-rules-list)
  3973. (defvar calc-embedded-close-formula)
  3974. (defvar calc-embedded-open-formula)
  3975. (defvar calc-embedded-open-mode)
  3976. (defvar font-lock-unfontify-region-function)
  3977. (defvar iswitchb-temp-buflist)
  3978. (defvar org-agenda-tags-todo-honor-ignore-options)
  3979. (defvar remember-data-file)
  3980. (defvar texmathp-why)
  3981. ;;;###autoload
  3982. (defun turn-on-orgtbl ()
  3983. "Unconditionally turn on `orgtbl-mode'."
  3984. (require 'org-table)
  3985. (orgtbl-mode 1))
  3986. (defun org-at-table-p (&optional table-type)
  3987. "Non-nil if the cursor is inside an Org table.
  3988. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3989. If `org-enable-table-editor' is nil, return nil unconditionally."
  3990. (and
  3991. org-enable-table-editor
  3992. (save-excursion
  3993. (beginning-of-line)
  3994. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3995. (or (not (derived-mode-p 'org-mode))
  3996. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3997. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3998. (defun org-at-table.el-p ()
  3999. "Non-nil when point is at a table.el table."
  4000. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4001. (let ((element (org-element-at-point)))
  4002. (and (eq (org-element-type element) 'table)
  4003. (eq (org-element-property :type element) 'table.el)))))
  4004. (defun org-table-recognize-table.el ()
  4005. "If there is a table.el table nearby, recognize it and move into it."
  4006. (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
  4007. (beginning-of-line)
  4008. (unless (or (looking-at org-table-dataline-regexp)
  4009. (not (looking-at org-table1-hline-regexp)))
  4010. (forward-line)
  4011. (when (looking-at org-table-any-border-regexp)
  4012. (forward-line -2)))
  4013. (if (re-search-forward "|" (org-table-end t) t)
  4014. (progn
  4015. (require 'table)
  4016. (if (table--at-cell-p (point)) t
  4017. (message "recognizing table.el table...")
  4018. (table-recognize-table)
  4019. (message "recognizing table.el table...done")))
  4020. (error "This should not happen"))))
  4021. ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
  4022. (make-obsolete 'org-table-recognize-table.el
  4023. "please notify the org mailing list if you use this function."
  4024. "Org 9.0")
  4025. (defun org-at-table-hline-p ()
  4026. "Non-nil when point is inside a hline in a table.
  4027. Assume point is already in a table. If `org-enable-table-editor'
  4028. is nil, return nil unconditionally."
  4029. (and org-enable-table-editor
  4030. (save-excursion
  4031. (beginning-of-line)
  4032. (looking-at org-table-hline-regexp))))
  4033. (defun org-table-map-tables (function &optional quietly)
  4034. "Apply FUNCTION to the start of all tables in the buffer."
  4035. (save-excursion
  4036. (save-restriction
  4037. (widen)
  4038. (goto-char (point-min))
  4039. (while (re-search-forward org-table-any-line-regexp nil t)
  4040. (unless quietly
  4041. (message "Mapping tables: %d%%"
  4042. (floor (* 100.0 (point)) (buffer-size))))
  4043. (beginning-of-line 1)
  4044. (when (and (looking-at org-table-line-regexp)
  4045. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4046. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4047. (save-excursion (funcall function))
  4048. (or (looking-at org-table-line-regexp)
  4049. (forward-char 1)))
  4050. (re-search-forward org-table-any-border-regexp nil 1))))
  4051. (unless quietly (message "Mapping tables: done")))
  4052. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4053. (declare-function org-clock-update-mode-line "org-clock" ())
  4054. (declare-function org-resolve-clocks "org-clock"
  4055. (&optional also-non-dangling-p prompt last-valid))
  4056. (defun org-at-TBLFM-p (&optional pos)
  4057. "Non-nil when point (or POS) is in #+TBLFM line."
  4058. (save-excursion
  4059. (goto-char (or pos (point)))
  4060. (beginning-of-line)
  4061. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4062. (eq (org-element-type (org-element-at-point)) 'table))))
  4063. (defvar org-clock-start-time)
  4064. (defvar org-clock-marker (make-marker)
  4065. "Marker recording the last clock-in.")
  4066. (defvar org-clock-hd-marker (make-marker)
  4067. "Marker recording the last clock-in, but the headline position.")
  4068. (defvar org-clock-heading ""
  4069. "The heading of the current clock entry.")
  4070. (defun org-clock-is-active ()
  4071. "Return the buffer where the clock is currently running.
  4072. Return nil if no clock is running."
  4073. (marker-buffer org-clock-marker))
  4074. (defun org-check-running-clock ()
  4075. "Check if the current buffer contains the running clock.
  4076. If yes, offer to stop it and to save the buffer with the changes."
  4077. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4078. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4079. (buffer-name))))
  4080. (org-clock-out)
  4081. (when (y-or-n-p "Save changed buffer?")
  4082. (save-buffer))))
  4083. (defun org-clocktable-try-shift (dir n)
  4084. "Check if this line starts a clock table, if yes, shift the time block."
  4085. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4086. (org-clocktable-shift dir n)))
  4087. ;;;###autoload
  4088. (defun org-clock-persistence-insinuate ()
  4089. "Set up hooks for clock persistence."
  4090. (require 'org-clock)
  4091. (add-hook 'org-mode-hook 'org-clock-load)
  4092. (add-hook 'kill-emacs-hook 'org-clock-save))
  4093. (defgroup org-archive nil
  4094. "Options concerning archiving in Org-mode."
  4095. :tag "Org Archive"
  4096. :group 'org-structure)
  4097. (defcustom org-archive-location "%s_archive::"
  4098. "The location where subtrees should be archived.
  4099. The value of this variable is a string, consisting of two parts,
  4100. separated by a double-colon. The first part is a filename and
  4101. the second part is a headline.
  4102. When the filename is omitted, archiving happens in the same file.
  4103. %s in the filename will be replaced by the current file
  4104. name (without the directory part). Archiving to a different file
  4105. is useful to keep archived entries from contributing to the
  4106. Org Agenda.
  4107. The archived entries will be filed as subtrees of the specified
  4108. headline. When the headline is omitted, the subtrees are simply
  4109. filed away at the end of the file, as top-level entries. Also in
  4110. the heading you can use %s to represent the file name, this can be
  4111. useful when using the same archive for a number of different files.
  4112. Here are a few examples:
  4113. \"%s_archive::\"
  4114. If the current file is Projects.org, archive in file
  4115. Projects.org_archive, as top-level trees. This is the default.
  4116. \"::* Archived Tasks\"
  4117. Archive in the current file, under the top-level headline
  4118. \"* Archived Tasks\".
  4119. \"~/org/archive.org::\"
  4120. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4121. \"~/org/archive.org::* From %s\"
  4122. Archive in file ~/org/archive.org (absolute path), under headlines
  4123. \"From FILENAME\" where file name is the current file name.
  4124. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4125. The \"datetree/\" string is special, signifying to archive
  4126. items to the datetree. Items are placed in either the CLOSED
  4127. date of the item, or the current date if there is no CLOSED date.
  4128. The heading will be a subentry to the current date. There doesn't
  4129. need to be a heading, but there always needs to be a slash after
  4130. datetree. For example, to store archived items directly in the
  4131. datetree, use \"~/org/datetree.org::datetree/\".
  4132. \"basement::** Finished Tasks\"
  4133. Archive in file ./basement (relative path), as level 3 trees
  4134. below the level 2 heading \"** Finished Tasks\".
  4135. You may set this option on a per-file basis by adding to the buffer a
  4136. line like
  4137. #+ARCHIVE: basement::** Finished Tasks
  4138. You may also define it locally for a subtree by setting an ARCHIVE property
  4139. in the entry. If such a property is found in an entry, or anywhere up
  4140. the hierarchy, it will be used."
  4141. :group 'org-archive
  4142. :type 'string)
  4143. (defcustom org-agenda-skip-archived-trees t
  4144. "Non-nil means the agenda will skip any items located in archived trees.
  4145. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4146. variable is no longer recommended, you should leave it at the value t.
  4147. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4148. :group 'org-archive
  4149. :group 'org-agenda-skip
  4150. :type 'boolean)
  4151. (defcustom org-columns-skip-archived-trees t
  4152. "Non-nil means ignore archived trees when creating column view."
  4153. :group 'org-archive
  4154. :group 'org-properties
  4155. :type 'boolean)
  4156. (defcustom org-cycle-open-archived-trees nil
  4157. "Non-nil means `org-cycle' will open archived trees.
  4158. An archived tree is a tree marked with the tag ARCHIVE.
  4159. When nil, archived trees will stay folded. You can still open them with
  4160. normal outline commands like `show-all', but not with the cycling commands."
  4161. :group 'org-archive
  4162. :group 'org-cycle
  4163. :type 'boolean)
  4164. (defcustom org-sparse-tree-open-archived-trees nil
  4165. "Non-nil means sparse tree construction shows matches in archived trees.
  4166. When nil, matches in these trees are highlighted, but the trees are kept in
  4167. collapsed state."
  4168. :group 'org-archive
  4169. :group 'org-sparse-trees
  4170. :type 'boolean)
  4171. (defcustom org-sparse-tree-default-date-type nil
  4172. "The default date type when building a sparse tree.
  4173. When this is nil, a date is a scheduled or a deadline timestamp.
  4174. Otherwise, these types are allowed:
  4175. all: all timestamps
  4176. active: only active timestamps (<...>)
  4177. inactive: only inactive timestamps ([...])
  4178. scheduled: only scheduled timestamps
  4179. deadline: only deadline timestamps"
  4180. :type '(choice (const :tag "Scheduled or deadline" nil)
  4181. (const :tag "All timestamps" all)
  4182. (const :tag "Only active timestamps" active)
  4183. (const :tag "Only inactive timestamps" inactive)
  4184. (const :tag "Only scheduled timestamps" scheduled)
  4185. (const :tag "Only deadline timestamps" deadline)
  4186. (const :tag "Only closed timestamps" closed))
  4187. :version "25.1"
  4188. :package-version '(Org . "8.3")
  4189. :group 'org-sparse-trees)
  4190. (defun org-cycle-hide-archived-subtrees (state)
  4191. "Re-hide all archived subtrees after a visibility state change."
  4192. (when (and (not org-cycle-open-archived-trees)
  4193. (not (memq state '(overview folded))))
  4194. (save-excursion
  4195. (let* ((globalp (memq state '(contents all)))
  4196. (beg (if globalp (point-min) (point)))
  4197. (end (if globalp (point-max) (org-end-of-subtree t))))
  4198. (org-hide-archived-subtrees beg end)
  4199. (goto-char beg)
  4200. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4201. (message "%s" (substitute-command-keys
  4202. "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
  4203. (defun org-force-cycle-archived ()
  4204. "Cycle subtree even if it is archived."
  4205. (interactive)
  4206. (setq this-command 'org-cycle)
  4207. (let ((org-cycle-open-archived-trees t))
  4208. (call-interactively 'org-cycle)))
  4209. (defun org-hide-archived-subtrees (beg end)
  4210. "Re-hide all archived subtrees after a visibility state change."
  4211. (org-with-wide-buffer
  4212. (let ((case-fold-search nil)
  4213. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4214. (goto-char beg)
  4215. ;; Include headline point is currently on.
  4216. (beginning-of-line)
  4217. (while (and (< (point) end) (re-search-forward re end t))
  4218. (when (member org-archive-tag (org-get-tags))
  4219. (org-flag-subtree t)
  4220. (org-end-of-subtree t))))))
  4221. (declare-function outline-end-of-heading "outline" ())
  4222. (declare-function outline-flag-region "outline" (from to flag))
  4223. (defun org-flag-subtree (flag)
  4224. (save-excursion
  4225. (org-back-to-heading t)
  4226. (outline-end-of-heading)
  4227. (outline-flag-region (point)
  4228. (progn (org-end-of-subtree t) (point))
  4229. flag)))
  4230. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4231. ;; Declare Column View Code
  4232. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4233. (declare-function org-columns-compute "org-colview" (property))
  4234. ;; Declare ID code
  4235. (declare-function org-id-store-link "org-id")
  4236. (declare-function org-id-locations-load "org-id")
  4237. (declare-function org-id-locations-save "org-id")
  4238. (defvar org-id-track-globally)
  4239. ;;; Variables for pre-computed regular expressions, all buffer local
  4240. (defvar-local org-todo-regexp nil
  4241. "Matches any of the TODO state keywords.")
  4242. (defvar-local org-not-done-regexp nil
  4243. "Matches any of the TODO state keywords except the last one.")
  4244. (defvar-local org-not-done-heading-regexp nil
  4245. "Matches a TODO headline that is not done.")
  4246. (defvar-local org-todo-line-regexp nil
  4247. "Matches a headline and puts TODO state into group 2 if present.")
  4248. (defvar-local org-complex-heading-regexp nil
  4249. "Matches a headline and puts everything into groups:
  4250. group 1: the stars
  4251. group 2: The todo keyword, maybe
  4252. group 3: Priority cookie
  4253. group 4: True headline
  4254. group 5: Tags")
  4255. (defvar-local org-complex-heading-regexp-format nil
  4256. "Printf format to make regexp to match an exact headline.
  4257. This regexp will match the headline of any node which has the
  4258. exact headline text that is put into the format, but may have any
  4259. TODO state, priority and tags.")
  4260. (defvar-local org-todo-line-tags-regexp nil
  4261. "Matches a headline and puts TODO state into group 2 if present.
  4262. Also put tags into group 4 if tags are present.")
  4263. (defconst org-plain-time-of-day-regexp
  4264. (concat
  4265. "\\(\\<[012]?[0-9]"
  4266. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4267. "\\(--?"
  4268. "\\(\\<[012]?[0-9]"
  4269. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4270. "\\)?")
  4271. "Regular expression to match a plain time or time range.
  4272. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4273. groups carry important information:
  4274. 0 the full match
  4275. 1 the first time, range or not
  4276. 8 the second time, if it is a range.")
  4277. (defconst org-plain-time-extension-regexp
  4278. (concat
  4279. "\\(\\<[012]?[0-9]"
  4280. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4281. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4282. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4283. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4284. groups carry important information:
  4285. 0 the full match
  4286. 7 hours of duration
  4287. 9 minutes of duration")
  4288. (defconst org-stamp-time-of-day-regexp
  4289. (concat
  4290. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4291. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4292. "\\(--?"
  4293. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4294. "Regular expression to match a timestamp time or time range.
  4295. After a match, the following groups carry important information:
  4296. 0 the full match
  4297. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4298. 2 the first time, range or not
  4299. 4 the second time, if it is a range.")
  4300. (defconst org-startup-options
  4301. '(("fold" org-startup-folded t)
  4302. ("overview" org-startup-folded t)
  4303. ("nofold" org-startup-folded nil)
  4304. ("showall" org-startup-folded nil)
  4305. ("showeverything" org-startup-folded showeverything)
  4306. ("content" org-startup-folded content)
  4307. ("indent" org-startup-indented t)
  4308. ("noindent" org-startup-indented nil)
  4309. ("hidestars" org-hide-leading-stars t)
  4310. ("showstars" org-hide-leading-stars nil)
  4311. ("odd" org-odd-levels-only t)
  4312. ("oddeven" org-odd-levels-only nil)
  4313. ("align" org-startup-align-all-tables t)
  4314. ("noalign" org-startup-align-all-tables nil)
  4315. ("inlineimages" org-startup-with-inline-images t)
  4316. ("noinlineimages" org-startup-with-inline-images nil)
  4317. ("latexpreview" org-startup-with-latex-preview t)
  4318. ("nolatexpreview" org-startup-with-latex-preview nil)
  4319. ("customtime" org-display-custom-times t)
  4320. ("logdone" org-log-done time)
  4321. ("lognotedone" org-log-done note)
  4322. ("nologdone" org-log-done nil)
  4323. ("lognoteclock-out" org-log-note-clock-out t)
  4324. ("nolognoteclock-out" org-log-note-clock-out nil)
  4325. ("logrepeat" org-log-repeat state)
  4326. ("lognoterepeat" org-log-repeat note)
  4327. ("logdrawer" org-log-into-drawer t)
  4328. ("nologdrawer" org-log-into-drawer nil)
  4329. ("logstatesreversed" org-log-states-order-reversed t)
  4330. ("nologstatesreversed" org-log-states-order-reversed nil)
  4331. ("nologrepeat" org-log-repeat nil)
  4332. ("logreschedule" org-log-reschedule time)
  4333. ("lognotereschedule" org-log-reschedule note)
  4334. ("nologreschedule" org-log-reschedule nil)
  4335. ("logredeadline" org-log-redeadline time)
  4336. ("lognoteredeadline" org-log-redeadline note)
  4337. ("nologredeadline" org-log-redeadline nil)
  4338. ("logrefile" org-log-refile time)
  4339. ("lognoterefile" org-log-refile note)
  4340. ("nologrefile" org-log-refile nil)
  4341. ("fninline" org-footnote-define-inline t)
  4342. ("nofninline" org-footnote-define-inline nil)
  4343. ("fnlocal" org-footnote-section nil)
  4344. ("fnauto" org-footnote-auto-label t)
  4345. ("fnprompt" org-footnote-auto-label nil)
  4346. ("fnconfirm" org-footnote-auto-label confirm)
  4347. ("fnplain" org-footnote-auto-label plain)
  4348. ("fnadjust" org-footnote-auto-adjust t)
  4349. ("nofnadjust" org-footnote-auto-adjust nil)
  4350. ("constcgs" constants-unit-system cgs)
  4351. ("constSI" constants-unit-system SI)
  4352. ("noptag" org-tag-persistent-alist nil)
  4353. ("hideblocks" org-hide-block-startup t)
  4354. ("nohideblocks" org-hide-block-startup nil)
  4355. ("beamer" org-startup-with-beamer-mode t)
  4356. ("entitiespretty" org-pretty-entities t)
  4357. ("entitiesplain" org-pretty-entities nil))
  4358. "Variable associated with STARTUP options for org-mode.
  4359. Each element is a list of three items: the startup options (as written
  4360. in the #+STARTUP line), the corresponding variable, and the value to set
  4361. this variable to if the option is found. An optional forth element PUSH
  4362. means to push this value onto the list in the variable.")
  4363. (defcustom org-group-tags t
  4364. "When non-nil (the default), use group tags.
  4365. This can be turned on/off through `org-toggle-tags-groups'."
  4366. :group 'org-tags
  4367. :group 'org-startup
  4368. :type 'boolean)
  4369. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4370. (defun org-toggle-tags-groups ()
  4371. "Toggle support for group tags.
  4372. Support for group tags is controlled by the option
  4373. `org-group-tags', which is non-nil by default."
  4374. (interactive)
  4375. (setq org-group-tags (not org-group-tags))
  4376. (cond ((and (derived-mode-p 'org-agenda-mode)
  4377. org-group-tags)
  4378. (org-agenda-redo))
  4379. ((derived-mode-p 'org-mode)
  4380. (let ((org-inhibit-startup t)) (org-mode))))
  4381. (message "Groups tags support has been turned %s"
  4382. (if org-group-tags "on" "off")))
  4383. (defun org-set-regexps-and-options (&optional tags-only)
  4384. "Precompute regular expressions used in the current buffer.
  4385. When optional argument TAGS-ONLY is non-nil, only compute tags
  4386. related expressions."
  4387. (when (derived-mode-p 'org-mode)
  4388. (let ((alist (org--setup-collect-keywords
  4389. (org-make-options-regexp
  4390. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4391. (and (not tags-only)
  4392. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4393. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4394. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4395. ;; Startup options. Get this early since it does change
  4396. ;; behavior for other options (e.g., tags).
  4397. (let ((startup (cdr (assq 'startup alist))))
  4398. (dolist (option startup)
  4399. (let ((entry (assoc-string option org-startup-options t)))
  4400. (when entry
  4401. (let ((var (nth 1 entry))
  4402. (val (nth 2 entry)))
  4403. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4404. (unless (listp (symbol-value var))
  4405. (set (make-local-variable var) nil))
  4406. (add-to-list var val)))))))
  4407. (setq-local org-file-tags
  4408. (mapcar #'org-add-prop-inherited
  4409. (cdr (assq 'filetags alist))))
  4410. (setq org-current-tag-alist
  4411. (append org-tag-persistent-alist
  4412. (let ((tags (cdr (assq 'tags alist))))
  4413. (if tags (org-tag-string-to-alist tags)
  4414. org-tag-alist))))
  4415. (setq org-tag-groups-alist
  4416. (org-tag-alist-to-groups org-current-tag-alist))
  4417. (unless tags-only
  4418. ;; File properties.
  4419. (setq-local org-file-properties (cdr (assq 'property alist)))
  4420. ;; Archive location.
  4421. (let ((archive (cdr (assq 'archive alist))))
  4422. (when archive (setq-local org-archive-location archive)))
  4423. ;; Category.
  4424. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4425. (when cat
  4426. (setq-local org-category (intern cat))
  4427. (setq-local org-file-properties
  4428. (org--update-property-plist
  4429. "CATEGORY" cat org-file-properties))))
  4430. ;; Columns.
  4431. (let ((column (cdr (assq 'columns alist))))
  4432. (when column (setq-local org-columns-default-format column)))
  4433. ;; Constants.
  4434. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4435. ;; Link abbreviations.
  4436. (let ((links (cdr (assq 'link alist))))
  4437. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4438. ;; Priorities.
  4439. (let ((priorities (cdr (assq 'priorities alist))))
  4440. (when priorities
  4441. (setq-local org-highest-priority (nth 0 priorities))
  4442. (setq-local org-lowest-priority (nth 1 priorities))
  4443. (setq-local org-default-priority (nth 2 priorities))))
  4444. ;; Scripts.
  4445. (let ((scripts (assq 'scripts alist)))
  4446. (when scripts
  4447. (setq-local org-use-sub-superscripts (cdr scripts))))
  4448. ;; TODO keywords.
  4449. (setq-local org-todo-kwd-alist nil)
  4450. (setq-local org-todo-key-alist nil)
  4451. (setq-local org-todo-key-trigger nil)
  4452. (setq-local org-todo-keywords-1 nil)
  4453. (setq-local org-done-keywords nil)
  4454. (setq-local org-todo-heads nil)
  4455. (setq-local org-todo-sets nil)
  4456. (setq-local org-todo-log-states nil)
  4457. (let ((todo-sequences
  4458. (or (nreverse (cdr (assq 'todo alist)))
  4459. (let ((d (default-value 'org-todo-keywords)))
  4460. (if (not (stringp (car d))) d
  4461. ;; XXX: Backward compatibility code.
  4462. (list (cons org-todo-interpretation d)))))))
  4463. (dolist (sequence todo-sequences)
  4464. (let* ((sequence (or (run-hook-with-args-until-success
  4465. 'org-todo-setup-filter-hook sequence)
  4466. sequence))
  4467. (sequence-type (car sequence))
  4468. (keywords (cdr sequence))
  4469. (sep (member "|" keywords))
  4470. names alist)
  4471. (dolist (k (remove "|" keywords))
  4472. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4473. k)
  4474. (error "Invalid TODO keyword %s" k))
  4475. (let ((name (match-string 1 k))
  4476. (key (match-string 2 k))
  4477. (log (org-extract-log-state-settings k)))
  4478. (push name names)
  4479. (push (cons name (and key (string-to-char key))) alist)
  4480. (when log (push log org-todo-log-states))))
  4481. (let* ((names (nreverse names))
  4482. (done (if sep (org-remove-keyword-keys (cdr sep))
  4483. (last names)))
  4484. (head (car names))
  4485. (tail (list sequence-type head (car done) (org-last done))))
  4486. (add-to-list 'org-todo-heads head 'append)
  4487. (push names org-todo-sets)
  4488. (setq org-done-keywords (append org-done-keywords done nil))
  4489. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4490. (setq org-todo-key-alist
  4491. (append org-todo-key-alist
  4492. (and alist
  4493. (append '((:startgroup))
  4494. (nreverse alist)
  4495. '((:endgroup))))))
  4496. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4497. (setq org-todo-sets (nreverse org-todo-sets)
  4498. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4499. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4500. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4501. ;; Compute the regular expressions and other local variables.
  4502. ;; Using `org-outline-regexp-bol' would complicate them much,
  4503. ;; because of the fixed white space at the end of that string.
  4504. (unless org-done-keywords
  4505. (setq org-done-keywords
  4506. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4507. (setq org-not-done-keywords
  4508. (org-delete-all org-done-keywords
  4509. (copy-sequence org-todo-keywords-1))
  4510. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4511. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4512. org-not-done-heading-regexp
  4513. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4514. org-todo-line-regexp
  4515. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4516. org-complex-heading-regexp
  4517. (concat "^\\(\\*+\\)"
  4518. "\\(?: +" org-todo-regexp "\\)?"
  4519. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4520. "\\(?: +\\(.*?\\)\\)??"
  4521. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4522. "[ \t]*$")
  4523. org-complex-heading-regexp-format
  4524. (concat "^\\(\\*+\\)"
  4525. "\\(?: +" org-todo-regexp "\\)?"
  4526. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4527. "\\(?: +"
  4528. ;; Stats cookies can be stuck to body.
  4529. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4530. "\\(%s\\)"
  4531. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4532. "\\)"
  4533. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4534. "[ \t]*$")
  4535. org-todo-line-tags-regexp
  4536. (concat "^\\(\\*+\\)"
  4537. "\\(?: +" org-todo-regexp "\\)?"
  4538. "\\(?: +\\(.*?\\)\\)??"
  4539. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4540. "[ \t]*$"))
  4541. (org-compute-latex-and-related-regexp)))))
  4542. (defun org--setup-collect-keywords (regexp &optional files alist)
  4543. "Return setup keywords values as an alist.
  4544. REGEXP matches a subset of setup keywords. FILES is a list of
  4545. file names already visited. It is used to avoid circular setup
  4546. files. ALIST, when non-nil, is the alist computed so far.
  4547. Return value contains the following keys: `archive', `category',
  4548. `columns', `constants', `filetags', `link', `priorities',
  4549. `property', `scripts', `startup', `tags' and `todo'."
  4550. (org-with-wide-buffer
  4551. (goto-char (point-min))
  4552. (let ((case-fold-search t))
  4553. (while (re-search-forward regexp nil t)
  4554. (let ((element (org-element-at-point)))
  4555. (when (eq (org-element-type element) 'keyword)
  4556. (let ((key (org-element-property :key element))
  4557. (value (org-element-property :value element)))
  4558. (cond
  4559. ((equal key "ARCHIVE")
  4560. (when (org-string-nw-p value)
  4561. (push (cons 'archive value) alist)))
  4562. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4563. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4564. ((equal key "CONSTANTS")
  4565. (let* ((constants (assq 'constants alist))
  4566. (store (cdr constants)))
  4567. (dolist (pair (org-split-string value))
  4568. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4569. pair)
  4570. (let* ((name (match-string 1 pair))
  4571. (value (match-string 2 pair))
  4572. (old (assoc name store)))
  4573. (if old (setcdr old value)
  4574. (push (cons name value) store)))))
  4575. (if constants (setcdr constants store)
  4576. (push (cons 'constants store) alist))))
  4577. ((equal key "FILETAGS")
  4578. (when (org-string-nw-p value)
  4579. (let ((old (assq 'filetags alist))
  4580. (new (apply #'nconc
  4581. (mapcar (lambda (x) (org-split-string x ":"))
  4582. (org-split-string value)))))
  4583. (if old (setcdr old (append new (cdr old)))
  4584. (push (cons 'filetags new) alist)))))
  4585. ((equal key "LINK")
  4586. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4587. (let ((links (assq 'link alist))
  4588. (pair (cons (match-string-no-properties 1 value)
  4589. (match-string-no-properties 2 value))))
  4590. (if links (push pair (cdr links))
  4591. (push (list 'link pair) alist)))))
  4592. ((equal key "OPTIONS")
  4593. (when (and (org-string-nw-p value)
  4594. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4595. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4596. ((equal key "PRIORITIES")
  4597. (push (cons 'priorities
  4598. (let ((prio (org-split-string value)))
  4599. (if (< (length prio) 3) '(?A ?C ?B)
  4600. (mapcar #'string-to-char prio))))
  4601. alist))
  4602. ((equal key "PROPERTY")
  4603. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4604. (let* ((property (assq 'property alist))
  4605. (value (org--update-property-plist
  4606. (match-string-no-properties 1 value)
  4607. (match-string-no-properties 2 value)
  4608. (cdr property))))
  4609. (if property (setcdr property value)
  4610. (push (cons 'property value) alist)))))
  4611. ((equal key "STARTUP")
  4612. (let ((startup (assq 'startup alist)))
  4613. (if startup
  4614. (setcdr startup
  4615. (append (cdr startup) (org-split-string value)))
  4616. (push (cons 'startup (org-split-string value)) alist))))
  4617. ((equal key "TAGS")
  4618. (let ((tag-cell (assq 'tags alist)))
  4619. (if tag-cell
  4620. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4621. (push (cons 'tags value) alist))))
  4622. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4623. (let ((todo (assq 'todo alist))
  4624. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4625. (org-split-string value))))
  4626. (if todo (push value (cdr todo))
  4627. (push (list 'todo value) alist))))
  4628. ((equal key "SETUPFILE")
  4629. (unless buffer-read-only ; Do not check in Gnus messages.
  4630. (let ((f (and (org-string-nw-p value)
  4631. (expand-file-name
  4632. (org-remove-double-quotes value)))))
  4633. (when (and f (file-readable-p f) (not (member f files)))
  4634. (with-temp-buffer
  4635. (setq default-directory (file-name-directory f))
  4636. (insert-file-contents f)
  4637. (setq alist
  4638. ;; Fake Org mode to benefit from cache
  4639. ;; without recurring needlessly.
  4640. (let ((major-mode 'org-mode))
  4641. (org--setup-collect-keywords
  4642. regexp (cons f files) alist)))))))))))))))
  4643. alist)
  4644. (defun org-tag-string-to-alist (s)
  4645. "Return tag alist associated to string S.
  4646. S is a value for TAGS keyword or produced with
  4647. `org-tag-alist-to-string'. Return value is an alist suitable for
  4648. `org-tag-alist' or `org-tag-persistent-alist'."
  4649. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4650. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4651. "\\|{.+?}\\)" ; regular expression
  4652. "\\(?:(\\(.\\))\\)?\\'"))
  4653. alist group-flag)
  4654. (dolist (tokens lines (cdr (nreverse alist)))
  4655. (push '(:newline) alist)
  4656. (while tokens
  4657. (let ((token (pop tokens)))
  4658. (pcase token
  4659. ("{"
  4660. (push '(:startgroup) alist)
  4661. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4662. ("}"
  4663. (push '(:endgroup) alist)
  4664. (setq group-flag nil))
  4665. ("["
  4666. (push '(:startgrouptag) alist)
  4667. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4668. ("]"
  4669. (push '(:endgrouptag) alist)
  4670. (setq group-flag nil))
  4671. (":"
  4672. (push '(:grouptags) alist))
  4673. ((guard (string-match tag-re token))
  4674. (let ((tag (match-string 1 token))
  4675. (key (and (match-beginning 2)
  4676. (string-to-char (match-string 2 token)))))
  4677. ;; Push all tags in groups, no matter if they already
  4678. ;; appear somewhere else in the list.
  4679. (when (or group-flag (not (assoc tag alist)))
  4680. (push (cons tag key) alist))))))))))
  4681. (defun org-tag-alist-to-string (alist &optional skip-key)
  4682. "Return tag string associated to ALIST.
  4683. ALIST is an alist, as defined in `org-tag-alist' or
  4684. `org-tag-persistent-alist', or produced with
  4685. `org-tag-string-to-alist'.
  4686. Return value is a string suitable as a value for \"TAGS\"
  4687. keyword.
  4688. When optional argument SKIP-KEY is non-nil, skip selection keys
  4689. next to tags."
  4690. (mapconcat (lambda (token)
  4691. (pcase token
  4692. (`(:startgroup) "{")
  4693. (`(:endgroup) "}")
  4694. (`(:startgrouptag) "[")
  4695. (`(:endgrouptag) "]")
  4696. (`(:grouptags) ":")
  4697. (`(:newline) "\\n")
  4698. ((and
  4699. (guard (not skip-key))
  4700. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4701. (format "%s(%c)" tag key))
  4702. (`(,(and tag (pred stringp)) . ,_) tag)
  4703. (_ (user-error "Invalid tag token: %S" token))))
  4704. alist
  4705. " "))
  4706. (defun org-tag-alist-to-groups (alist)
  4707. "Return group alist from tag ALIST.
  4708. ALIST is an alist, as defined in `org-tag-alist' or
  4709. `org-tag-persistent-alist', or produced with
  4710. `org-tag-string-to-alist'. Return value is an alist following
  4711. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4712. a string, summarizing TAGS, as a list of strings."
  4713. (let (groups group-status current-group)
  4714. (dolist (token alist (nreverse groups))
  4715. (pcase token
  4716. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4717. (`(,(or :endgroup :endgrouptag))
  4718. (when (eq group-status 'append)
  4719. (push (nreverse current-group) groups))
  4720. (setq group-status nil))
  4721. (`(:grouptags) (setq group-status 'append))
  4722. ((and `(,tag . ,_) (guard group-status))
  4723. (if (eq group-status 'append) (push tag current-group)
  4724. (setq current-group (list tag))))
  4725. (_ nil)))))
  4726. (defun org-file-contents (file &optional noerror)
  4727. "Return the contents of FILE, as a string."
  4728. (if (and file (file-readable-p file))
  4729. (with-temp-buffer
  4730. (insert-file-contents file)
  4731. (buffer-string))
  4732. (funcall (if noerror 'message 'error)
  4733. "Cannot read file \"%s\"%s"
  4734. file
  4735. (let ((from (buffer-file-name (buffer-base-buffer))))
  4736. (if from (concat " (referenced in file \"" from "\")") "")))))
  4737. (defun org-extract-log-state-settings (x)
  4738. "Extract the log state setting from a TODO keyword string.
  4739. This will extract info from a string like \"WAIT(w@/!)\"."
  4740. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4741. (let ((kw (match-string 1 x))
  4742. (log1 (and (match-end 3) (match-string 3 x)))
  4743. (log2 (and (match-end 4) (match-string 4 x))))
  4744. (and (or log1 log2)
  4745. (list kw
  4746. (and log1 (if (equal log1 "!") 'time 'note))
  4747. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4748. (defun org-remove-keyword-keys (list)
  4749. "Remove a pair of parenthesis at the end of each string in LIST."
  4750. (mapcar (lambda (x)
  4751. (if (string-match "(.*)$" x)
  4752. (substring x 0 (match-beginning 0))
  4753. x))
  4754. list))
  4755. (defun org-assign-fast-keys (alist)
  4756. "Assign fast keys to a keyword-key alist.
  4757. Respect keys that are already there."
  4758. (let (new e (alt ?0))
  4759. (while (setq e (pop alist))
  4760. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4761. (cdr e)) ;; Key already assigned.
  4762. (push e new)
  4763. (let ((clist (string-to-list (downcase (car e))))
  4764. (used (append new alist)))
  4765. (when (= (car clist) ?@)
  4766. (pop clist))
  4767. (while (and clist (rassoc (car clist) used))
  4768. (pop clist))
  4769. (unless clist
  4770. (while (rassoc alt used)
  4771. (cl-incf alt)))
  4772. (push (cons (car e) (or (car clist) alt)) new))))
  4773. (nreverse new)))
  4774. ;;; Some variables used in various places
  4775. (defvar org-window-configuration nil
  4776. "Used in various places to store a window configuration.")
  4777. (defvar org-selected-window nil
  4778. "Used in various places to store a window configuration.")
  4779. (defvar org-finish-function nil
  4780. "Function to be called when `C-c C-c' is used.
  4781. This is for getting out of special buffers like capture.")
  4782. (defvar org-last-state)
  4783. ;; Defined somewhere in this file, but used before definition.
  4784. (defvar org-entities) ;; defined in org-entities.el
  4785. (defvar org-struct-menu)
  4786. (defvar org-org-menu)
  4787. (defvar org-tbl-menu)
  4788. ;;;; Define the Org mode
  4789. ;; We use a before-change function to check if a table might need
  4790. ;; an update.
  4791. (defvar org-table-may-need-update t
  4792. "Indicates that a table might need an update.
  4793. This variable is set by `org-before-change-function'.
  4794. `org-table-align' sets it back to nil.")
  4795. (defun org-before-change-function (_beg _end)
  4796. "Every change indicates that a table might need an update."
  4797. (setq org-table-may-need-update t))
  4798. (defvar org-mode-map)
  4799. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4800. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4801. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4802. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4803. (defvar org-table-buffer-is-an nil)
  4804. (defvar bidi-paragraph-direction)
  4805. (defvar buffer-face-mode-face)
  4806. (require 'outline)
  4807. ;; Other stuff we need.
  4808. (require 'time-date)
  4809. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4810. (require 'easymenu)
  4811. (autoload 'easy-menu-add "easymenu")
  4812. (require 'overlay)
  4813. ;; (require 'org-macs) moved higher up in the file before it is first used
  4814. (require 'org-entities)
  4815. ;; (require 'org-compat) moved higher up in the file before it is first used
  4816. (require 'org-faces)
  4817. (require 'org-list)
  4818. (require 'org-pcomplete)
  4819. (require 'org-src)
  4820. (require 'org-footnote)
  4821. (require 'org-macro)
  4822. ;; babel
  4823. (require 'ob)
  4824. ;;;###autoload
  4825. (define-derived-mode org-mode outline-mode "Org"
  4826. "Outline-based notes management and organizer, alias
  4827. \"Carsten's outline-mode for keeping track of everything.\"
  4828. Org mode develops organizational tasks around a NOTES file which
  4829. contains information about projects as plain text. Org mode is
  4830. implemented on top of Outline mode, which is ideal to keep the content
  4831. of large files well structured. It supports ToDo items, deadlines and
  4832. time stamps, which magically appear in the diary listing of the Emacs
  4833. calendar. Tables are easily created with a built-in table editor.
  4834. Plain text URL-like links connect to websites, emails (VM), Usenet
  4835. messages (Gnus), BBDB entries, and any files related to the project.
  4836. For printing and sharing of notes, an Org file (or a part of it)
  4837. can be exported as a structured ASCII or HTML file.
  4838. The following commands are available:
  4839. \\{org-mode-map}"
  4840. ;; Get rid of Outline menus, they are not needed
  4841. ;; Need to do this here because define-derived-mode sets up
  4842. ;; the keymap so late. Still, it is a waste to call this each time
  4843. ;; we switch another buffer into Org mode.
  4844. (define-key org-mode-map [menu-bar headings] 'undefined)
  4845. (define-key org-mode-map [menu-bar hide] 'undefined)
  4846. (define-key org-mode-map [menu-bar show] 'undefined)
  4847. (org-load-modules-maybe)
  4848. (org-install-agenda-files-menu)
  4849. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4850. (add-to-invisibility-spec '(org-cwidth))
  4851. (add-to-invisibility-spec '(org-hide-block . t))
  4852. (setq-local outline-regexp org-outline-regexp)
  4853. (setq-local outline-level 'org-outline-level)
  4854. (setq bidi-paragraph-direction 'left-to-right)
  4855. (when (and org-ellipsis
  4856. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4857. (fboundp 'make-glyph-code))
  4858. (unless org-display-table
  4859. (setq org-display-table (make-display-table)))
  4860. (set-display-table-slot
  4861. org-display-table 4
  4862. (vconcat (mapcar
  4863. (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
  4864. org-ellipsis)))
  4865. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4866. (setq buffer-display-table org-display-table))
  4867. (org-set-regexps-and-options)
  4868. (org-set-font-lock-defaults)
  4869. (when (and org-tag-faces (not org-tags-special-faces-re))
  4870. ;; tag faces set outside customize.... force initialization.
  4871. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4872. ;; Calc embedded
  4873. (setq-local calc-embedded-open-mode "# ")
  4874. ;; Modify a few syntax entries
  4875. (modify-syntax-entry ?@ "w")
  4876. (modify-syntax-entry ?\" "\"")
  4877. (modify-syntax-entry ?\\ "_")
  4878. (modify-syntax-entry ?~ "_")
  4879. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4880. ;; Activate before-change-function
  4881. (setq-local org-table-may-need-update t)
  4882. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4883. ;; Check for running clock before killing a buffer
  4884. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4885. ;; Initialize macros templates.
  4886. (org-macro-initialize-templates)
  4887. ;; Initialize radio targets.
  4888. (org-update-radio-target-regexp)
  4889. ;; Indentation.
  4890. (setq-local indent-line-function 'org-indent-line)
  4891. (setq-local indent-region-function 'org-indent-region)
  4892. ;; Filling and auto-filling.
  4893. (org-setup-filling)
  4894. ;; Comments.
  4895. (org-setup-comments-handling)
  4896. ;; Initialize cache.
  4897. (org-element-cache-reset)
  4898. ;; Beginning/end of defun
  4899. (setq-local beginning-of-defun-function 'org-backward-element)
  4900. (setq-local end-of-defun-function
  4901. (lambda ()
  4902. (if (not (org-at-heading-p))
  4903. (org-forward-element)
  4904. (org-forward-element)
  4905. (forward-char -1))))
  4906. ;; Next error for sparse trees
  4907. (setq-local next-error-function 'org-occur-next-match)
  4908. ;; Make sure dependence stuff works reliably, even for users who set it
  4909. ;; too late :-(
  4910. (if org-enforce-todo-dependencies
  4911. (add-hook 'org-blocker-hook
  4912. 'org-block-todo-from-children-or-siblings-or-parent)
  4913. (remove-hook 'org-blocker-hook
  4914. 'org-block-todo-from-children-or-siblings-or-parent))
  4915. (if org-enforce-todo-checkbox-dependencies
  4916. (add-hook 'org-blocker-hook
  4917. 'org-block-todo-from-checkboxes)
  4918. (remove-hook 'org-blocker-hook
  4919. 'org-block-todo-from-checkboxes))
  4920. ;; Align options lines
  4921. (setq-local
  4922. align-mode-rules-list
  4923. '((org-in-buffer-settings
  4924. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4925. (modes . '(org-mode)))))
  4926. ;; Imenu
  4927. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4928. ;; Make isearch reveal context
  4929. (setq-local outline-isearch-open-invisible-function
  4930. (lambda (&rest _) (org-show-context 'isearch)))
  4931. ;; Setup the pcomplete hooks
  4932. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4933. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4934. (setq-local pcomplete-default-completion-function 'ignore)
  4935. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4936. (setq-local pcomplete-termination-string "")
  4937. (setq-local buffer-face-mode-face 'org-default)
  4938. ;; If empty file that did not turn on Org mode automatically, make
  4939. ;; it to.
  4940. (when (and org-insert-mode-line-in-empty-file
  4941. (called-interactively-p 'any)
  4942. (= (point-min) (point-max)))
  4943. (insert "# -*- mode: org -*-\n\n"))
  4944. (unless org-inhibit-startup
  4945. (org-unmodified
  4946. (when org-startup-with-beamer-mode (org-beamer-mode))
  4947. (when org-startup-align-all-tables
  4948. (org-table-map-tables #'org-table-align t))
  4949. (when org-startup-with-inline-images (org-display-inline-images))
  4950. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4951. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4952. (when org-startup-truncated (setq truncate-lines t))
  4953. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4954. (org-refresh-effort-properties)))
  4955. ;; Try to set `org-hide' face correctly.
  4956. (let ((foreground (org-find-invisible-foreground)))
  4957. (when foreground
  4958. (set-face-foreground 'org-hide foreground))))
  4959. ;; Update `customize-package-emacs-version-alist'
  4960. (add-to-list 'customize-package-emacs-version-alist
  4961. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4962. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4963. ("8.2.6" . "24.4") ("8.3" . "25.1")))
  4964. (defvar org-mode-transpose-word-syntax-table
  4965. (let ((st (make-syntax-table text-mode-syntax-table)))
  4966. (dolist (c org-emphasis-alist st)
  4967. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4968. (when (fboundp 'abbrev-table-put)
  4969. (abbrev-table-put org-mode-abbrev-table
  4970. :parents (list text-mode-abbrev-table)))
  4971. (defun org-find-invisible-foreground ()
  4972. (let ((candidates (remove
  4973. "unspecified-bg"
  4974. (nconc
  4975. (list (face-background 'default)
  4976. (face-background 'org-default))
  4977. (mapcar
  4978. (lambda (alist)
  4979. (when (boundp alist)
  4980. (cdr (assoc 'background-color (symbol-value alist)))))
  4981. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4982. (list (face-foreground 'org-hide))))))
  4983. (car (remove nil candidates))))
  4984. (defun org-current-time (&optional rounding-minutes past)
  4985. "Current time, possibly rounded to ROUNDING-MINUTES.
  4986. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4987. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4988. the rounding returns a past time."
  4989. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4990. (car org-time-stamp-rounding-minutes)))
  4991. (time (decode-time)) res)
  4992. (if (< r 1)
  4993. (current-time)
  4994. (setq res
  4995. (apply 'encode-time
  4996. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4997. (nthcdr 2 time))))
  4998. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4999. (seconds-to-time (- (float-time res) (* r 60)))
  5000. res))))
  5001. (defun org-today ()
  5002. "Return today date, considering `org-extend-today-until'."
  5003. (time-to-days
  5004. (time-subtract (current-time)
  5005. (list 0 (* 3600 org-extend-today-until) 0))))
  5006. ;;;; Font-Lock stuff, including the activators
  5007. (defvar org-mouse-map (make-sparse-keymap))
  5008. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  5009. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  5010. (when org-mouse-1-follows-link
  5011. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5012. (when org-tab-follows-link
  5013. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5014. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5015. (require 'font-lock)
  5016. (defconst org-non-link-chars "]\t\n\r<>")
  5017. (defvar org-link-types-re nil
  5018. "Matches a link that has a url-like prefix like \"http:\"")
  5019. (defvar org-link-re-with-space nil
  5020. "Matches a link with spaces, optional angular brackets around it.")
  5021. (defvar org-link-re-with-space2 nil
  5022. "Matches a link with spaces, optional angular brackets around it.")
  5023. (defvar org-link-re-with-space3 nil
  5024. "Matches a link with spaces, only for internal part in bracket links.")
  5025. (defvar org-angle-link-re nil
  5026. "Matches link with angular brackets, spaces are allowed.")
  5027. (defvar org-plain-link-re nil
  5028. "Matches plain link, without spaces.")
  5029. (defvar org-bracket-link-regexp nil
  5030. "Matches a link in double brackets.")
  5031. (defvar org-bracket-link-analytic-regexp nil
  5032. "Regular expression used to analyze links.
  5033. Here is what the match groups contain after a match:
  5034. 1: http:
  5035. 2: http
  5036. 3: path
  5037. 4: [desc]
  5038. 5: desc")
  5039. (defvar org-bracket-link-analytic-regexp++ nil
  5040. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5041. (defvar org-any-link-re nil
  5042. "Regular expression matching any link.")
  5043. (defconst org-match-sexp-depth 3
  5044. "Number of stacked braces for sub/superscript matching.")
  5045. (defun org-create-multibrace-regexp (left right n)
  5046. "Create a regular expression which will match a balanced sexp.
  5047. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5048. as single character strings.
  5049. The regexp returned will match the entire expression including the
  5050. delimiters. It will also define a single group which contains the
  5051. match except for the outermost delimiters. The maximum depth of
  5052. stacked delimiters is N. Escaping delimiters is not possible."
  5053. (let* ((nothing (concat "[^" left right "]*?"))
  5054. (or "\\|")
  5055. (re nothing)
  5056. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5057. (while (> n 1)
  5058. (setq n (1- n)
  5059. re (concat re or next)
  5060. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5061. (concat left "\\(" re "\\)" right)))
  5062. (defconst org-match-substring-regexp
  5063. (concat
  5064. "\\(\\S-\\)\\([_^]\\)\\("
  5065. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5066. "\\|"
  5067. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5068. "\\|"
  5069. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5070. "The regular expression matching a sub- or superscript.")
  5071. (defconst org-match-substring-with-braces-regexp
  5072. (concat
  5073. "\\(\\S-\\)\\([_^]\\)"
  5074. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5075. "The regular expression matching a sub- or superscript, forcing braces.")
  5076. (defun org-make-link-regexps ()
  5077. "Update the link regular expressions.
  5078. This should be called after the variable `org-link-parameters' has changed."
  5079. (let ((types-re (regexp-opt (org-link-types) t)))
  5080. (setq org-link-types-re
  5081. (concat "\\`" types-re ":")
  5082. org-link-re-with-space
  5083. (concat "<?" types-re ":"
  5084. "\\([^" org-non-link-chars " ]"
  5085. "[^" org-non-link-chars "]*"
  5086. "[^" org-non-link-chars " ]\\)>?")
  5087. org-link-re-with-space2
  5088. (concat "<?" types-re ":"
  5089. "\\([^" org-non-link-chars " ]"
  5090. "[^\t\n\r]*"
  5091. "[^" org-non-link-chars " ]\\)>?")
  5092. org-link-re-with-space3
  5093. (concat "<?" types-re ":"
  5094. "\\([^" org-non-link-chars " ]"
  5095. "[^\t\n\r]*\\)")
  5096. org-angle-link-re
  5097. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5098. types-re)
  5099. org-plain-link-re
  5100. (concat
  5101. "\\<" types-re ":"
  5102. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5103. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5104. org-bracket-link-regexp
  5105. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5106. org-bracket-link-analytic-regexp
  5107. (concat
  5108. "\\[\\["
  5109. "\\(" types-re ":\\)?"
  5110. "\\([^]]+\\)"
  5111. "\\]"
  5112. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5113. "\\]")
  5114. org-bracket-link-analytic-regexp++
  5115. (concat
  5116. "\\[\\["
  5117. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5118. "\\([^]]+\\)"
  5119. "\\]"
  5120. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5121. "\\]")
  5122. org-any-link-re
  5123. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5124. org-angle-link-re "\\)\\|\\("
  5125. org-plain-link-re "\\)"))))
  5126. (org-make-link-regexps)
  5127. (defvar org-emph-face nil)
  5128. (defun org-do-emphasis-faces (limit)
  5129. "Run through the buffer and emphasize strings."
  5130. (let (rtn a)
  5131. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5132. (let* ((border (char-after (match-beginning 3)))
  5133. (bre (regexp-quote (char-to-string border))))
  5134. (when (and (not (= border (char-after (match-beginning 4))))
  5135. (not (string-match-p (concat bre ".*" bre)
  5136. (replace-regexp-in-string
  5137. "\n" " "
  5138. (substring (match-string 2) 1 -1)))))
  5139. (setq rtn t)
  5140. (setq a (assoc (match-string 3) org-emphasis-alist))
  5141. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5142. 'face
  5143. (nth 1 a))
  5144. (and (nth 2 a)
  5145. (org-remove-flyspell-overlays-in
  5146. (match-beginning 0) (match-end 0)))
  5147. (add-text-properties (match-beginning 2) (match-end 2)
  5148. '(font-lock-multiline t org-emphasis t))
  5149. (when org-hide-emphasis-markers
  5150. (add-text-properties (match-end 4) (match-beginning 5)
  5151. '(invisible org-link))
  5152. (add-text-properties (match-beginning 3) (match-end 3)
  5153. '(invisible org-link)))))
  5154. (goto-char (1+ (match-beginning 0))))
  5155. rtn))
  5156. (defun org-emphasize (&optional char)
  5157. "Insert or change an emphasis, i.e. a font like bold or italic.
  5158. If there is an active region, change that region to a new emphasis.
  5159. If there is no region, just insert the marker characters and position
  5160. the cursor between them.
  5161. CHAR should be the marker character. If it is a space, it means to
  5162. remove the emphasis of the selected region.
  5163. If CHAR is not given (for example in an interactive call) it will be
  5164. prompted for."
  5165. (interactive)
  5166. (let ((erc org-emphasis-regexp-components)
  5167. (string "") beg end move s)
  5168. (if (org-region-active-p)
  5169. (setq beg (region-beginning)
  5170. end (region-end)
  5171. string (buffer-substring beg end))
  5172. (setq move t))
  5173. (unless char
  5174. (message "Emphasis marker or tag: [%s]"
  5175. (mapconcat #'car org-emphasis-alist ""))
  5176. (setq char (read-char-exclusive)))
  5177. (if (equal char ?\s)
  5178. (setq s ""
  5179. move nil)
  5180. (unless (assoc (char-to-string char) org-emphasis-alist)
  5181. (user-error "No such emphasis marker: \"%c\"" char))
  5182. (setq s (char-to-string char)))
  5183. (while (and (> (length string) 1)
  5184. (equal (substring string 0 1) (substring string -1))
  5185. (assoc (substring string 0 1) org-emphasis-alist))
  5186. (setq string (substring string 1 -1)))
  5187. (setq string (concat s string s))
  5188. (when beg (delete-region beg end))
  5189. (unless (or (bolp)
  5190. (string-match (concat "[" (nth 0 erc) "\n]")
  5191. (char-to-string (char-before (point)))))
  5192. (insert " "))
  5193. (unless (or (eobp)
  5194. (string-match (concat "[" (nth 1 erc) "\n]")
  5195. (char-to-string (char-after (point)))))
  5196. (insert " ") (backward-char 1))
  5197. (insert string)
  5198. (and move (backward-char 1))))
  5199. (defconst org-nonsticky-props
  5200. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5201. (defsubst org-rear-nonsticky-at (pos)
  5202. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5203. (defun org-activate-plain-links (limit)
  5204. "Add link properties for plain links."
  5205. (when (and (re-search-forward org-plain-link-re limit t)
  5206. (not (org-in-src-block-p)))
  5207. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5208. 'face))
  5209. (link (match-string-no-properties 0))
  5210. (type (match-string-no-properties 1))
  5211. (path (match-string-no-properties 2))
  5212. (link-start (match-beginning 0))
  5213. (link-end (match-end 0))
  5214. (link-face (org-link-get-parameter type :face))
  5215. (help-echo (org-link-get-parameter type :help-echo))
  5216. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5217. (activate-func (org-link-get-parameter type :activate-func)))
  5218. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5219. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5220. (add-text-properties (match-beginning 0) (match-end 0)
  5221. (list
  5222. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5223. 'highlight)
  5224. 'face (cond
  5225. ;; A function that returns a face
  5226. ((functionp link-face)
  5227. (funcall link-face path))
  5228. ;; a face
  5229. ((facep link-face)
  5230. link-face)
  5231. ;; An anonymous face
  5232. ((consp link-face)
  5233. link-face)
  5234. ;; default
  5235. (t
  5236. 'org-link))
  5237. 'help-echo (cond
  5238. ((stringp help-echo)
  5239. help-echo)
  5240. ((functionp help-echo)
  5241. help-echo)
  5242. (t
  5243. (concat "LINK: "
  5244. (save-match-data
  5245. (org-link-unescape link)))))
  5246. 'htmlize-link (cond
  5247. ((functionp htmlize-link)
  5248. (funcall htmlize-link path))
  5249. (t
  5250. `(:uri ,link)))
  5251. 'keymap (or (org-link-get-parameter type :keymap)
  5252. org-mouse-map)
  5253. 'org-link-start (match-beginning 0)))
  5254. (org-rear-nonsticky-at (match-end 0))
  5255. (when activate-func
  5256. (funcall activate-func link-start link-end path nil))
  5257. t))))
  5258. (defun org-activate-code (limit)
  5259. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5260. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5261. (remove-text-properties (match-beginning 0) (match-end 0)
  5262. '(display t invisible t intangible t))
  5263. t))
  5264. (defcustom org-src-fontify-natively t
  5265. "When non-nil, fontify code in code blocks.
  5266. See also the `org-block' face."
  5267. :type 'boolean
  5268. :version "24.4"
  5269. :package-version '(Org . "8.3")
  5270. :group 'org-appearance
  5271. :group 'org-babel)
  5272. (defcustom org-allow-promoting-top-level-subtree nil
  5273. "When non-nil, allow promoting a top level subtree.
  5274. The leading star of the top level headline will be replaced
  5275. by a #."
  5276. :type 'boolean
  5277. :version "24.1"
  5278. :group 'org-appearance)
  5279. (defun org-fontify-meta-lines-and-blocks (limit)
  5280. (condition-case nil
  5281. (org-fontify-meta-lines-and-blocks-1 limit)
  5282. (error (message "org-mode fontification error in %S at %d"
  5283. (current-buffer)
  5284. (line-number-at-pos)))))
  5285. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5286. "Fontify #+ lines and blocks."
  5287. (let ((case-fold-search t))
  5288. (when (re-search-forward
  5289. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5290. limit t)
  5291. (let ((beg (match-beginning 0))
  5292. (block-start (match-end 0))
  5293. (block-end nil)
  5294. (lang (match-string 7))
  5295. (beg1 (line-beginning-position 2))
  5296. (dc1 (downcase (match-string 2)))
  5297. (dc3 (downcase (match-string 3)))
  5298. end end1 quoting block-type)
  5299. (cond
  5300. ((and (match-end 4) (equal dc3 "+begin"))
  5301. ;; Truly a block
  5302. (setq block-type (downcase (match-string 5))
  5303. quoting (member block-type org-protecting-blocks))
  5304. (when (re-search-forward
  5305. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5306. nil t) ;; on purpose, we look further than LIMIT
  5307. (setq end (min (point-max) (match-end 0))
  5308. end1 (min (point-max) (1- (match-beginning 0))))
  5309. (setq block-end (match-beginning 0))
  5310. (when quoting
  5311. (org-remove-flyspell-overlays-in beg1 end1)
  5312. (remove-text-properties beg end
  5313. '(display t invisible t intangible t)))
  5314. (add-text-properties
  5315. beg end '(font-lock-fontified t font-lock-multiline t))
  5316. (add-text-properties beg beg1 '(face org-meta-line))
  5317. (org-remove-flyspell-overlays-in beg beg1)
  5318. (add-text-properties ; For end_src
  5319. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5320. (org-remove-flyspell-overlays-in end1 end)
  5321. (cond
  5322. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5323. (org-src-font-lock-fontify-block lang block-start block-end)
  5324. (add-text-properties beg1 block-end '(src-block t)))
  5325. (quoting
  5326. (add-text-properties beg1 (min (point-max) (1+ end1))
  5327. (list 'face
  5328. (list :inherit
  5329. (let ((face-name
  5330. (intern (format "org-block-%s" lang))))
  5331. (append (and (facep face-name) (list face-name))
  5332. '(org-block))))))) ; end of source block
  5333. ((not org-fontify-quote-and-verse-blocks))
  5334. ((string= block-type "quote")
  5335. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5336. ((string= block-type "verse")
  5337. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5338. (add-text-properties beg beg1 '(face org-block-begin-line))
  5339. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5340. '(face org-block-end-line))
  5341. t))
  5342. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5343. (org-remove-flyspell-overlays-in
  5344. (match-beginning 0)
  5345. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5346. (add-text-properties
  5347. beg (match-end 3)
  5348. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5349. '(font-lock-fontified t invisible t)
  5350. '(font-lock-fontified t face org-document-info-keyword)))
  5351. (add-text-properties
  5352. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5353. (if (string-equal dc1 "+title:")
  5354. '(font-lock-fontified t face org-document-title)
  5355. '(font-lock-fontified t face org-document-info))))
  5356. ((equal dc1 "+caption:")
  5357. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5358. (remove-text-properties (match-beginning 0) (match-end 0)
  5359. '(display t invisible t intangible t))
  5360. (add-text-properties (match-beginning 1) (match-end 3)
  5361. '(font-lock-fontified t face org-meta-line))
  5362. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5363. '(font-lock-fontified t face org-block))
  5364. t)
  5365. ((member dc3 '(" " ""))
  5366. (org-remove-flyspell-overlays-in beg (match-end 0))
  5367. (add-text-properties
  5368. beg (match-end 0)
  5369. '(font-lock-fontified t face font-lock-comment-face)))
  5370. (t ;; just any other in-buffer setting, but not indented
  5371. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5372. (remove-text-properties (match-beginning 0) (match-end 0)
  5373. '(display t invisible t intangible t))
  5374. (add-text-properties beg (match-end 0)
  5375. '(font-lock-fontified t face org-meta-line))
  5376. t))))))
  5377. (defun org-fontify-drawers (limit)
  5378. "Fontify drawers."
  5379. (when (re-search-forward org-drawer-regexp limit t)
  5380. (add-text-properties
  5381. (match-beginning 0) (match-end 0)
  5382. '(font-lock-fontified t face org-special-keyword))
  5383. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5384. t))
  5385. (defun org-fontify-macros (limit)
  5386. "Fontify macros."
  5387. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5388. (add-text-properties
  5389. (match-beginning 0) (match-end 0)
  5390. '(font-lock-fontified t face org-macro))
  5391. (when org-hide-macro-markers
  5392. (add-text-properties (match-end 2) (match-beginning 2)
  5393. '(invisible t))
  5394. (add-text-properties (match-beginning 1) (match-end 1)
  5395. '(invisible t)))
  5396. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5397. t))
  5398. (defun org-activate-angle-links (limit)
  5399. "Add text properties for angle links."
  5400. (when (and (re-search-forward org-angle-link-re limit t)
  5401. (not (org-in-src-block-p)))
  5402. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5403. (add-text-properties (match-beginning 0) (match-end 0)
  5404. (list 'mouse-face 'highlight
  5405. 'keymap org-mouse-map
  5406. 'font-lock-multiline t))
  5407. (org-rear-nonsticky-at (match-end 0))
  5408. t))
  5409. (defun org-activate-footnote-links (limit)
  5410. "Add text properties for footnotes."
  5411. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5412. (when fn
  5413. (let* ((beg (nth 1 fn))
  5414. (end (nth 2 fn))
  5415. (label (car fn))
  5416. (referencep (/= (line-beginning-position) beg)))
  5417. (when (and referencep (nth 3 fn))
  5418. (save-excursion
  5419. (goto-char beg)
  5420. (search-forward (or label "fn:"))
  5421. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5422. (add-text-properties beg end
  5423. (list 'mouse-face 'highlight
  5424. 'keymap org-mouse-map
  5425. 'help-echo
  5426. (if referencep "Footnote reference"
  5427. "Footnote definition")
  5428. 'font-lock-fontified t
  5429. 'font-lock-multiline t
  5430. 'face 'org-footnote))))))
  5431. (defun org-activate-bracket-links (limit)
  5432. "Add text properties for bracketed links."
  5433. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5434. (not (org-in-src-block-p)))
  5435. (let* ((hl (save-match-data
  5436. (org-link-expand-abbrev (match-string-no-properties 1))))
  5437. (type (save-match-data
  5438. (and (string-match org-plain-link-re hl)
  5439. (match-string-no-properties 1 hl))))
  5440. (path (save-match-data
  5441. (and (string-match org-plain-link-re hl)
  5442. (match-string-no-properties 2 hl))))
  5443. (link-start (match-beginning 0))
  5444. (link-end (match-end 0))
  5445. (bracketp t)
  5446. (help-echo (org-link-get-parameter type :help-echo))
  5447. (help (cond
  5448. ((stringp help-echo)
  5449. help-echo)
  5450. ((functionp help-echo)
  5451. help-echo)
  5452. (t
  5453. (concat "LINK: "
  5454. (save-match-data
  5455. (org-link-unescape hl))))))
  5456. (link-face (org-link-get-parameter type :face))
  5457. (face (cond
  5458. ;; A function that returns a face
  5459. ((functionp link-face)
  5460. (funcall link-face path))
  5461. ;; a face
  5462. ((facep link-face)
  5463. link-face)
  5464. ;; An anonymous face
  5465. ((consp link-face)
  5466. link-face)
  5467. ;; default
  5468. (t
  5469. 'org-link)))
  5470. (keymap (or (org-link-get-parameter type :keymap)
  5471. org-mouse-map))
  5472. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5473. 'highlight))
  5474. (htmlize (org-link-get-parameter type :htmlize-link))
  5475. (htmlize-link (cond
  5476. ((functionp htmlize)
  5477. (funcall htmlize))
  5478. (t
  5479. `(:uri ,(format "%s:%s" type path)))))
  5480. (activate-func (org-link-get-parameter type :activate-func))
  5481. ;; invisible part
  5482. (ip (list 'invisible (or
  5483. (org-link-get-parameter type :display)
  5484. 'org-link)
  5485. 'face face
  5486. 'keymap keymap
  5487. 'mouse-face mouse-face
  5488. 'font-lock-multiline t
  5489. 'help-echo help
  5490. 'htmlize-link htmlize-link))
  5491. ;; visible part
  5492. (vp (list 'keymap keymap
  5493. 'face face
  5494. 'mouse-face mouse-face
  5495. 'font-lock-multiline t
  5496. 'help-echo help
  5497. 'htmlize-link htmlize-link)))
  5498. ;; We need to remove the invisible property here. Table narrowing
  5499. ;; may have made some of this invisible.
  5500. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5501. (remove-text-properties (match-beginning 0) (match-end 0)
  5502. '(invisible nil))
  5503. (if (match-end 3)
  5504. (progn
  5505. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5506. (org-rear-nonsticky-at (match-beginning 3))
  5507. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5508. (org-rear-nonsticky-at (match-end 3))
  5509. (add-text-properties (match-end 3) (match-end 0) ip)
  5510. (org-rear-nonsticky-at (match-end 0)))
  5511. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5512. (org-rear-nonsticky-at (match-beginning 1))
  5513. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5514. (org-rear-nonsticky-at (match-end 1))
  5515. (add-text-properties (match-end 1) (match-end 0) ip)
  5516. (org-rear-nonsticky-at (match-end 0)))
  5517. (when activate-func
  5518. (funcall activate-func link-start link-end path bracketp))
  5519. t)))
  5520. (defun org-activate-dates (limit)
  5521. "Add text properties for dates."
  5522. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5523. (not (equal (char-before (match-beginning 0)) 91)))
  5524. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5525. (add-text-properties (match-beginning 0) (match-end 0)
  5526. (list 'mouse-face 'highlight
  5527. 'keymap org-mouse-map))
  5528. (org-rear-nonsticky-at (match-end 0))
  5529. (when org-display-custom-times
  5530. (if (match-end 3)
  5531. (org-display-custom-time (match-beginning 3) (match-end 3))
  5532. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5533. t))
  5534. (defvar-local org-target-link-regexp nil
  5535. "Regular expression matching radio targets in plain text.")
  5536. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5537. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5538. border border border))
  5539. "Regular expression matching a link target.")
  5540. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5541. "Regular expression matching a radio target.")
  5542. (defconst org-any-target-regexp
  5543. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5544. "Regular expression matching any target.")
  5545. (defun org-activate-target-links (limit)
  5546. "Add text properties for target matches."
  5547. (when org-target-link-regexp
  5548. (let ((case-fold-search t))
  5549. (when (re-search-forward org-target-link-regexp limit t)
  5550. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5551. (add-text-properties (match-beginning 1) (match-end 1)
  5552. (list 'mouse-face 'highlight
  5553. 'keymap org-mouse-map
  5554. 'help-echo "Radio target link"
  5555. 'org-linked-text t))
  5556. (org-rear-nonsticky-at (match-end 1))
  5557. t))))
  5558. (defun org-update-radio-target-regexp ()
  5559. "Find all radio targets in this file and update the regular expression.
  5560. Also refresh fontification if needed."
  5561. (interactive)
  5562. (let ((old-regexp org-target-link-regexp)
  5563. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5564. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5565. (targets
  5566. (org-with-wide-buffer
  5567. (goto-char (point-min))
  5568. (let (rtn)
  5569. (while (re-search-forward org-radio-target-regexp nil t)
  5570. ;; Make sure point is really within the object.
  5571. (backward-char)
  5572. (let ((obj (org-element-context)))
  5573. (when (eq (org-element-type obj) 'radio-target)
  5574. (cl-pushnew (org-element-property :value obj) rtn
  5575. :test #'equal))))
  5576. rtn))))
  5577. (setq org-target-link-regexp
  5578. (and targets
  5579. (concat before-re
  5580. (mapconcat
  5581. (lambda (x)
  5582. (replace-regexp-in-string
  5583. " +" "\\s-+" (regexp-quote x) t t))
  5584. targets
  5585. "\\|")
  5586. after-re)))
  5587. (unless (equal old-regexp org-target-link-regexp)
  5588. ;; Clean-up cache.
  5589. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5590. ((not org-target-link-regexp) old-regexp)
  5591. (t
  5592. (concat before-re
  5593. (mapconcat
  5594. (lambda (re)
  5595. (substring re (length before-re)
  5596. (- (length after-re))))
  5597. (list old-regexp org-target-link-regexp)
  5598. "\\|")
  5599. after-re)))))
  5600. (org-with-wide-buffer
  5601. (goto-char (point-min))
  5602. (while (re-search-forward regexp nil t)
  5603. (org-element-cache-refresh (match-beginning 1)))))
  5604. ;; Re fontify buffer.
  5605. (when (memq 'radio org-highlight-links)
  5606. (org-restart-font-lock)))))
  5607. (defun org-hide-wide-columns (limit)
  5608. (let (s e)
  5609. (setq s (text-property-any (point) (or limit (point-max))
  5610. 'org-cwidth t))
  5611. (when s
  5612. (setq e (next-single-property-change s 'org-cwidth))
  5613. (add-text-properties s e '(invisible org-cwidth))
  5614. (goto-char e)
  5615. t)))
  5616. (defvar org-latex-and-related-regexp nil
  5617. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5618. (defun org-compute-latex-and-related-regexp ()
  5619. "Compute regular expression for LaTeX, entities and sub/superscript.
  5620. Result depends on variable `org-highlight-latex-and-related'."
  5621. (setq-local
  5622. org-latex-and-related-regexp
  5623. (let* ((re-sub
  5624. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5625. ((eq org-use-sub-superscripts '{})
  5626. (list org-match-substring-with-braces-regexp))
  5627. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5628. (re-latex
  5629. (when (memq 'latex org-highlight-latex-and-related)
  5630. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5631. (delq nil
  5632. (mapcar (lambda (x)
  5633. (and (member (car x) matchers) (nth 1 x)))
  5634. org-latex-regexps)))))
  5635. (re-entities
  5636. (when (memq 'entities org-highlight-latex-and-related)
  5637. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5638. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5639. (defun org-do-latex-and-related (limit)
  5640. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5641. LIMIT bounds the search for syntax to highlight. Stop at first
  5642. highlighted object, if any. Return t if some highlighting was
  5643. done, nil otherwise."
  5644. (when (org-string-nw-p org-latex-and-related-regexp)
  5645. (catch 'found
  5646. (while (re-search-forward org-latex-and-related-regexp limit t)
  5647. (unless
  5648. (cl-some
  5649. (lambda (f)
  5650. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5651. (save-excursion
  5652. (goto-char (1+ (match-beginning 0)))
  5653. (face-at-point nil t)))
  5654. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5655. '(?_ ?^))
  5656. 1
  5657. 0)))
  5658. (font-lock-prepend-text-property
  5659. (+ offset (match-beginning 0)) (match-end 0)
  5660. 'face 'org-latex-and-related)
  5661. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5662. '(font-lock-multiline t)))
  5663. (throw 'found t)))
  5664. nil)))
  5665. (defun org-restart-font-lock ()
  5666. "Restart `font-lock-mode', to force refontification."
  5667. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5668. (font-lock-mode -1)
  5669. (font-lock-mode 1)))
  5670. (defun org-activate-tags (limit)
  5671. (when (re-search-forward
  5672. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5673. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5674. (add-text-properties (match-beginning 1) (match-end 1)
  5675. (list 'mouse-face 'highlight
  5676. 'keymap org-mouse-map))
  5677. (org-rear-nonsticky-at (match-end 1))
  5678. t))
  5679. (defun org-outline-level ()
  5680. "Compute the outline level of the heading at point.
  5681. If this is called at a normal headline, the level is the number
  5682. of stars. Use `org-reduced-level' to remove the effect of
  5683. `org-odd-levels'. Unlike to `org-current-level', this function
  5684. takes into consideration inlinetasks."
  5685. (org-with-wide-buffer
  5686. (end-of-line)
  5687. (if (re-search-backward org-outline-regexp-bol nil t)
  5688. (1- (- (match-end 0) (match-beginning 0)))
  5689. 0)))
  5690. (defvar org-font-lock-keywords nil)
  5691. (defsubst org-re-property (property &optional literal allow-null value)
  5692. "Return a regexp matching a PROPERTY line.
  5693. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5694. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5695. non-nil, match properties even without a value.
  5696. Match group 3 is set to the value when it exists. If there is no
  5697. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5698. With optional argument VALUE, match only property lines with
  5699. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5700. unless LITERAL is non-nil."
  5701. (concat
  5702. "^\\(?4:[ \t]*\\)"
  5703. (format "\\(?1::\\(?2:%s\\):\\)"
  5704. (if literal property (regexp-quote property)))
  5705. (cond (value
  5706. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5707. (if literal value (regexp-quote value))))
  5708. (allow-null
  5709. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5710. (t
  5711. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5712. (defconst org-property-re
  5713. (org-re-property "\\S-+" 'literal t)
  5714. "Regular expression matching a property line.
  5715. There are four matching groups:
  5716. 1: :PROPKEY: including the leading and trailing colon,
  5717. 2: PROPKEY without the leading and trailing colon,
  5718. 3: PROPVAL without leading or trailing spaces,
  5719. 4: the indentation of the current line,
  5720. 5: trailing whitespace.")
  5721. (defvar org-font-lock-hook nil
  5722. "Functions to be called for special font lock stuff.")
  5723. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5724. (defvar org-font-lock-set-keywords-hook nil
  5725. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5726. This is called after `org-font-lock-extra-keywords' is defined, but before
  5727. it is installed to be used by font lock. This can be useful if something
  5728. needs to be inserted at a specific position in the font-lock sequence.")
  5729. (defun org-font-lock-hook (limit)
  5730. "Run `org-font-lock-hook' within LIMIT."
  5731. (run-hook-with-args 'org-font-lock-hook limit))
  5732. (defun org-set-font-lock-defaults ()
  5733. "Set font lock defaults for the current buffer."
  5734. (let* ((em org-fontify-emphasized-text)
  5735. (lk org-highlight-links)
  5736. (org-font-lock-extra-keywords
  5737. (list
  5738. ;; Call the hook
  5739. '(org-font-lock-hook)
  5740. ;; Headlines
  5741. `(,(if org-fontify-whole-heading-line
  5742. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5743. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5744. (1 (org-get-level-face 1))
  5745. (2 (org-get-level-face 2))
  5746. (3 (org-get-level-face 3)))
  5747. ;; Table lines
  5748. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5749. (1 'org-table t))
  5750. ;; Table internals
  5751. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5752. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5753. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5754. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5755. ;; Drawers
  5756. '(org-fontify-drawers)
  5757. ;; Properties
  5758. (list org-property-re
  5759. '(1 'org-special-keyword t)
  5760. '(3 'org-property-value t))
  5761. ;; Links
  5762. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5763. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5764. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5765. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5766. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5767. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5768. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5769. ;; Targets.
  5770. (list org-any-target-regexp '(0 'org-target t))
  5771. ;; Diary sexps.
  5772. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5773. ;; Macro
  5774. '(org-fontify-macros)
  5775. '(org-hide-wide-columns (0 nil append))
  5776. ;; TODO keyword
  5777. (list (format org-heading-keyword-regexp-format
  5778. org-todo-regexp)
  5779. '(2 (org-get-todo-face 2) t))
  5780. ;; DONE
  5781. (if org-fontify-done-headline
  5782. (list (format org-heading-keyword-regexp-format
  5783. (concat
  5784. "\\(?:"
  5785. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5786. "\\)"))
  5787. '(2 'org-headline-done t))
  5788. nil)
  5789. ;; Priorities
  5790. '(org-font-lock-add-priority-faces)
  5791. ;; Tags
  5792. '(org-font-lock-add-tag-faces)
  5793. ;; Tags groups
  5794. (when (and org-group-tags org-tag-groups-alist)
  5795. (list (concat org-outline-regexp-bol ".+\\(:"
  5796. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5797. ":\\).*$")
  5798. '(1 'org-tag-group prepend)))
  5799. ;; Special keywords
  5800. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5801. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5802. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5803. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5804. ;; Emphasis
  5805. (when em '(org-do-emphasis-faces))
  5806. ;; Checkboxes
  5807. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5808. 1 'org-checkbox prepend)
  5809. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5810. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5811. (0 (org-get-checkbox-statistics-face) t)))
  5812. ;; Description list items
  5813. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5814. 1 'org-list-dt prepend)
  5815. ;; ARCHIVEd headings
  5816. (list (concat
  5817. org-outline-regexp-bol
  5818. "\\(.*:" org-archive-tag ":.*\\)")
  5819. '(1 'org-archived prepend))
  5820. ;; Specials
  5821. '(org-do-latex-and-related)
  5822. '(org-fontify-entities)
  5823. '(org-raise-scripts)
  5824. ;; Code
  5825. '(org-activate-code (1 'org-code t))
  5826. ;; COMMENT
  5827. (list (format
  5828. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5829. org-todo-regexp
  5830. org-comment-string)
  5831. '(9 'org-special-keyword t))
  5832. ;; Blocks and meta lines
  5833. '(org-fontify-meta-lines-and-blocks))))
  5834. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5835. (run-hooks 'org-font-lock-set-keywords-hook)
  5836. ;; Now set the full font-lock-keywords
  5837. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5838. (setq-local font-lock-defaults
  5839. '(org-font-lock-keywords t nil nil backward-paragraph))
  5840. (kill-local-variable 'font-lock-keywords)
  5841. nil))
  5842. (defun org-toggle-pretty-entities ()
  5843. "Toggle the composition display of entities as UTF8 characters."
  5844. (interactive)
  5845. (setq-local org-pretty-entities (not org-pretty-entities))
  5846. (org-restart-font-lock)
  5847. (if org-pretty-entities
  5848. (message "Entities are now displayed as UTF8 characters")
  5849. (save-restriction
  5850. (widen)
  5851. (decompose-region (point-min) (point-max))
  5852. (message "Entities are now displayed as plain text"))))
  5853. (defvar-local org-custom-properties-overlays nil
  5854. "List of overlays used for custom properties.")
  5855. (defun org-toggle-custom-properties-visibility ()
  5856. "Display or hide properties in `org-custom-properties'."
  5857. (interactive)
  5858. (if org-custom-properties-overlays
  5859. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5860. (setq org-custom-properties-overlays nil))
  5861. (when org-custom-properties
  5862. (org-with-wide-buffer
  5863. (goto-char (point-min))
  5864. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5865. (while (re-search-forward regexp nil t)
  5866. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5867. (when (and end (< (point) end))
  5868. ;; Hide first custom property in current drawer.
  5869. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5870. (overlay-put o 'invisible t)
  5871. (overlay-put o 'org-custom-property t)
  5872. (push o org-custom-properties-overlays))
  5873. ;; Hide additional custom properties in the same drawer.
  5874. (while (re-search-forward regexp end t)
  5875. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5876. (overlay-put o 'invisible t)
  5877. (overlay-put o 'org-custom-property t)
  5878. (push o org-custom-properties-overlays)))))
  5879. ;; Each entry is limited to a single property drawer.
  5880. (outline-next-heading)))))))
  5881. (defun org-fontify-entities (limit)
  5882. "Find an entity to fontify."
  5883. (let (ee)
  5884. (when org-pretty-entities
  5885. (catch 'match
  5886. ;; "\_ "-family is left out on purpose. Only the first one,
  5887. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5888. ;; confusing when adding a second white space character.
  5889. (while (re-search-forward
  5890. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5891. limit t)
  5892. (when (and (not (org-at-comment-p))
  5893. (setq ee (org-entity-get (match-string 1)))
  5894. (= (length (nth 6 ee)) 1))
  5895. (let* ((end (if (equal (match-string 2) "{}")
  5896. (match-end 2)
  5897. (match-end 1))))
  5898. (add-text-properties
  5899. (match-beginning 0) end
  5900. (list 'font-lock-fontified t))
  5901. (compose-region (match-beginning 0) end
  5902. (nth 6 ee) nil)
  5903. (backward-char 1)
  5904. (throw 'match t))))
  5905. nil))))
  5906. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5907. "Fontify string S like in Org-mode."
  5908. (with-temp-buffer
  5909. (insert s)
  5910. (let ((org-odd-levels-only odd-levels))
  5911. (org-mode)
  5912. (org-font-lock-ensure)
  5913. (buffer-string))))
  5914. (defvar org-m nil)
  5915. (defvar org-l nil)
  5916. (defvar org-f nil)
  5917. (defun org-get-level-face (n)
  5918. "Get the right face for match N in font-lock matching of headlines."
  5919. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5920. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5921. (if org-cycle-level-faces
  5922. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5923. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5924. (cond
  5925. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5926. ((eq n 2) org-f)
  5927. (t (unless org-level-color-stars-only org-f))))
  5928. (defun org-face-from-face-or-color (context inherit face-or-color)
  5929. "Create a face list that inherits INHERIT, but sets the foreground color.
  5930. When FACE-OR-COLOR is not a string, just return it."
  5931. (if (stringp face-or-color)
  5932. (list :inherit inherit
  5933. (cdr (assoc context org-faces-easy-properties))
  5934. face-or-color)
  5935. face-or-color))
  5936. (defun org-get-todo-face (kwd)
  5937. "Get the right face for a TODO keyword KWD.
  5938. If KWD is a number, get the corresponding match group."
  5939. (when (numberp kwd) (setq kwd (match-string kwd)))
  5940. (or (org-face-from-face-or-color
  5941. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5942. (and (member kwd org-done-keywords) 'org-done)
  5943. 'org-todo))
  5944. (defun org-get-priority-face (priority)
  5945. "Get the right face for PRIORITY.
  5946. PRIORITY is a character."
  5947. (or (org-face-from-face-or-color
  5948. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5949. 'org-priority))
  5950. (defun org-get-tag-face (tag)
  5951. "Get the right face for TAG.
  5952. If TAG is a number, get the corresponding match group."
  5953. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5954. (or (org-face-from-face-or-color
  5955. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5956. 'org-tag)))
  5957. (defun org-font-lock-add-priority-faces (limit)
  5958. "Add the special priority faces."
  5959. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5960. (add-text-properties
  5961. (match-beginning 1) (match-end 1)
  5962. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5963. 'font-lock-fontified t))))
  5964. (defun org-font-lock-add-tag-faces (limit)
  5965. "Add the special tag faces."
  5966. (when (and org-tag-faces org-tags-special-faces-re)
  5967. (while (re-search-forward org-tags-special-faces-re limit t)
  5968. (add-text-properties (match-beginning 1) (match-end 1)
  5969. (list 'face (org-get-tag-face 1)
  5970. 'font-lock-fontified t))
  5971. (backward-char 1))))
  5972. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5973. "Remove fontification and activation overlays from links."
  5974. (font-lock-default-unfontify-region beg end)
  5975. (let* ((buffer-undo-list t)
  5976. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5977. (inhibit-modification-hooks t)
  5978. deactivate-mark buffer-file-name buffer-file-truename)
  5979. (decompose-region beg end)
  5980. (remove-text-properties beg end
  5981. '(mouse-face t keymap t org-linked-text t
  5982. invisible t intangible t
  5983. org-emphasis t))
  5984. (org-remove-font-lock-display-properties beg end)))
  5985. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5986. ((raise 0.3) (height 0.7))
  5987. ((raise -0.5))
  5988. ((raise 0.5)))
  5989. "Display properties for showing superscripts and subscripts.")
  5990. (defun org-remove-font-lock-display-properties (beg end)
  5991. "Remove specific display properties that have been added by font lock.
  5992. The will remove the raise properties that are used to show superscripts
  5993. and subscripts."
  5994. (let (next prop)
  5995. (while (< beg end)
  5996. (setq next (next-single-property-change beg 'display nil end)
  5997. prop (get-text-property beg 'display))
  5998. (when (member prop org-script-display)
  5999. (put-text-property beg next 'display nil))
  6000. (setq beg next))))
  6001. (defun org-raise-scripts (limit)
  6002. "Add raise properties to sub/superscripts."
  6003. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  6004. (re-search-forward
  6005. (if (eq org-use-sub-superscripts t)
  6006. org-match-substring-regexp
  6007. org-match-substring-with-braces-regexp)
  6008. limit t))
  6009. (let* ((pos (point)) table-p comment-p
  6010. (mpos (match-beginning 3))
  6011. (emph-p (get-text-property mpos 'org-emphasis))
  6012. (link-p (get-text-property mpos 'mouse-face))
  6013. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  6014. (goto-char (point-at-bol))
  6015. (setq table-p (looking-at-p org-table-dataline-regexp)
  6016. comment-p (looking-at-p "^[ \t]*#[ +]"))
  6017. (goto-char pos)
  6018. ;; Handle a_b^c
  6019. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  6020. (unless (or comment-p emph-p link-p keyw-p)
  6021. (put-text-property (match-beginning 3) (match-end 0)
  6022. 'display
  6023. (if (equal (char-after (match-beginning 2)) ?^)
  6024. (nth (if table-p 3 1) org-script-display)
  6025. (nth (if table-p 2 0) org-script-display)))
  6026. (add-text-properties (match-beginning 2) (match-end 2)
  6027. (list 'invisible t
  6028. 'org-dwidth t 'org-dwidth-n 1))
  6029. (if (and (eq (char-after (match-beginning 3)) ?{)
  6030. (eq (char-before (match-end 3)) ?}))
  6031. (progn
  6032. (add-text-properties
  6033. (match-beginning 3) (1+ (match-beginning 3))
  6034. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6035. (add-text-properties
  6036. (1- (match-end 3)) (match-end 3)
  6037. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6038. t)))
  6039. ;;;; Visibility cycling, including org-goto and indirect buffer
  6040. ;;; Cycling
  6041. (defvar-local org-cycle-global-status nil)
  6042. (put 'org-cycle-global-status 'org-state t)
  6043. (defvar-local org-cycle-subtree-status nil)
  6044. (put 'org-cycle-subtree-status 'org-state t)
  6045. (defvar org-inlinetask-min-level)
  6046. (defun org-unlogged-message (&rest args)
  6047. "Display a message, but avoid logging it in the *Messages* buffer."
  6048. (let ((message-log-max nil))
  6049. (apply 'message args)))
  6050. ;;;###autoload
  6051. (defun org-cycle (&optional arg)
  6052. "TAB-action and visibility cycling for Org-mode.
  6053. This is the command invoked in Org mode by the TAB key. Its main purpose
  6054. is outline visibility cycling, but it also invokes other actions
  6055. in special contexts.
  6056. - When this function is called with a prefix argument, rotate the entire
  6057. buffer through 3 states (global cycling)
  6058. 1. OVERVIEW: Show only top-level headlines.
  6059. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6060. 3. SHOW ALL: Show everything.
  6061. With a double \\[universal-argument] prefix argument, \
  6062. switch to the startup visibility,
  6063. determined by the variable `org-startup-folded', and by any VISIBILITY
  6064. properties in the buffer.
  6065. With a triple \\[universal-argument] prefix argument, \
  6066. show the entire buffer, including any drawers.
  6067. - When inside a table, re-align the table and move to the next field.
  6068. - When point is at the beginning of a headline, rotate the subtree started
  6069. by this line through 3 different states (local cycling)
  6070. 1. FOLDED: Only the main headline is shown.
  6071. 2. CHILDREN: The main headline and the direct children are shown.
  6072. From this state, you can move to one of the children
  6073. and zoom in further.
  6074. 3. SUBTREE: Show the entire subtree, including body text.
  6075. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6076. - When point is at the beginning of an empty headline and the variable
  6077. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6078. of the headline by demoting and promoting it to likely levels. This
  6079. speeds up creation document structure by pressing TAB once or several
  6080. times right after creating a new headline.
  6081. - When there is a numeric prefix, go up to a heading with level ARG, do
  6082. a `show-subtree' and return to the previous cursor position. If ARG
  6083. is negative, go up that many levels.
  6084. - When point is not at the beginning of a headline, execute the global
  6085. binding for TAB, which is re-indenting the line. See the option
  6086. `org-cycle-emulate-tab' for details.
  6087. - Special case: if point is at the beginning of the buffer and there is
  6088. no headline in line 1, this function will act as if called with prefix arg
  6089. (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
  6090. But only if also the variable `org-cycle-global-at-bob' is t."
  6091. (interactive "P")
  6092. (org-load-modules-maybe)
  6093. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6094. (and org-cycle-level-after-item/entry-creation
  6095. (or (org-cycle-level)
  6096. (org-cycle-item-indentation))))
  6097. (let* ((limit-level
  6098. (or org-cycle-max-level
  6099. (and (boundp 'org-inlinetask-min-level)
  6100. org-inlinetask-min-level
  6101. (1- org-inlinetask-min-level))))
  6102. (nstars (and limit-level
  6103. (if org-odd-levels-only
  6104. (and limit-level (1- (* limit-level 2)))
  6105. limit-level)))
  6106. (org-outline-regexp
  6107. (if (not (derived-mode-p 'org-mode))
  6108. outline-regexp
  6109. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6110. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6111. (not (looking-at org-outline-regexp))))
  6112. (org-cycle-hook
  6113. (if bob-special
  6114. (delq 'org-optimize-window-after-visibility-change
  6115. (copy-sequence org-cycle-hook))
  6116. org-cycle-hook))
  6117. (pos (point)))
  6118. (when (or bob-special (equal arg '(4)))
  6119. ;; special case: use global cycling
  6120. (setq arg t))
  6121. (cond
  6122. ((equal arg '(16))
  6123. (setq last-command 'dummy)
  6124. (org-set-startup-visibility)
  6125. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6126. ((equal arg '(64))
  6127. (outline-show-all)
  6128. (org-unlogged-message "Entire buffer visible, including drawers"))
  6129. ;; Try cdlatex TAB completion
  6130. ((org-try-cdlatex-tab))
  6131. ;; Table: enter it or move to the next field.
  6132. ((org-at-table-p 'any)
  6133. (if (org-at-table.el-p)
  6134. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6135. Use \\[org-edit-special] to edit table.el tables"))
  6136. (if arg (org-table-edit-field t)
  6137. (org-table-justify-field-maybe)
  6138. (call-interactively 'org-table-next-field))))
  6139. ((run-hook-with-args-until-success
  6140. 'org-tab-after-check-for-table-hook))
  6141. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6142. ((eq arg t) (org-cycle-internal-global))
  6143. ;; Drawers: delegate to `org-flag-drawer'.
  6144. ((save-excursion
  6145. (beginning-of-line 1)
  6146. (looking-at org-drawer-regexp))
  6147. (org-flag-drawer ; toggle block visibility
  6148. (not (get-char-property (match-end 0) 'invisible))))
  6149. ;; Show-subtree, ARG levels up from here.
  6150. ((integerp arg)
  6151. (save-excursion
  6152. (org-back-to-heading)
  6153. (outline-up-heading (if (< arg 0) (- arg)
  6154. (- (funcall outline-level) arg)))
  6155. (org-show-subtree)))
  6156. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6157. ((and (featurep 'org-inlinetask)
  6158. (org-inlinetask-at-task-p)
  6159. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6160. (org-inlinetask-toggle-visibility))
  6161. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6162. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6163. (save-excursion (move-beginning-of-line 1)
  6164. (looking-at org-outline-regexp)))
  6165. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6166. (org-cycle-internal-local))
  6167. ;; From there: TAB emulation and template completion.
  6168. (buffer-read-only (org-back-to-heading))
  6169. ((run-hook-with-args-until-success
  6170. 'org-tab-after-check-for-cycling-hook))
  6171. ((org-try-structure-completion))
  6172. ((run-hook-with-args-until-success
  6173. 'org-tab-before-tab-emulation-hook))
  6174. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6175. (or (not (bolp))
  6176. (not (looking-at org-outline-regexp))))
  6177. (call-interactively (global-key-binding "\t")))
  6178. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6179. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6180. (or (and (eq org-cycle-emulate-tab 'white)
  6181. (= (match-end 0) (point-at-eol)))
  6182. (and (eq org-cycle-emulate-tab 'whitestart)
  6183. (>= (match-end 0) pos))))
  6184. t
  6185. (eq org-cycle-emulate-tab t))
  6186. (call-interactively (global-key-binding "\t")))
  6187. (t (save-excursion
  6188. (org-back-to-heading)
  6189. (org-cycle)))))))
  6190. (defun org-cycle-internal-global ()
  6191. "Do the global cycling action."
  6192. ;; Hack to avoid display of messages for .org attachments in Gnus
  6193. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6194. (cond
  6195. ((and (eq last-command this-command)
  6196. (eq org-cycle-global-status 'overview))
  6197. ;; We just created the overview - now do table of contents
  6198. ;; This can be slow in very large buffers, so indicate action
  6199. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6200. (unless ga (org-unlogged-message "CONTENTS..."))
  6201. (org-content)
  6202. (unless ga (org-unlogged-message "CONTENTS...done"))
  6203. (setq org-cycle-global-status 'contents)
  6204. (run-hook-with-args 'org-cycle-hook 'contents))
  6205. ((and (eq last-command this-command)
  6206. (eq org-cycle-global-status 'contents))
  6207. ;; We just showed the table of contents - now show everything
  6208. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6209. (outline-show-all)
  6210. (unless ga (org-unlogged-message "SHOW ALL"))
  6211. (setq org-cycle-global-status 'all)
  6212. (run-hook-with-args 'org-cycle-hook 'all))
  6213. (t
  6214. ;; Default action: go to overview
  6215. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6216. (org-overview)
  6217. (unless ga (org-unlogged-message "OVERVIEW"))
  6218. (setq org-cycle-global-status 'overview)
  6219. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6220. (defvar org-called-with-limited-levels nil
  6221. "Non-nil when `org-with-limited-levels' is currently active.")
  6222. (defun org-cycle-internal-local ()
  6223. "Do the local cycling action."
  6224. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6225. ;; First, determine end of headline (EOH), end of subtree or item
  6226. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6227. (save-excursion
  6228. (if (org-at-item-p)
  6229. (progn
  6230. (beginning-of-line)
  6231. (setq struct (org-list-struct))
  6232. (setq eoh (point-at-eol))
  6233. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6234. (setq has-children (org-list-has-child-p (point) struct)))
  6235. (org-back-to-heading)
  6236. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6237. (setq eos (save-excursion (org-end-of-subtree t t)
  6238. (when (bolp) (backward-char)) (point)))
  6239. (setq has-children
  6240. (or (save-excursion
  6241. (let ((level (funcall outline-level)))
  6242. (outline-next-heading)
  6243. (and (org-at-heading-p t)
  6244. (> (funcall outline-level) level))))
  6245. (save-excursion
  6246. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6247. ;; Determine end invisible part of buffer (EOL)
  6248. (beginning-of-line 2)
  6249. (while (and (not (eobp)) ;This is like `next-line'.
  6250. (get-char-property (1- (point)) 'invisible))
  6251. (goto-char (next-single-char-property-change (point) 'invisible))
  6252. (and (eolp) (beginning-of-line 2)))
  6253. (setq eol (point)))
  6254. ;; Find out what to do next and set `this-command'
  6255. (cond
  6256. ((= eos eoh)
  6257. ;; Nothing is hidden behind this heading
  6258. (unless (org-before-first-heading-p)
  6259. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6260. (org-unlogged-message "EMPTY ENTRY")
  6261. (setq org-cycle-subtree-status nil)
  6262. (save-excursion
  6263. (goto-char eos)
  6264. (outline-next-heading)
  6265. (when (outline-invisible-p) (org-flag-heading nil))))
  6266. ((and (or (>= eol eos)
  6267. (not (string-match "\\S-" (buffer-substring eol eos))))
  6268. (or has-children
  6269. (not (setq children-skipped
  6270. org-cycle-skip-children-state-if-no-children))))
  6271. ;; Entire subtree is hidden in one line: children view
  6272. (unless (org-before-first-heading-p)
  6273. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6274. (if (org-at-item-p)
  6275. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6276. (org-show-entry)
  6277. (org-with-limited-levels (org-show-children))
  6278. ;; FIXME: This slows down the func way too much.
  6279. ;; How keep drawers hidden in subtree anyway?
  6280. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6281. ;; (org-cycle-hide-drawers 'subtree))
  6282. ;; Fold every list in subtree to top-level items.
  6283. (when (eq org-cycle-include-plain-lists 'integrate)
  6284. (save-excursion
  6285. (org-back-to-heading)
  6286. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6287. (beginning-of-line 1)
  6288. (let* ((struct (org-list-struct))
  6289. (prevs (org-list-prevs-alist struct))
  6290. (end (org-list-get-bottom-point struct)))
  6291. (dolist (e (org-list-get-all-items (point) struct prevs))
  6292. (org-list-set-item-visibility e struct 'folded))
  6293. (goto-char (if (< end eos) end eos)))))))
  6294. (org-unlogged-message "CHILDREN")
  6295. (save-excursion
  6296. (goto-char eos)
  6297. (outline-next-heading)
  6298. (when (outline-invisible-p) (org-flag-heading nil)))
  6299. (setq org-cycle-subtree-status 'children)
  6300. (unless (org-before-first-heading-p)
  6301. (run-hook-with-args 'org-cycle-hook 'children)))
  6302. ((or children-skipped
  6303. (and (eq last-command this-command)
  6304. (eq org-cycle-subtree-status 'children)))
  6305. ;; We just showed the children, or no children are there,
  6306. ;; now show everything.
  6307. (unless (org-before-first-heading-p)
  6308. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6309. (outline-flag-region eoh eos nil)
  6310. (org-unlogged-message
  6311. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6312. (setq org-cycle-subtree-status 'subtree)
  6313. (unless (org-before-first-heading-p)
  6314. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6315. (t
  6316. ;; Default action: hide the subtree.
  6317. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6318. (outline-flag-region eoh eos t)
  6319. (org-unlogged-message "FOLDED")
  6320. (setq org-cycle-subtree-status 'folded)
  6321. (unless (org-before-first-heading-p)
  6322. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6323. ;;;###autoload
  6324. (defun org-global-cycle (&optional arg)
  6325. "Cycle the global visibility. For details see `org-cycle'.
  6326. With \\[universal-argument] prefix arg, switch to startup visibility.
  6327. With a numeric prefix, show all headlines up to that level."
  6328. (interactive "P")
  6329. (let ((org-cycle-include-plain-lists
  6330. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6331. (cond
  6332. ((integerp arg)
  6333. (outline-show-all)
  6334. (outline-hide-sublevels arg)
  6335. (setq org-cycle-global-status 'contents))
  6336. ((equal arg '(4))
  6337. (org-set-startup-visibility)
  6338. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6339. (t
  6340. (org-cycle '(4))))))
  6341. (defun org-set-startup-visibility ()
  6342. "Set the visibility required by startup options and properties."
  6343. (cond
  6344. ((eq org-startup-folded t)
  6345. (org-overview))
  6346. ((eq org-startup-folded 'content)
  6347. (org-content))
  6348. ((or (eq org-startup-folded 'showeverything)
  6349. (eq org-startup-folded nil))
  6350. (outline-show-all)))
  6351. (unless (eq org-startup-folded 'showeverything)
  6352. (when org-hide-block-startup (org-hide-block-all))
  6353. (org-set-visibility-according-to-property 'no-cleanup)
  6354. (org-cycle-hide-archived-subtrees 'all)
  6355. (org-cycle-hide-drawers 'all)
  6356. (org-cycle-show-empty-lines t)))
  6357. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6358. "Switch subtree visibilities according to :VISIBILITY: property."
  6359. (interactive)
  6360. (org-with-wide-buffer
  6361. (goto-char (point-min))
  6362. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6363. (if (not (org-at-property-p)) (outline-next-heading)
  6364. (let ((state (match-string 3)))
  6365. (save-excursion
  6366. (org-back-to-heading t)
  6367. (outline-hide-subtree)
  6368. (org-reveal)
  6369. (cond
  6370. ((equal state "folded")
  6371. (outline-hide-subtree))
  6372. ((equal state "children")
  6373. (org-show-hidden-entry)
  6374. (org-show-children))
  6375. ((equal state "content")
  6376. (save-excursion
  6377. (save-restriction
  6378. (org-narrow-to-subtree)
  6379. (org-content))))
  6380. ((member state '("all" "showall"))
  6381. (outline-show-subtree)))))))
  6382. (unless no-cleanup
  6383. (org-cycle-hide-archived-subtrees 'all)
  6384. (org-cycle-hide-drawers 'all)
  6385. (org-cycle-show-empty-lines 'all))))
  6386. ;; This function uses outline-regexp instead of the more fundamental
  6387. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6388. ;; buffers, where outline-regexp is needed.
  6389. (defun org-overview ()
  6390. "Switch to overview mode, showing only top-level headlines.
  6391. This shows all headlines with a level equal or greater than the level
  6392. of the first headline in the buffer. This is important, because if the
  6393. first headline is not level one, then (hide-sublevels 1) gives confusing
  6394. results."
  6395. (interactive)
  6396. (save-excursion
  6397. (let ((level
  6398. (save-excursion
  6399. (goto-char (point-min))
  6400. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6401. (goto-char (match-beginning 0))
  6402. (funcall outline-level)))))
  6403. (and level (outline-hide-sublevels level)))))
  6404. (defun org-content (&optional arg)
  6405. "Show all headlines in the buffer, like a table of contents.
  6406. With numerical argument N, show content up to level N."
  6407. (interactive "P")
  6408. (org-overview)
  6409. (save-excursion
  6410. ;; Visit all headings and show their offspring
  6411. (and (integerp arg) (org-overview))
  6412. (goto-char (point-max))
  6413. (catch 'exit
  6414. (while (and (progn (condition-case nil
  6415. (outline-previous-visible-heading 1)
  6416. (error (goto-char (point-min))))
  6417. t)
  6418. (looking-at org-outline-regexp))
  6419. (if (integerp arg)
  6420. (org-show-children (1- arg))
  6421. (outline-show-branches))
  6422. (when (bobp) (throw 'exit nil))))))
  6423. (defun org-optimize-window-after-visibility-change (state)
  6424. "Adjust the window after a change in outline visibility.
  6425. This function is the default value of the hook `org-cycle-hook'."
  6426. (when (get-buffer-window (current-buffer))
  6427. (cond
  6428. ((eq state 'content) nil)
  6429. ((eq state 'all) nil)
  6430. ((eq state 'folded) nil)
  6431. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6432. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6433. (defun org-remove-empty-overlays-at (pos)
  6434. "Remove outline overlays that do not contain non-white stuff."
  6435. (dolist (o (overlays-at pos))
  6436. (and (eq 'outline (overlay-get o 'invisible))
  6437. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6438. (overlay-end o))))
  6439. (delete-overlay o))))
  6440. (defun org-clean-visibility-after-subtree-move ()
  6441. "Fix visibility issues after moving a subtree."
  6442. ;; First, find a reasonable region to look at:
  6443. ;; Start two siblings above, end three below
  6444. (let* ((beg (save-excursion
  6445. (and (org-get-last-sibling)
  6446. (org-get-last-sibling))
  6447. (point)))
  6448. (end (save-excursion
  6449. (and (org-get-next-sibling)
  6450. (org-get-next-sibling)
  6451. (org-get-next-sibling))
  6452. (if (org-at-heading-p)
  6453. (point-at-eol)
  6454. (point))))
  6455. (level (looking-at "\\*+"))
  6456. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6457. (save-excursion
  6458. (save-restriction
  6459. (narrow-to-region beg end)
  6460. (when re
  6461. ;; Properly fold already folded siblings
  6462. (goto-char (point-min))
  6463. (while (re-search-forward re nil t)
  6464. (when (and (not (outline-invisible-p))
  6465. (save-excursion
  6466. (goto-char (point-at-eol)) (outline-invisible-p)))
  6467. (outline-hide-entry))))
  6468. (org-cycle-show-empty-lines 'overview)
  6469. (org-cycle-hide-drawers 'overview)))))
  6470. (defun org-cycle-show-empty-lines (state)
  6471. "Show empty lines above all visible headlines.
  6472. The region to be covered depends on STATE when called through
  6473. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6474. entire buffer covered. Note that an empty line is only shown if there
  6475. are at least `org-cycle-separator-lines' empty lines before the headline."
  6476. (when (/= org-cycle-separator-lines 0)
  6477. (save-excursion
  6478. (let* ((n (abs org-cycle-separator-lines))
  6479. (re (cond
  6480. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6481. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6482. (t (let ((ns (number-to-string (- n 2))))
  6483. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6484. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6485. beg end)
  6486. (cond
  6487. ((memq state '(overview contents t))
  6488. (setq beg (point-min) end (point-max)))
  6489. ((memq state '(children folded))
  6490. (setq beg (point)
  6491. end (progn (org-end-of-subtree t t)
  6492. (line-beginning-position 2)))))
  6493. (when beg
  6494. (goto-char beg)
  6495. (while (re-search-forward re end t)
  6496. (unless (get-char-property (match-end 1) 'invisible)
  6497. (let ((e (match-end 1))
  6498. (b (if (>= org-cycle-separator-lines 0)
  6499. (match-beginning 1)
  6500. (save-excursion
  6501. (goto-char (match-beginning 0))
  6502. (skip-chars-backward " \t\n")
  6503. (line-end-position)))))
  6504. (outline-flag-region b e nil))))))))
  6505. ;; Never hide empty lines at the end of the file.
  6506. (save-excursion
  6507. (goto-char (point-max))
  6508. (outline-previous-heading)
  6509. (outline-end-of-heading)
  6510. (when (and (looking-at "[ \t\n]+")
  6511. (= (match-end 0) (point-max)))
  6512. (outline-flag-region (point) (match-end 0) nil))))
  6513. (defun org-show-empty-lines-in-parent ()
  6514. "Move to the parent and re-show empty lines before visible headlines."
  6515. (save-excursion
  6516. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6517. (org-cycle-show-empty-lines context))))
  6518. (defun org-files-list ()
  6519. "Return `org-agenda-files' list, plus all open Org files.
  6520. This is useful for operations that need to scan all of a user's
  6521. open and agenda-wise Org files."
  6522. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6523. (dolist (buf (buffer-list))
  6524. (with-current-buffer buf
  6525. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6526. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6527. files))
  6528. (defsubst org-entry-beginning-position ()
  6529. "Return the beginning position of the current entry."
  6530. (save-excursion (org-back-to-heading t) (point)))
  6531. (defsubst org-entry-end-position ()
  6532. "Return the end position of the current entry."
  6533. (save-excursion (outline-next-heading) (point)))
  6534. (defun org-cycle-hide-drawers (state &optional exceptions)
  6535. "Re-hide all drawers after a visibility state change.
  6536. When non-nil, optional argument EXCEPTIONS is a list of strings
  6537. specifying which drawers should not be hidden."
  6538. (when (and (derived-mode-p 'org-mode)
  6539. (not (memq state '(overview folded contents))))
  6540. (save-excursion
  6541. (let* ((globalp (memq state '(contents all)))
  6542. (beg (if globalp (point-min) (point)))
  6543. (end (if globalp (point-max)
  6544. (if (eq state 'children)
  6545. (save-excursion (outline-next-heading) (point))
  6546. (org-end-of-subtree t)))))
  6547. (goto-char beg)
  6548. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6549. (unless (member-ignore-case (match-string 1) exceptions)
  6550. (let ((drawer (org-element-at-point)))
  6551. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6552. (org-flag-drawer t drawer)
  6553. ;; Make sure to skip drawer entirely or we might flag
  6554. ;; it another time when matching its ending line with
  6555. ;; `org-drawer-regexp'.
  6556. (goto-char (org-element-property :end drawer))))))))))
  6557. (defun org-flag-drawer (flag &optional element)
  6558. "When FLAG is non-nil, hide the drawer we are at.
  6559. Otherwise make it visible. When optional argument ELEMENT is
  6560. a parsed drawer, as returned by `org-element-at-point', hide or
  6561. show that drawer instead."
  6562. (let ((drawer (or element
  6563. (and (save-excursion
  6564. (beginning-of-line)
  6565. (looking-at-p org-drawer-regexp))
  6566. (org-element-at-point)))))
  6567. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6568. (let ((post (org-element-property :post-affiliated drawer)))
  6569. (save-excursion
  6570. (outline-flag-region
  6571. (progn (goto-char post) (line-end-position))
  6572. (progn (goto-char (org-element-property :end drawer))
  6573. (skip-chars-backward " \r\t\n")
  6574. (line-end-position))
  6575. flag))
  6576. ;; When the drawer is hidden away, make sure point lies in
  6577. ;; a visible part of the buffer.
  6578. (when (and flag (> (line-beginning-position) post))
  6579. (goto-char post))))))
  6580. (defun org-subtree-end-visible-p ()
  6581. "Is the end of the current subtree visible?"
  6582. (pos-visible-in-window-p
  6583. (save-excursion (org-end-of-subtree t) (point))))
  6584. (defun org-first-headline-recenter ()
  6585. "Move cursor to the first headline and recenter the headline."
  6586. (let ((window (get-buffer-window)))
  6587. (when window
  6588. (goto-char (point-min))
  6589. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6590. (set-window-start window (line-beginning-position))))))
  6591. ;;; Saving and restoring visibility
  6592. (defun org-outline-overlay-data (&optional use-markers)
  6593. "Return a list of the locations of all outline overlays.
  6594. These are overlays with the `invisible' property value `outline'.
  6595. The return value is a list of cons cells, with start and stop
  6596. positions for each overlay.
  6597. If USE-MARKERS is set, return the positions as markers."
  6598. (let (beg end)
  6599. (save-excursion
  6600. (save-restriction
  6601. (widen)
  6602. (delq nil
  6603. (mapcar (lambda (o)
  6604. (when (eq (overlay-get o 'invisible) 'outline)
  6605. (setq beg (overlay-start o)
  6606. end (overlay-end o))
  6607. (and beg end (> end beg)
  6608. (if use-markers
  6609. (cons (copy-marker beg)
  6610. (copy-marker end t))
  6611. (cons beg end)))))
  6612. (overlays-in (point-min) (point-max))))))))
  6613. (defun org-set-outline-overlay-data (data)
  6614. "Create visibility overlays for all positions in DATA.
  6615. DATA should have been made by `org-outline-overlay-data'."
  6616. (org-with-wide-buffer
  6617. (outline-show-all)
  6618. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6619. ;;; Folding of blocks
  6620. (defvar-local org-hide-block-overlays nil
  6621. "Overlays hiding blocks.")
  6622. (defun org-block-map (function &optional start end)
  6623. "Call FUNCTION at the head of all source blocks in the current buffer.
  6624. Optional arguments START and END can be used to limit the range."
  6625. (let ((start (or start (point-min)))
  6626. (end (or end (point-max))))
  6627. (save-excursion
  6628. (goto-char start)
  6629. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6630. (save-excursion
  6631. (save-match-data
  6632. (goto-char (match-beginning 0))
  6633. (funcall function)))))))
  6634. (defun org-hide-block-toggle-all ()
  6635. "Toggle the visibility of all blocks in the current buffer."
  6636. (org-block-map 'org-hide-block-toggle))
  6637. (defun org-hide-block-all ()
  6638. "Fold all blocks in the current buffer."
  6639. (interactive)
  6640. (org-show-block-all)
  6641. (org-block-map 'org-hide-block-toggle-maybe))
  6642. (defun org-show-block-all ()
  6643. "Unfold all blocks in the current buffer."
  6644. (interactive)
  6645. (mapc #'delete-overlay org-hide-block-overlays)
  6646. (setq org-hide-block-overlays nil))
  6647. (defun org-hide-block-toggle-maybe ()
  6648. "Toggle visibility of block at point.
  6649. Unlike to `org-hide-block-toggle', this function does not throw
  6650. an error. Return a non-nil value when toggling is successful."
  6651. (interactive)
  6652. (ignore-errors (org-hide-block-toggle)))
  6653. (defun org-hide-block-toggle (&optional force)
  6654. "Toggle the visibility of the current block.
  6655. When optional argument FORCE is `off', make block visible. If it
  6656. is non-nil, hide it unconditionally. Throw an error when not at
  6657. a block. Return a non-nil value when toggling is successful."
  6658. (interactive)
  6659. (let ((element (org-element-at-point)))
  6660. (unless (memq (org-element-type element)
  6661. '(center-block comment-block dynamic-block example-block
  6662. export-block quote-block special-block
  6663. src-block verse-block))
  6664. (user-error "Not at a block"))
  6665. (let* ((start (save-excursion
  6666. (goto-char (org-element-property :post-affiliated element))
  6667. (line-end-position)))
  6668. (end (save-excursion
  6669. (goto-char (org-element-property :end element))
  6670. (skip-chars-backward " \r\t\n")
  6671. (line-end-position)))
  6672. (overlays (overlays-at start)))
  6673. (cond
  6674. ;; Do nothing when not before or at the block opening line or
  6675. ;; at the block closing line.
  6676. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6677. ((and (not (eq force 'off))
  6678. (not (memq t (mapcar
  6679. (lambda (o)
  6680. (eq (overlay-get o 'invisible) 'org-hide-block))
  6681. overlays))))
  6682. (let ((ov (make-overlay start end)))
  6683. (overlay-put ov 'invisible 'org-hide-block)
  6684. ;; Make the block accessible to `isearch'.
  6685. (overlay-put
  6686. ov 'isearch-open-invisible
  6687. (lambda (ov)
  6688. (when (memq ov org-hide-block-overlays)
  6689. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6690. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6691. (delete-overlay ov))))
  6692. (push ov org-hide-block-overlays)
  6693. ;; When the block is hidden away, make sure point is left in
  6694. ;; a visible part of the buffer.
  6695. (when (> (line-beginning-position) start)
  6696. (goto-char start)
  6697. (beginning-of-line))
  6698. ;; Signal successful toggling.
  6699. t))
  6700. ((or (not force) (eq force 'off))
  6701. (dolist (ov overlays t)
  6702. (when (memq ov org-hide-block-overlays)
  6703. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6704. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6705. (delete-overlay ov))))))))
  6706. ;; org-tab-after-check-for-cycling-hook
  6707. (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
  6708. ;; Remove overlays when changing major mode
  6709. (add-hook 'org-mode-hook
  6710. (lambda () (add-hook 'change-major-mode-hook
  6711. 'org-show-block-all 'append 'local)))
  6712. ;;; Org-goto
  6713. (defvar org-goto-window-configuration nil)
  6714. (defvar org-goto-marker nil)
  6715. (defvar org-goto-map)
  6716. (defun org-goto-map ()
  6717. "Set the keymap `org-goto'."
  6718. (setq org-goto-map
  6719. (let ((map (make-sparse-keymap)))
  6720. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6721. mouse-drag-region universal-argument org-occur)))
  6722. (dolist (cmd cmds)
  6723. (substitute-key-definition cmd cmd map global-map)))
  6724. (suppress-keymap map)
  6725. (org-defkey map "\C-m" 'org-goto-ret)
  6726. (org-defkey map [(return)] 'org-goto-ret)
  6727. (org-defkey map [(left)] 'org-goto-left)
  6728. (org-defkey map [(right)] 'org-goto-right)
  6729. (org-defkey map [(control ?g)] 'org-goto-quit)
  6730. (org-defkey map "\C-i" 'org-cycle)
  6731. (org-defkey map [(tab)] 'org-cycle)
  6732. (org-defkey map [(down)] 'outline-next-visible-heading)
  6733. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6734. (if org-goto-auto-isearch
  6735. (if (fboundp 'define-key-after)
  6736. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6737. nil)
  6738. (org-defkey map "q" 'org-goto-quit)
  6739. (org-defkey map "n" 'outline-next-visible-heading)
  6740. (org-defkey map "p" 'outline-previous-visible-heading)
  6741. (org-defkey map "f" 'outline-forward-same-level)
  6742. (org-defkey map "b" 'outline-backward-same-level)
  6743. (org-defkey map "u" 'outline-up-heading))
  6744. (org-defkey map "/" 'org-occur)
  6745. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6746. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6747. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6748. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6749. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6750. map)))
  6751. (defconst org-goto-help
  6752. "Browse buffer copy, to find location or copy text.%s
  6753. RET=jump to location C-g=quit and return to previous location
  6754. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6755. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6756. (defun org-goto (&optional alternative-interface)
  6757. "Look up a different location in the current file, keeping current visibility.
  6758. When you want look-up or go to a different location in a
  6759. document, the fastest way is often to fold the entire buffer and
  6760. then dive into the tree. This method has the disadvantage, that
  6761. the previous location will be folded, which may not be what you
  6762. want.
  6763. This command works around this by showing a copy of the current
  6764. buffer in an indirect buffer, in overview mode. You can dive
  6765. into the tree in that copy, use org-occur and incremental search
  6766. to find a location. When pressing RET or `Q', the command
  6767. returns to the original buffer in which the visibility is still
  6768. unchanged. After RET it will also jump to the location selected
  6769. in the indirect buffer and expose the headline hierarchy above.
  6770. With a prefix argument, use the alternative interface: e.g., if
  6771. `org-goto-interface' is `outline' use `outline-path-completion'."
  6772. (interactive "P")
  6773. (org-goto-map)
  6774. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6775. (org-refile-use-outline-path t)
  6776. (org-refile-target-verify-function nil)
  6777. (interface
  6778. (if (not alternative-interface)
  6779. org-goto-interface
  6780. (if (eq org-goto-interface 'outline)
  6781. 'outline-path-completion
  6782. 'outline)))
  6783. (org-goto-start-pos (point))
  6784. (selected-point
  6785. (if (eq interface 'outline)
  6786. (car (org-get-location (current-buffer) org-goto-help))
  6787. (let ((pa (org-refile-get-location "Goto")))
  6788. (org-refile-check-position pa)
  6789. (nth 3 pa)))))
  6790. (if selected-point
  6791. (progn
  6792. (org-mark-ring-push org-goto-start-pos)
  6793. (goto-char selected-point)
  6794. (when (or (outline-invisible-p) (org-invisible-p2))
  6795. (org-show-context 'org-goto)))
  6796. (message "Quit"))))
  6797. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6798. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6799. (defvar org-goto-local-auto-isearch-map) ; defined below
  6800. (defun org-get-location (_buf help)
  6801. "Let the user select a location in current buffer.
  6802. This function uses a recursive edit. It returns the selected position
  6803. or nil."
  6804. (org-no-popups
  6805. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6806. (isearch-hide-immediately nil)
  6807. (isearch-search-fun-function
  6808. (lambda () 'org-goto-local-search-headings))
  6809. (org-goto-selected-point org-goto-exit-command))
  6810. (save-excursion
  6811. (save-window-excursion
  6812. (delete-other-windows)
  6813. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6814. (pop-to-buffer-same-window
  6815. (condition-case nil
  6816. (make-indirect-buffer (current-buffer) "*org-goto*")
  6817. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6818. (with-output-to-temp-buffer "*Org Help*"
  6819. (princ (format help (if org-goto-auto-isearch
  6820. " Just type for auto-isearch."
  6821. " n/p/f/b/u to navigate, q to quit."))))
  6822. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6823. (setq buffer-read-only nil)
  6824. (let ((org-startup-truncated t)
  6825. (org-startup-folded nil)
  6826. (org-startup-align-all-tables nil))
  6827. (org-mode)
  6828. (org-overview))
  6829. (setq buffer-read-only t)
  6830. (if (and (boundp 'org-goto-start-pos)
  6831. (integer-or-marker-p org-goto-start-pos))
  6832. (progn (goto-char org-goto-start-pos)
  6833. (when (outline-invisible-p)
  6834. (org-show-set-visibility 'lineage)))
  6835. (goto-char (point-min)))
  6836. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6837. (message "Select location and press RET")
  6838. (use-local-map org-goto-map)
  6839. (recursive-edit)))
  6840. (kill-buffer "*org-goto*")
  6841. (cons org-goto-selected-point org-goto-exit-command))))
  6842. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6843. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6844. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6845. (if (fboundp 'isearch-other-control-char)
  6846. (progn
  6847. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6848. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6849. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6850. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6851. (define-key org-goto-local-auto-isearch-map [return] nil))
  6852. (defun org-goto-local-search-headings (string bound noerror)
  6853. "Search and make sure that any matches are in headlines."
  6854. (catch 'return
  6855. (while (if isearch-forward
  6856. (search-forward string bound noerror)
  6857. (search-backward string bound noerror))
  6858. (when (save-match-data
  6859. (and (save-excursion
  6860. (beginning-of-line)
  6861. (looking-at org-complex-heading-regexp))
  6862. (or (not (match-beginning 5))
  6863. (< (point) (match-beginning 5)))))
  6864. (throw 'return (point))))))
  6865. (defun org-goto-local-auto-isearch ()
  6866. "Start isearch."
  6867. (interactive)
  6868. (goto-char (point-min))
  6869. (let ((keys (this-command-keys)))
  6870. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6871. (isearch-mode t)
  6872. (isearch-process-search-char (string-to-char keys)))))
  6873. (defun org-goto-ret (&optional _arg)
  6874. "Finish `org-goto' by going to the new location."
  6875. (interactive "P")
  6876. (setq org-goto-selected-point (point))
  6877. (setq org-goto-exit-command 'return)
  6878. (throw 'exit nil))
  6879. (defun org-goto-left ()
  6880. "Finish `org-goto' by going to the new location."
  6881. (interactive)
  6882. (if (org-at-heading-p)
  6883. (progn
  6884. (beginning-of-line 1)
  6885. (setq org-goto-selected-point (point)
  6886. org-goto-exit-command 'left)
  6887. (throw 'exit nil))
  6888. (user-error "Not on a heading")))
  6889. (defun org-goto-right ()
  6890. "Finish `org-goto' by going to the new location."
  6891. (interactive)
  6892. (if (org-at-heading-p)
  6893. (progn
  6894. (setq org-goto-selected-point (point)
  6895. org-goto-exit-command 'right)
  6896. (throw 'exit nil))
  6897. (user-error "Not on a heading")))
  6898. (defun org-goto-quit ()
  6899. "Finish `org-goto' without cursor motion."
  6900. (interactive)
  6901. (setq org-goto-selected-point nil)
  6902. (setq org-goto-exit-command 'quit)
  6903. (throw 'exit nil))
  6904. ;;; Indirect buffer display of subtrees
  6905. (defvar org-indirect-dedicated-frame nil
  6906. "This is the frame being used for indirect tree display.")
  6907. (defvar org-last-indirect-buffer nil)
  6908. (defun org-tree-to-indirect-buffer (&optional arg)
  6909. "Create indirect buffer and narrow it to current subtree.
  6910. With a numerical prefix ARG, go up to this level and then take that tree.
  6911. If ARG is negative, go up that many levels.
  6912. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6913. indirect buffer previously made with this command, to avoid proliferation of
  6914. indirect buffers. However, when you call the command with a \
  6915. \\[universal-argument] prefix, or
  6916. when `org-indirect-buffer-display' is `new-frame', the last buffer
  6917. is kept so that you can work with several indirect buffers at the same time.
  6918. If `org-indirect-buffer-display' is `dedicated-frame', the \
  6919. \\[universal-argument] prefix also
  6920. requests that a new frame be made for the new buffer, so that the dedicated
  6921. frame is not changed."
  6922. (interactive "P")
  6923. (let ((cbuf (current-buffer))
  6924. (cwin (selected-window))
  6925. (pos (point))
  6926. beg end level heading ibuf)
  6927. (save-excursion
  6928. (org-back-to-heading t)
  6929. (when (numberp arg)
  6930. (setq level (org-outline-level))
  6931. (when (< arg 0) (setq arg (+ level arg)))
  6932. (while (> (setq level (org-outline-level)) arg)
  6933. (org-up-heading-safe)))
  6934. (setq beg (point)
  6935. heading (org-get-heading 'no-tags))
  6936. (org-end-of-subtree t t)
  6937. (when (org-at-heading-p) (backward-char 1))
  6938. (setq end (point)))
  6939. (when (and (buffer-live-p org-last-indirect-buffer)
  6940. (not (eq org-indirect-buffer-display 'new-frame))
  6941. (not arg))
  6942. (kill-buffer org-last-indirect-buffer))
  6943. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6944. org-last-indirect-buffer ibuf)
  6945. (cond
  6946. ((or (eq org-indirect-buffer-display 'new-frame)
  6947. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6948. (select-frame (make-frame))
  6949. (delete-other-windows)
  6950. (pop-to-buffer-same-window ibuf)
  6951. (org-set-frame-title heading))
  6952. ((eq org-indirect-buffer-display 'dedicated-frame)
  6953. (raise-frame
  6954. (select-frame (or (and org-indirect-dedicated-frame
  6955. (frame-live-p org-indirect-dedicated-frame)
  6956. org-indirect-dedicated-frame)
  6957. (setq org-indirect-dedicated-frame (make-frame)))))
  6958. (delete-other-windows)
  6959. (pop-to-buffer-same-window ibuf)
  6960. (org-set-frame-title (concat "Indirect: " heading)))
  6961. ((eq org-indirect-buffer-display 'current-window)
  6962. (pop-to-buffer-same-window ibuf))
  6963. ((eq org-indirect-buffer-display 'other-window)
  6964. (pop-to-buffer ibuf))
  6965. (t (error "Invalid value")))
  6966. (narrow-to-region beg end)
  6967. (outline-show-all)
  6968. (goto-char pos)
  6969. (run-hook-with-args 'org-cycle-hook 'all)
  6970. (and (window-live-p cwin) (select-window cwin))))
  6971. (defun org-get-indirect-buffer (&optional buffer heading)
  6972. (setq buffer (or buffer (current-buffer)))
  6973. (let ((n 1) (base (buffer-name buffer)) bname)
  6974. (while (buffer-live-p
  6975. (get-buffer
  6976. (setq bname
  6977. (concat base "-"
  6978. (if heading (concat heading "-" (number-to-string n))
  6979. (number-to-string n))))))
  6980. (setq n (1+ n)))
  6981. (condition-case nil
  6982. (make-indirect-buffer buffer bname 'clone)
  6983. (error (make-indirect-buffer buffer bname)))))
  6984. (defun org-set-frame-title (title)
  6985. "Set the title of the current frame to the string TITLE."
  6986. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6987. ;;;; Structure editing
  6988. ;;; Inserting headlines
  6989. (defun org--line-empty-p (n)
  6990. "Is the Nth next line empty?
  6991. Counts the current line as N = 1 and the previous line as N = 0;
  6992. see `beginning-of-line'."
  6993. (save-excursion
  6994. (and (not (bobp))
  6995. (or (beginning-of-line n) t)
  6996. (save-match-data
  6997. (looking-at "[ \t]*$")))))
  6998. (defun org-previous-line-empty-p ()
  6999. "Is the previous line a blank line?
  7000. When NEXT is non-nil, check the next line instead."
  7001. (org--line-empty-p 0))
  7002. (defun org-next-line-empty-p ()
  7003. "Is the previous line a blank line?
  7004. When NEXT is non-nil, check the next line instead."
  7005. (org--line-empty-p 2))
  7006. (defun org-insert-heading (&optional arg invisible-ok top)
  7007. "Insert a new heading or an item with the same depth at point.
  7008. If point is at the beginning of a heading or a list item, insert
  7009. a new heading or a new item above the current one. If point is
  7010. at the beginning of a normal line, turn the line into a heading.
  7011. If point is in the middle of a headline or a list item, split the
  7012. headline or the item and create a new headline/item with the text
  7013. in the current line after point \(see `org-M-RET-may-split-line'
  7014. on how to modify this behavior).
  7015. With one universal prefix argument, set the user option
  7016. `org-insert-heading-respect-content' to t for the duration of
  7017. the command. This modifies the behavior described above in this
  7018. ways: on list items and at the beginning of normal lines, force
  7019. the insertion of a heading after the current subtree.
  7020. With two universal prefix arguments, insert the heading at the
  7021. end of the grandparent subtree. For example, if point is within
  7022. a 2nd-level heading, then it will insert a 2nd-level heading at
  7023. the end of the 1st-level parent heading.
  7024. If point is at the beginning of a headline, insert a sibling
  7025. before the current headline. If point is not at the beginning,
  7026. split the line and create a new headline with the text in the
  7027. current line after point \(see `org-M-RET-may-split-line' on how
  7028. to modify this behavior).
  7029. If point is at the beginning of a normal line, turn this line
  7030. into a heading.
  7031. When INVISIBLE-OK is set, stop at invisible headlines when going
  7032. back. This is important for non-interactive uses of the
  7033. command.
  7034. When optional argument TOP is non-nil, insert a level 1 heading,
  7035. unconditionally."
  7036. (interactive "P")
  7037. (let ((itemp (and (not top) (org-in-item-p)))
  7038. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7039. (respect-content (or org-insert-heading-respect-content
  7040. (equal arg '(4))))
  7041. (initial-content ""))
  7042. (cond
  7043. ((or (= (buffer-size) 0)
  7044. (and (not (save-excursion
  7045. (and (ignore-errors (org-back-to-heading invisible-ok))
  7046. (org-at-heading-p))))
  7047. (or arg (not itemp))))
  7048. ;; At beginning of buffer or so high up that only a heading
  7049. ;; makes sense.
  7050. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7051. ((not respect-content)
  7052. (unless may-split (end-of-line))
  7053. (insert "\n* "))
  7054. ((re-search-forward org-outline-regexp-bol nil t)
  7055. (beginning-of-line)
  7056. (insert "* \n")
  7057. (backward-char))
  7058. (t (goto-char (point-max))
  7059. (insert "\n* ")))
  7060. (run-hooks 'org-insert-heading-hook))
  7061. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7062. (t
  7063. ;; Maybe move at the end of the subtree
  7064. (when (equal arg '(16))
  7065. (org-up-heading-safe)
  7066. (org-end-of-subtree t))
  7067. ;; Insert a heading
  7068. (save-restriction
  7069. (widen)
  7070. (let* ((level nil)
  7071. (on-heading (org-at-heading-p))
  7072. (empty-line-p (if on-heading
  7073. (org-previous-line-empty-p)
  7074. ;; We will decide later
  7075. nil))
  7076. ;; Get a level string to fall back on.
  7077. (fix-level
  7078. (if (org-before-first-heading-p) "*"
  7079. (save-excursion
  7080. (org-back-to-heading t)
  7081. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7082. (looking-at org-outline-regexp)
  7083. (make-string (1- (length (match-string 0))) ?*))))
  7084. (stars
  7085. (save-excursion
  7086. (condition-case nil
  7087. (if top "* "
  7088. (org-back-to-heading invisible-ok)
  7089. (when (and (not on-heading)
  7090. (featurep 'org-inlinetask)
  7091. (integerp org-inlinetask-min-level)
  7092. (>= (length (match-string 0))
  7093. org-inlinetask-min-level))
  7094. ;; Find a heading level before the inline
  7095. ;; task.
  7096. (while (and (setq level (org-up-heading-safe))
  7097. (>= level org-inlinetask-min-level)))
  7098. (if (org-at-heading-p)
  7099. (org-back-to-heading invisible-ok)
  7100. (error "This should not happen")))
  7101. (unless (and (save-excursion
  7102. (save-match-data
  7103. (org-backward-heading-same-level
  7104. 1 invisible-ok))
  7105. (= (point) (match-beginning 0)))
  7106. (not (org-next-line-empty-p)))
  7107. (setq empty-line-p (or empty-line-p
  7108. (org-previous-line-empty-p))))
  7109. (match-string 0))
  7110. (error (or fix-level "* ")))))
  7111. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7112. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7113. ;; If we insert after content, move there and clean up
  7114. ;; whitespace.
  7115. (when (and respect-content
  7116. (not (looking-at-p org-outline-regexp-bol)))
  7117. (if (not (org-before-first-heading-p))
  7118. (org-end-of-subtree nil t)
  7119. (re-search-forward org-outline-regexp-bol)
  7120. (beginning-of-line 0))
  7121. (skip-chars-backward " \r\t\n")
  7122. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7123. (looking-at "[ \t]+") (replace-match ""))
  7124. (unless (eobp) (forward-char 1))
  7125. (when (looking-at "^\\*")
  7126. (unless (bobp) (backward-char 1))
  7127. (insert "\n")))
  7128. ;; If we are splitting, grab the text that should be moved
  7129. ;; to the new headline.
  7130. (when may-split
  7131. (if (org-at-heading-p)
  7132. ;; This is a heading: split intelligently (keeping
  7133. ;; tags).
  7134. (let ((pos (point)))
  7135. (beginning-of-line)
  7136. (unless (looking-at org-complex-heading-regexp)
  7137. (error "This should not happen"))
  7138. (when (and (match-beginning 4)
  7139. (> pos (match-beginning 4))
  7140. (< pos (match-end 4)))
  7141. (setq initial-content (buffer-substring pos (match-end 4)))
  7142. (goto-char pos)
  7143. (delete-region (point) (match-end 4))
  7144. (if (looking-at "[ \t]*$")
  7145. (replace-match "")
  7146. (insert (make-string (length initial-content) ?\s)))
  7147. (setq initial-content (org-trim initial-content)))
  7148. (goto-char pos))
  7149. ;; A normal line.
  7150. (setq initial-content
  7151. (org-trim
  7152. (delete-and-extract-region (point) (line-end-position))))))
  7153. ;; If we are at the beginning of the line, insert before it.
  7154. ;; Otherwise, after it.
  7155. (cond
  7156. ((and (bolp) (looking-at "[ \t]*$")))
  7157. ((bolp) (save-excursion (insert "\n")))
  7158. (t (end-of-line)
  7159. (insert "\n")))
  7160. ;; Insert the new heading
  7161. (insert stars)
  7162. (just-one-space)
  7163. (insert initial-content)
  7164. (unless (and blank (org-previous-line-empty-p))
  7165. (org-N-empty-lines-before-current (if blank 1 0)))
  7166. ;; Adjust visibility, which may be messed up if we removed
  7167. ;; blank lines while previous entry was hidden.
  7168. (let ((bol (line-beginning-position)))
  7169. (dolist (o (overlays-at (1- bol)))
  7170. (when (and (eq (overlay-get o 'invisible) 'outline)
  7171. (eq (overlay-end o) bol))
  7172. (move-overlay o (overlay-start o) (1- bol)))))
  7173. (run-hooks 'org-insert-heading-hook)))))))
  7174. (defun org-N-empty-lines-before-current (N)
  7175. "Make the number of empty lines before current exactly N.
  7176. So this will delete or add empty lines."
  7177. (save-excursion
  7178. (beginning-of-line)
  7179. (let ((p (point)))
  7180. (skip-chars-backward " \r\t\n")
  7181. (unless (bolp) (forward-line))
  7182. (delete-region (point) p))
  7183. (when (> N 0) (insert (make-string N ?\n)))))
  7184. (defun org-get-heading (&optional no-tags no-todo)
  7185. "Return the heading of the current entry, without the stars.
  7186. When NO-TAGS is non-nil, don't include tags.
  7187. When NO-TODO is non-nil, don't include TODO keywords."
  7188. (save-excursion
  7189. (org-back-to-heading t)
  7190. (let ((case-fold-search nil))
  7191. (cond
  7192. ((and no-tags no-todo)
  7193. (looking-at org-complex-heading-regexp)
  7194. ;; Return value has to be a string, but match group 4 is
  7195. ;; optional.
  7196. (or (match-string 4) ""))
  7197. (no-tags
  7198. (looking-at (concat org-outline-regexp
  7199. "\\(.*?\\)"
  7200. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7201. (match-string 1))
  7202. (no-todo
  7203. (looking-at org-todo-line-regexp)
  7204. (match-string 3))
  7205. (t (looking-at org-heading-regexp)
  7206. (match-string 2))))))
  7207. (defvar orgstruct-mode) ; defined below
  7208. (defun org-heading-components ()
  7209. "Return the components of the current heading.
  7210. This is a list with the following elements:
  7211. - the level as an integer
  7212. - the reduced level, different if `org-odd-levels-only' is set.
  7213. - the TODO keyword, or nil
  7214. - the priority character, like ?A, or nil if no priority is given
  7215. - the headline text itself, or the tags string if no headline text
  7216. - the tags string, or nil."
  7217. (save-excursion
  7218. (org-back-to-heading t)
  7219. (when (let (case-fold-search)
  7220. (looking-at
  7221. (if orgstruct-mode
  7222. org-heading-regexp
  7223. org-complex-heading-regexp)))
  7224. (if orgstruct-mode
  7225. (list (length (match-string 1))
  7226. (org-reduced-level (length (match-string 1)))
  7227. nil
  7228. nil
  7229. (match-string 2)
  7230. nil)
  7231. (list (length (match-string 1))
  7232. (org-reduced-level (length (match-string 1)))
  7233. (match-string-no-properties 2)
  7234. (and (match-end 3) (aref (match-string 3) 2))
  7235. (match-string-no-properties 4)
  7236. (match-string-no-properties 5))))))
  7237. (defun org-get-entry ()
  7238. "Get the entry text, after heading, entire subtree."
  7239. (save-excursion
  7240. (org-back-to-heading t)
  7241. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7242. (defun org-edit-headline (&optional heading)
  7243. "Edit the current headline.
  7244. Set it to HEADING when provided."
  7245. (interactive)
  7246. (org-with-wide-buffer
  7247. (org-back-to-heading t)
  7248. (when (looking-at org-complex-heading-regexp)
  7249. (let* ((old (match-string-no-properties 4))
  7250. (new (save-match-data
  7251. (org-trim (or heading (read-string "Edit: " old))))))
  7252. (unless (equal old new)
  7253. (if old (replace-match new t t nil 4)
  7254. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7255. (insert " " new))
  7256. (org-set-tags nil t)
  7257. (when (looking-at "[ \t]*$") (replace-match "")))))))
  7258. (defun org-insert-heading-after-current ()
  7259. "Insert a new heading with same level as current, after current subtree."
  7260. (interactive)
  7261. (org-back-to-heading)
  7262. (org-insert-heading)
  7263. (org-move-subtree-down)
  7264. (end-of-line 1))
  7265. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7266. "Insert heading with `org-insert-heading-respect-content' set to t."
  7267. (interactive)
  7268. (org-insert-heading '(4) invisible-ok))
  7269. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7270. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7271. (interactive)
  7272. (org-insert-todo-heading force-state '(4)))
  7273. (defun org-insert-todo-heading (arg &optional force-heading)
  7274. "Insert a new heading with the same level and TODO state as current heading.
  7275. If the heading has no TODO state, or if the state is DONE, use the first
  7276. state (TODO by default). Also with one prefix arg, force first state. With
  7277. two prefix args, force inserting at the end of the parent subtree."
  7278. (interactive "P")
  7279. (when (or force-heading (not (org-insert-item 'checkbox)))
  7280. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7281. force-heading))
  7282. (save-excursion
  7283. (org-back-to-heading)
  7284. (outline-previous-heading)
  7285. (looking-at org-todo-line-regexp))
  7286. (let*
  7287. ((new-mark-x
  7288. (if (or (equal arg '(4))
  7289. (not (match-beginning 2))
  7290. (member (match-string 2) org-done-keywords))
  7291. (car org-todo-keywords-1)
  7292. (match-string 2)))
  7293. (new-mark
  7294. (or
  7295. (run-hook-with-args-until-success
  7296. 'org-todo-get-default-hook new-mark-x nil)
  7297. new-mark-x)))
  7298. (beginning-of-line 1)
  7299. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7300. (if org-treat-insert-todo-heading-as-state-change
  7301. (org-todo new-mark)
  7302. (insert new-mark " "))))
  7303. (when org-provide-todo-statistics
  7304. (org-update-parent-todo-statistics))))
  7305. (defun org-insert-subheading (arg)
  7306. "Insert a new subheading and demote it.
  7307. Works for outline headings and for plain lists alike."
  7308. (interactive "P")
  7309. (org-insert-heading arg)
  7310. (cond
  7311. ((org-at-heading-p) (org-do-demote))
  7312. ((org-at-item-p) (org-indent-item))))
  7313. (defun org-insert-todo-subheading (arg)
  7314. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7315. Works for outline headings and for plain lists alike."
  7316. (interactive "P")
  7317. (org-insert-todo-heading arg)
  7318. (cond
  7319. ((org-at-heading-p) (org-do-demote))
  7320. ((org-at-item-p) (org-indent-item))))
  7321. ;;; Promotion and Demotion
  7322. (defvar org-after-demote-entry-hook nil
  7323. "Hook run after an entry has been demoted.
  7324. The cursor will be at the beginning of the entry.
  7325. When a subtree is being demoted, the hook will be called for each node.")
  7326. (defvar org-after-promote-entry-hook nil
  7327. "Hook run after an entry has been promoted.
  7328. The cursor will be at the beginning of the entry.
  7329. When a subtree is being promoted, the hook will be called for each node.")
  7330. (defun org-promote-subtree ()
  7331. "Promote the entire subtree.
  7332. See also `org-promote'."
  7333. (interactive)
  7334. (save-excursion
  7335. (org-with-limited-levels (org-map-tree 'org-promote)))
  7336. (org-fix-position-after-promote))
  7337. (defun org-demote-subtree ()
  7338. "Demote the entire subtree.
  7339. See `org-demote' and `org-promote'."
  7340. (interactive)
  7341. (save-excursion
  7342. (org-with-limited-levels (org-map-tree 'org-demote)))
  7343. (org-fix-position-after-promote))
  7344. (defun org-do-promote ()
  7345. "Promote the current heading higher up the tree.
  7346. If the region is active in `transient-mark-mode', promote all
  7347. headings in the region."
  7348. (interactive)
  7349. (save-excursion
  7350. (if (org-region-active-p)
  7351. (org-map-region 'org-promote (region-beginning) (region-end))
  7352. (org-promote)))
  7353. (org-fix-position-after-promote))
  7354. (defun org-do-demote ()
  7355. "Demote the current heading lower down the tree.
  7356. If the region is active in `transient-mark-mode', demote all
  7357. headings in the region."
  7358. (interactive)
  7359. (save-excursion
  7360. (if (org-region-active-p)
  7361. (org-map-region 'org-demote (region-beginning) (region-end))
  7362. (org-demote)))
  7363. (org-fix-position-after-promote))
  7364. (defun org-fix-position-after-promote ()
  7365. "Fix cursor position and indentation after demoting/promoting."
  7366. (let ((pos (point)))
  7367. (when (save-excursion
  7368. (beginning-of-line 1)
  7369. (looking-at org-todo-line-regexp)
  7370. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7371. (cond ((eobp) (insert " "))
  7372. ((eolp) (insert " "))
  7373. ((equal (char-after) ?\ ) (forward-char 1))))))
  7374. (defun org-current-level ()
  7375. "Return the level of the current entry, or nil if before the first headline.
  7376. The level is the number of stars at the beginning of the
  7377. headline. Use `org-reduced-level' to remove the effect of
  7378. `org-odd-levels'. Unlike to `org-outline-level', this function
  7379. ignores inlinetasks."
  7380. (let ((level (org-with-limited-levels (org-outline-level))))
  7381. (and (> level 0) level)))
  7382. (defun org-get-previous-line-level ()
  7383. "Return the outline depth of the last headline before the current line.
  7384. Returns 0 for the first headline in the buffer, and nil if before the
  7385. first headline."
  7386. (and (org-current-level)
  7387. (or (and (/= (line-beginning-position) (point-min))
  7388. (save-excursion (beginning-of-line 0) (org-current-level)))
  7389. 0)))
  7390. (defun org-reduced-level (l)
  7391. "Compute the effective level of a heading.
  7392. This takes into account the setting of `org-odd-levels-only'."
  7393. (cond
  7394. ((zerop l) 0)
  7395. (org-odd-levels-only (1+ (floor (/ l 2))))
  7396. (t l)))
  7397. (defun org-level-increment ()
  7398. "Return the number of stars that will be added or removed at a
  7399. time to headlines when structure editing, based on the value of
  7400. `org-odd-levels-only'."
  7401. (if org-odd-levels-only 2 1))
  7402. (defun org-get-valid-level (level &optional change)
  7403. "Rectify a level change under the influence of `org-odd-levels-only'
  7404. LEVEL is a current level, CHANGE is by how much the level should be
  7405. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7406. even level numbers will become the next higher odd number."
  7407. (if org-odd-levels-only
  7408. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7409. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7410. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7411. (max 1 (+ level (or change 0)))))
  7412. (defun org-promote ()
  7413. "Promote the current heading higher up the tree."
  7414. (org-with-wide-buffer
  7415. (org-back-to-heading t)
  7416. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7417. after-change-functions))
  7418. (level (save-match-data (funcall outline-level)))
  7419. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7420. (diff (abs (- level (length up-head) -1))))
  7421. (cond
  7422. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7423. (replace-match "# " nil t))
  7424. ((= level 1)
  7425. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7426. (t (replace-match up-head nil t)))
  7427. (unless (= level 1)
  7428. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7429. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7430. (run-hooks 'org-after-promote-entry-hook))))
  7431. (defun org-demote ()
  7432. "Demote the current heading lower down the tree."
  7433. (org-with-wide-buffer
  7434. (org-back-to-heading t)
  7435. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7436. after-change-functions))
  7437. (level (save-match-data (funcall outline-level)))
  7438. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7439. (diff (abs (- level (length down-head) -1))))
  7440. (replace-match down-head nil t)
  7441. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7442. (when org-adapt-indentation (org-fixup-indentation diff))
  7443. (run-hooks 'org-after-demote-entry-hook))))
  7444. (defun org-cycle-level ()
  7445. "Cycle the level of an empty headline through possible states.
  7446. This goes first to child, then to parent, level, then up the hierarchy.
  7447. After top level, it switches back to sibling level."
  7448. (interactive)
  7449. (let ((org-adapt-indentation nil))
  7450. (when (org-point-at-end-of-empty-headline)
  7451. (setq this-command 'org-cycle-level) ; Only needed for caching
  7452. (let ((cur-level (org-current-level))
  7453. (prev-level (org-get-previous-line-level)))
  7454. (cond
  7455. ;; If first headline in file, promote to top-level.
  7456. ((= prev-level 0)
  7457. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7458. do (org-do-promote)))
  7459. ;; If same level as prev, demote one.
  7460. ((= prev-level cur-level)
  7461. (org-do-demote))
  7462. ;; If parent is top-level, promote to top level if not already.
  7463. ((= prev-level 1)
  7464. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7465. do (org-do-promote)))
  7466. ;; If top-level, return to prev-level.
  7467. ((= cur-level 1)
  7468. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7469. do (org-do-demote)))
  7470. ;; If less than prev-level, promote one.
  7471. ((< cur-level prev-level)
  7472. (org-do-promote))
  7473. ;; If deeper than prev-level, promote until higher than
  7474. ;; prev-level.
  7475. ((> cur-level prev-level)
  7476. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7477. do (org-do-promote))))
  7478. t))))
  7479. (defun org-map-tree (fun)
  7480. "Call FUN for every heading underneath the current one."
  7481. (org-back-to-heading t)
  7482. (let ((level (funcall outline-level)))
  7483. (save-excursion
  7484. (funcall fun)
  7485. (while (and (progn
  7486. (outline-next-heading)
  7487. (> (funcall outline-level) level))
  7488. (not (eobp)))
  7489. (funcall fun)))))
  7490. (defun org-map-region (fun beg end)
  7491. "Call FUN for every heading between BEG and END."
  7492. (let ((org-ignore-region t))
  7493. (save-excursion
  7494. (setq end (copy-marker end))
  7495. (goto-char beg)
  7496. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7497. (< (point) end))
  7498. (funcall fun))
  7499. (while (and (progn
  7500. (outline-next-heading)
  7501. (< (point) end))
  7502. (not (eobp)))
  7503. (funcall fun)))))
  7504. (defun org-fixup-indentation (diff)
  7505. "Change the indentation in the current entry by DIFF.
  7506. DIFF is an integer. Indentation is done according to the
  7507. following rules:
  7508. - Planning information and property drawers are always indented
  7509. according to the new level of the headline;
  7510. - Footnote definitions and their contents are ignored;
  7511. - Inlinetasks' boundaries are not shifted;
  7512. - Empty lines are ignored;
  7513. - Other lines' indentation are shifted by DIFF columns, unless
  7514. it would introduce a structural change in the document, in
  7515. which case no shifting is done at all.
  7516. Assume point is at a heading or an inlinetask beginning."
  7517. (org-with-wide-buffer
  7518. (narrow-to-region (line-beginning-position)
  7519. (save-excursion
  7520. (if (org-with-limited-levels (org-at-heading-p))
  7521. (org-with-limited-levels (outline-next-heading))
  7522. (org-inlinetask-goto-end))
  7523. (point)))
  7524. (forward-line)
  7525. ;; Indent properly planning info and property drawer.
  7526. (when (looking-at-p org-planning-line-re)
  7527. (org-indent-line)
  7528. (forward-line))
  7529. (when (looking-at org-property-drawer-re)
  7530. (goto-char (match-end 0))
  7531. (forward-line)
  7532. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7533. (catch 'no-shift
  7534. (when (zerop diff) (throw 'no-shift nil))
  7535. ;; If DIFF is negative, first check if a shift is possible at all
  7536. ;; (e.g., it doesn't break structure). This can only happen if
  7537. ;; some contents are not properly indented.
  7538. (let ((case-fold-search t))
  7539. (when (< diff 0)
  7540. (let ((diff (- diff))
  7541. (forbidden-re (concat org-outline-regexp
  7542. "\\|"
  7543. (substring org-footnote-definition-re 1))))
  7544. (save-excursion
  7545. (while (not (eobp))
  7546. (cond
  7547. ((looking-at-p "[ \t]*$") (forward-line))
  7548. ((and (looking-at-p org-footnote-definition-re)
  7549. (let ((e (org-element-at-point)))
  7550. (and (eq (org-element-type e) 'footnote-definition)
  7551. (goto-char (org-element-property :end e))))))
  7552. ((looking-at-p org-outline-regexp) (forward-line))
  7553. ;; Give up if shifting would move before column 0 or
  7554. ;; if it would introduce a headline or a footnote
  7555. ;; definition.
  7556. (t
  7557. (skip-chars-forward " \t")
  7558. (let ((ind (current-column)))
  7559. (when (or (< ind diff)
  7560. (and (= ind diff) (looking-at-p forbidden-re)))
  7561. (throw 'no-shift nil)))
  7562. ;; Ignore contents of example blocks and source
  7563. ;; blocks if their indentation is meant to be
  7564. ;; preserved. Jump to block's closing line.
  7565. (beginning-of-line)
  7566. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7567. (let ((e (org-element-at-point)))
  7568. (and (memq (org-element-type e)
  7569. '(example-block src-block))
  7570. (or org-src-preserve-indentation
  7571. (org-element-property :preserve-indent e))
  7572. (goto-char (org-element-property :end e))
  7573. (progn (skip-chars-backward " \r\t\n")
  7574. (beginning-of-line)
  7575. t))))
  7576. (forward-line))))))))
  7577. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7578. ;; by DIFF. Also skip contents of source or example blocks
  7579. ;; when indentation is meant to be preserved.
  7580. (while (not (eobp))
  7581. (cond
  7582. ((and (looking-at-p org-footnote-definition-re)
  7583. (let ((e (org-element-at-point)))
  7584. (and (eq (org-element-type e) 'footnote-definition)
  7585. (goto-char (org-element-property :end e))))))
  7586. ((looking-at-p org-outline-regexp) (forward-line))
  7587. ((looking-at-p "[ \t]*$") (forward-line))
  7588. (t
  7589. (indent-line-to (+ (org-get-indentation) diff))
  7590. (beginning-of-line)
  7591. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7592. (let ((e (org-element-at-point)))
  7593. (and (memq (org-element-type e)
  7594. '(example-block src-block))
  7595. (or org-src-preserve-indentation
  7596. (org-element-property :preserve-indent e))
  7597. (goto-char (org-element-property :end e))
  7598. (progn (skip-chars-backward " \r\t\n")
  7599. (beginning-of-line)
  7600. t))))
  7601. (forward-line)))))))))
  7602. (defun org-convert-to-odd-levels ()
  7603. "Convert an Org file with all levels allowed to one with odd levels.
  7604. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7605. level 5 etc."
  7606. (interactive)
  7607. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7608. (let ((outline-level 'org-outline-level)
  7609. (org-odd-levels-only nil) n)
  7610. (save-excursion
  7611. (goto-char (point-min))
  7612. (while (re-search-forward "^\\*\\*+ " nil t)
  7613. (setq n (- (length (match-string 0)) 2))
  7614. (while (>= (setq n (1- n)) 0)
  7615. (org-demote))
  7616. (end-of-line 1))))))
  7617. (defun org-convert-to-oddeven-levels ()
  7618. "Convert an Org file with only odd levels to one with odd/even levels.
  7619. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7620. file contains a section with an even level, conversion would
  7621. destroy the structure of the file. An error is signaled in this
  7622. case."
  7623. (interactive)
  7624. (goto-char (point-min))
  7625. ;; First check if there are no even levels
  7626. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7627. (org-show-set-visibility 'canonical)
  7628. (error "Not all levels are odd in this file. Conversion not possible"))
  7629. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7630. (let ((outline-regexp org-outline-regexp)
  7631. (outline-level 'org-outline-level)
  7632. (org-odd-levels-only nil) n)
  7633. (save-excursion
  7634. (goto-char (point-min))
  7635. (while (re-search-forward "^\\*\\*+ " nil t)
  7636. (setq n (/ (1- (length (match-string 0))) 2))
  7637. (while (>= (setq n (1- n)) 0)
  7638. (org-promote))
  7639. (end-of-line 1))))))
  7640. (defun org-tr-level (n)
  7641. "Make N odd if required."
  7642. (if org-odd-levels-only (1+ (/ n 2)) n))
  7643. ;;; Vertical tree motion, cutting and pasting of subtrees
  7644. (defun org-move-subtree-up (&optional arg)
  7645. "Move the current subtree up past ARG headlines of the same level."
  7646. (interactive "p")
  7647. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7648. (defun org-move-subtree-down (&optional arg)
  7649. "Move the current subtree down past ARG headlines of the same level."
  7650. (interactive "p")
  7651. (setq arg (prefix-numeric-value arg))
  7652. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7653. 'org-get-last-sibling))
  7654. (ins-point (make-marker))
  7655. (cnt (abs arg))
  7656. (col (current-column))
  7657. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7658. ;; Select the tree
  7659. (org-back-to-heading)
  7660. (setq beg0 (point))
  7661. (save-excursion
  7662. (setq ne-beg (org-back-over-empty-lines))
  7663. (setq beg (point)))
  7664. (save-match-data
  7665. (save-excursion (outline-end-of-heading)
  7666. (setq folded (outline-invisible-p)))
  7667. (progn (org-end-of-subtree nil t)
  7668. (unless (eobp) (backward-char))))
  7669. (outline-next-heading)
  7670. (setq ne-end (org-back-over-empty-lines))
  7671. (setq end (point))
  7672. (goto-char beg0)
  7673. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7674. ;; include less whitespace
  7675. (save-excursion
  7676. (goto-char beg)
  7677. (forward-line (- ne-beg ne-end))
  7678. (setq beg (point))))
  7679. ;; Find insertion point, with error handling
  7680. (while (> cnt 0)
  7681. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7682. (progn (goto-char beg0)
  7683. (user-error "Cannot move past superior level or buffer limit")))
  7684. (setq cnt (1- cnt)))
  7685. (when (> arg 0)
  7686. ;; Moving forward - still need to move over subtree
  7687. (org-end-of-subtree t t)
  7688. (save-excursion
  7689. (org-back-over-empty-lines)
  7690. (or (bolp) (newline))))
  7691. (setq ne-ins (org-back-over-empty-lines))
  7692. (move-marker ins-point (point))
  7693. (setq txt (buffer-substring beg end))
  7694. (org-save-markers-in-region beg end)
  7695. (delete-region beg end)
  7696. (org-remove-empty-overlays-at beg)
  7697. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7698. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7699. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7700. (let ((bbb (point)))
  7701. (insert-before-markers txt)
  7702. (org-reinstall-markers-in-region bbb)
  7703. (move-marker ins-point bbb))
  7704. (or (bolp) (insert "\n"))
  7705. (setq ins-end (point))
  7706. (goto-char ins-point)
  7707. (org-skip-whitespace)
  7708. (when (and (< arg 0)
  7709. (org-first-sibling-p)
  7710. (> ne-ins ne-beg))
  7711. ;; Move whitespace back to beginning
  7712. (save-excursion
  7713. (goto-char ins-end)
  7714. (let ((kill-whole-line t))
  7715. (kill-line (- ne-ins ne-beg)) (point)))
  7716. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7717. (move-marker ins-point nil)
  7718. (if folded
  7719. (outline-hide-subtree)
  7720. (org-show-entry)
  7721. (org-show-children)
  7722. (org-cycle-hide-drawers 'children))
  7723. (org-clean-visibility-after-subtree-move)
  7724. ;; move back to the initial column we were at
  7725. (move-to-column col)))
  7726. (defvar org-subtree-clip ""
  7727. "Clipboard for cut and paste of subtrees.
  7728. This is actually only a copy of the kill, because we use the normal kill
  7729. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7730. (defvar org-subtree-clip-folded nil
  7731. "Was the last copied subtree folded?
  7732. This is used to fold the tree back after pasting.")
  7733. (defun org-cut-subtree (&optional n)
  7734. "Cut the current subtree into the clipboard.
  7735. With prefix arg N, cut this many sequential subtrees.
  7736. This is a short-hand for marking the subtree and then cutting it."
  7737. (interactive "p")
  7738. (org-copy-subtree n 'cut))
  7739. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7740. "Copy the current subtree it in the clipboard.
  7741. With prefix arg N, copy this many sequential subtrees.
  7742. This is a short-hand for marking the subtree and then copying it.
  7743. If CUT is non-nil, actually cut the subtree.
  7744. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7745. of some markers in the region, even if CUT is non-nil. This is
  7746. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7747. (interactive "p")
  7748. (let (beg end folded (beg0 (point)))
  7749. (if (called-interactively-p 'any)
  7750. (org-back-to-heading nil) ; take what looks like a subtree
  7751. (org-back-to-heading t)) ; take what is really there
  7752. (setq beg (point))
  7753. (skip-chars-forward " \t\r\n")
  7754. (save-match-data
  7755. (if nosubtrees
  7756. (outline-next-heading)
  7757. (save-excursion (outline-end-of-heading)
  7758. (setq folded (outline-invisible-p)))
  7759. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7760. (org-end-of-subtree t t)))
  7761. ;; Include the end of an inlinetask
  7762. (when (and (featurep 'org-inlinetask)
  7763. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7764. "END[ \t]*$")))
  7765. (end-of-line))
  7766. (setq end (point))
  7767. (goto-char beg0)
  7768. (when (> end beg)
  7769. (setq org-subtree-clip-folded folded)
  7770. (when (or cut force-store-markers)
  7771. (org-save-markers-in-region beg end))
  7772. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7773. (setq org-subtree-clip (current-kill 0))
  7774. (message "%s: Subtree(s) with %d characters"
  7775. (if cut "Cut" "Copied")
  7776. (length org-subtree-clip)))))
  7777. (defun org-paste-subtree (&optional level tree for-yank remove)
  7778. "Paste the clipboard as a subtree, with modification of headline level.
  7779. The entire subtree is promoted or demoted in order to match a new headline
  7780. level.
  7781. If the cursor is at the beginning of a headline, the same level as
  7782. that headline is used to paste the tree.
  7783. If not, the new level is derived from the *visible* headings
  7784. before and after the insertion point, and taken to be the inferior headline
  7785. level of the two. So if the previous visible heading is level 3 and the
  7786. next is level 4 (or vice versa), level 4 will be used for insertion.
  7787. This makes sure that the subtree remains an independent subtree and does
  7788. not swallow low level entries.
  7789. You can also force a different level, either by using a numeric prefix
  7790. argument, or by inserting the heading marker by hand. For example, if the
  7791. cursor is after \"*****\", then the tree will be shifted to level 5.
  7792. If optional TREE is given, use this text instead of the kill ring.
  7793. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7794. move back over whitespace before inserting, and move point to the end of
  7795. the inserted text when done.
  7796. When REMOVE is non-nil, remove the subtree from the clipboard."
  7797. (interactive "P")
  7798. (setq tree (or tree (and kill-ring (current-kill 0))))
  7799. (unless (org-kill-is-subtree-p tree)
  7800. (user-error "%s"
  7801. (substitute-command-keys
  7802. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7803. (org-with-limited-levels
  7804. (let* ((visp (not (outline-invisible-p)))
  7805. (txt tree)
  7806. (^re_ "\\(\\*+\\)[ \t]*")
  7807. (old-level (if (string-match org-outline-regexp-bol txt)
  7808. (- (match-end 0) (match-beginning 0) 1)
  7809. -1))
  7810. (force-level (cond (level (prefix-numeric-value level))
  7811. ((and (looking-at "[ \t]*$")
  7812. (string-match
  7813. "^\\*+$" (buffer-substring
  7814. (point-at-bol) (point))))
  7815. (- (match-end 0) (match-beginning 0)))
  7816. ((and (bolp)
  7817. (looking-at org-outline-regexp))
  7818. (- (match-end 0) (point) 1))))
  7819. (previous-level (save-excursion
  7820. (condition-case nil
  7821. (progn
  7822. (outline-previous-visible-heading 1)
  7823. (if (looking-at ^re_)
  7824. (- (match-end 0) (match-beginning 0) 1)
  7825. 1))
  7826. (error 1))))
  7827. (next-level (save-excursion
  7828. (condition-case nil
  7829. (progn
  7830. (or (looking-at org-outline-regexp)
  7831. (outline-next-visible-heading 1))
  7832. (if (looking-at ^re_)
  7833. (- (match-end 0) (match-beginning 0) 1)
  7834. 1))
  7835. (error 1))))
  7836. (new-level (or force-level (max previous-level next-level)))
  7837. (shift (if (or (= old-level -1)
  7838. (= new-level -1)
  7839. (= old-level new-level))
  7840. 0
  7841. (- new-level old-level)))
  7842. (delta (if (> shift 0) -1 1))
  7843. (func (if (> shift 0) 'org-demote 'org-promote))
  7844. (org-odd-levels-only nil)
  7845. beg end newend)
  7846. ;; Remove the forced level indicator
  7847. (when force-level
  7848. (delete-region (point-at-bol) (point)))
  7849. ;; Paste
  7850. (beginning-of-line (if (bolp) 1 2))
  7851. (setq beg (point))
  7852. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7853. (insert-before-markers txt)
  7854. (unless (string-match "\n\\'" txt) (insert "\n"))
  7855. (setq newend (point))
  7856. (org-reinstall-markers-in-region beg)
  7857. (setq end (point))
  7858. (goto-char beg)
  7859. (skip-chars-forward " \t\n\r")
  7860. (setq beg (point))
  7861. (when (and (outline-invisible-p) visp)
  7862. (save-excursion (outline-show-heading)))
  7863. ;; Shift if necessary
  7864. (unless (= shift 0)
  7865. (save-restriction
  7866. (narrow-to-region beg end)
  7867. (while (not (= shift 0))
  7868. (org-map-region func (point-min) (point-max))
  7869. (setq shift (+ delta shift)))
  7870. (goto-char (point-min))
  7871. (setq newend (point-max))))
  7872. (when (or (called-interactively-p 'interactive) for-yank)
  7873. (message "Clipboard pasted as level %d subtree" new-level))
  7874. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7875. kill-ring
  7876. (eq org-subtree-clip (current-kill 0))
  7877. org-subtree-clip-folded)
  7878. ;; The tree was folded before it was killed/copied
  7879. (outline-hide-subtree))
  7880. (and for-yank (goto-char newend))
  7881. (and remove (setq kill-ring (cdr kill-ring))))))
  7882. (defun org-kill-is-subtree-p (&optional txt)
  7883. "Check if the current kill is an outline subtree, or a set of trees.
  7884. Returns nil if kill does not start with a headline, or if the first
  7885. headline level is not the largest headline level in the tree.
  7886. So this will actually accept several entries of equal levels as well,
  7887. which is OK for `org-paste-subtree'.
  7888. If optional TXT is given, check this string instead of the current kill."
  7889. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7890. (re (org-get-limited-outline-regexp))
  7891. (^re (concat "^" re))
  7892. (start-level (and kill
  7893. (string-match
  7894. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7895. kill)
  7896. (- (match-end 2) (match-beginning 2) 1)))
  7897. (start (1+ (or (match-beginning 2) -1))))
  7898. (if (not start-level)
  7899. (progn
  7900. nil) ;; does not even start with a heading
  7901. (catch 'exit
  7902. (while (setq start (string-match ^re kill (1+ start)))
  7903. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7904. (throw 'exit nil)))
  7905. t))))
  7906. (defvar org-markers-to-move nil
  7907. "Markers that should be moved with a cut-and-paste operation.
  7908. Those markers are stored together with their positions relative to
  7909. the start of the region.")
  7910. (defun org-save-markers-in-region (beg end)
  7911. "Check markers in region.
  7912. If these markers are between BEG and END, record their position relative
  7913. to BEG, so that after moving the block of text, we can put the markers back
  7914. into place.
  7915. This function gets called just before an entry or tree gets cut from the
  7916. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7917. called immediately, to move the markers with the entries."
  7918. (setq org-markers-to-move nil)
  7919. (when (featurep 'org-clock)
  7920. (org-clock-save-markers-for-cut-and-paste beg end))
  7921. (when (featurep 'org-agenda)
  7922. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7923. (defun org-check-and-save-marker (marker beg end)
  7924. "Check if MARKER is between BEG and END.
  7925. If yes, remember the marker and the distance to BEG."
  7926. (when (and (marker-buffer marker)
  7927. (equal (marker-buffer marker) (current-buffer))
  7928. (>= marker beg) (< marker end))
  7929. (push (cons marker (- marker beg)) org-markers-to-move)))
  7930. (defun org-reinstall-markers-in-region (beg)
  7931. "Move all remembered markers to their position relative to BEG."
  7932. (dolist (x org-markers-to-move)
  7933. (move-marker (car x) (+ beg (cdr x))))
  7934. (setq org-markers-to-move nil))
  7935. (defun org-narrow-to-subtree ()
  7936. "Narrow buffer to the current subtree."
  7937. (interactive)
  7938. (save-excursion
  7939. (save-match-data
  7940. (org-with-limited-levels
  7941. (narrow-to-region
  7942. (progn (org-back-to-heading t) (point))
  7943. (progn (org-end-of-subtree t t)
  7944. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7945. (point)))))))
  7946. (defun org-narrow-to-block ()
  7947. "Narrow buffer to the current block."
  7948. (interactive)
  7949. (let* ((case-fold-search t)
  7950. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7951. "^[ \t]*#\\+end_.*")))
  7952. (if blockp
  7953. (narrow-to-region (car blockp) (cdr blockp))
  7954. (user-error "Not in a block"))))
  7955. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7956. "Clone the task (subtree) at point N times.
  7957. The clones will be inserted as siblings.
  7958. In interactive use, the user will be prompted for the number of
  7959. clones to be produced. If the entry has a timestamp, the user
  7960. will also be prompted for a time shift, which may be a repeater
  7961. as used in time stamps, for example `+3d'. To disable this,
  7962. you can call the function with a universal prefix argument.
  7963. When a valid repeater is given and the entry contains any time
  7964. stamps, the clones will become a sequence in time, with time
  7965. stamps in the subtree shifted for each clone produced. If SHIFT
  7966. is nil or the empty string, time stamps will be left alone. The
  7967. ID property of the original subtree is removed.
  7968. If the original subtree did contain time stamps with a repeater,
  7969. the following will happen:
  7970. - the repeater will be removed in each clone
  7971. - an additional clone will be produced, with the current, unshifted
  7972. date(s) in the entry.
  7973. - the original entry will be placed *after* all the clones, with
  7974. repeater intact.
  7975. - the start days in the repeater in the original entry will be shifted
  7976. to past the last clone.
  7977. In this way you can spell out a number of instances of a repeating task,
  7978. and still retain the repeater to cover future instances of the task.
  7979. As described above, N+1 clones are produced when the original
  7980. subtree has a repeater. Setting N to 0, then, can be used to
  7981. remove the repeater from a subtree and create a shifted clone
  7982. with the original repeater."
  7983. (interactive "nNumber of clones to produce: ")
  7984. (let ((shift
  7985. (or shift
  7986. (if (and (not (equal current-prefix-arg '(4)))
  7987. (save-excursion
  7988. (re-search-forward org-ts-regexp-both
  7989. (save-excursion
  7990. (org-end-of-subtree t)
  7991. (point)) t)))
  7992. (read-from-minibuffer
  7993. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7994. ""))) ;; No time shift
  7995. (n-no-remove -1)
  7996. (drawer-re org-drawer-regexp)
  7997. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7998. beg end template task idprop
  7999. shift-n shift-what doshift nmin nmax)
  8000. (unless (wholenump n)
  8001. (user-error "Invalid number of replications %s" n))
  8002. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  8003. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  8004. shift)))
  8005. (user-error "Invalid shift specification %s" shift))
  8006. (when doshift
  8007. (setq shift-n (string-to-number (match-string 1 shift))
  8008. shift-what (cdr (assoc (match-string 2 shift)
  8009. '(("d" . day) ("w" . week)
  8010. ("m" . month) ("y" . year))))))
  8011. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  8012. (setq nmin 1 nmax n)
  8013. (org-back-to-heading t)
  8014. (setq beg (point))
  8015. (setq idprop (org-entry-get nil "ID"))
  8016. (org-end-of-subtree t t)
  8017. (or (bolp) (insert "\n"))
  8018. (setq end (point))
  8019. (setq template (buffer-substring beg end))
  8020. (when (and doshift
  8021. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  8022. (delete-region beg end)
  8023. (setq end beg)
  8024. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  8025. (goto-char end)
  8026. (cl-loop for n from nmin to nmax do
  8027. ;; prepare clone
  8028. (with-temp-buffer
  8029. (insert template)
  8030. (org-mode)
  8031. (goto-char (point-min))
  8032. (org-show-subtree)
  8033. (and idprop (if org-clone-delete-id
  8034. (org-entry-delete nil "ID")
  8035. (org-id-get-create t)))
  8036. (unless (= n 0)
  8037. (while (re-search-forward org-clock-re nil t)
  8038. (kill-whole-line))
  8039. (goto-char (point-min))
  8040. (while (re-search-forward drawer-re nil t)
  8041. (org-remove-empty-drawer-at (point))))
  8042. (goto-char (point-min))
  8043. (when doshift
  8044. (while (re-search-forward org-ts-regexp-both nil t)
  8045. (org-timestamp-change (* n shift-n) shift-what))
  8046. (unless (= n n-no-remove)
  8047. (goto-char (point-min))
  8048. (while (re-search-forward org-ts-regexp nil t)
  8049. (save-excursion
  8050. (goto-char (match-beginning 0))
  8051. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8052. (delete-region (match-beginning 1) (match-end 1)))))))
  8053. (setq task (buffer-string)))
  8054. (insert task))
  8055. (goto-char beg)))
  8056. ;;; Outline Sorting
  8057. (defun org-sort (with-case)
  8058. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8059. Optional argument WITH-CASE means sort case-sensitively."
  8060. (interactive "P")
  8061. (cond
  8062. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8063. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8064. (t
  8065. (org-call-with-arg 'org-sort-entries with-case))))
  8066. (defun org-sort-remove-invisible (s)
  8067. "Remove invisible links from string S."
  8068. (remove-text-properties 0 (length s) org-rm-props s)
  8069. (while (string-match org-bracket-link-regexp s)
  8070. (setq s (replace-match (if (match-end 2)
  8071. (match-string 3 s)
  8072. (match-string 1 s))
  8073. t t s)))
  8074. (let ((st (format " %s " s)))
  8075. (while (string-match org-emph-re st)
  8076. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8077. (setq s (substring st 1 -1)))
  8078. s)
  8079. (defvar org-priority-regexp) ; defined later in the file
  8080. (defvar org-after-sorting-entries-or-items-hook nil
  8081. "Hook that is run after a bunch of entries or items have been sorted.
  8082. When children are sorted, the cursor is in the parent line when this
  8083. hook gets called. When a region or a plain list is sorted, the cursor
  8084. will be in the first entry of the sorted region/list.")
  8085. (defun org-sort-entries
  8086. (&optional with-case sorting-type getkey-func compare-func property)
  8087. "Sort entries on a certain level of an outline tree.
  8088. If there is an active region, the entries in the region are sorted.
  8089. Else, if the cursor is before the first entry, sort the top-level items.
  8090. Else, the children of the entry at point are sorted.
  8091. Sorting can be alphabetically, numerically, by date/time as given by
  8092. a time stamp, by a property, by priority order, or by a custom function.
  8093. The command prompts for the sorting type unless it has been given to the
  8094. function through the SORTING-TYPE argument, which needs to be a character,
  8095. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8096. the precise meaning of each character:
  8097. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8098. c By creation time, which is assumed to be the first inactive time stamp
  8099. at the beginning of a line.
  8100. d By deadline date/time.
  8101. k By clocking time.
  8102. n Numerically, by converting the beginning of the entry/item to a number.
  8103. o By order of TODO keywords.
  8104. p By priority according to the cookie.
  8105. r By the value of a property.
  8106. s By scheduled date/time.
  8107. t By date/time, either the first active time stamp in the entry, or, if
  8108. none exist, by the first inactive one.
  8109. Capital letters will reverse the sort order.
  8110. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8111. called with point at the beginning of the record. It must return either
  8112. a string or a number that should serve as the sorting key for that record.
  8113. Comparing entries ignores case by default. However, with an optional argument
  8114. WITH-CASE, the sorting considers case as well.
  8115. Sorting is done against the visible part of the headlines, it ignores hidden
  8116. links.
  8117. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8118. (interactive "P")
  8119. (let ((case-func (if with-case 'identity 'downcase))
  8120. (cmstr
  8121. ;; The clock marker is lost when using `sort-subr', let's
  8122. ;; store the clocking string.
  8123. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8124. (save-excursion
  8125. (goto-char org-clock-marker)
  8126. (buffer-substring-no-properties (line-beginning-position)
  8127. (point)))))
  8128. start beg end stars re re2
  8129. txt what tmp)
  8130. ;; Find beginning and end of region to sort
  8131. (cond
  8132. ((org-region-active-p)
  8133. ;; we will sort the region
  8134. (setq end (region-end)
  8135. what "region")
  8136. (goto-char (region-beginning))
  8137. (unless (org-at-heading-p) (outline-next-heading))
  8138. (setq start (point)))
  8139. ((or (org-at-heading-p)
  8140. (ignore-errors (progn (org-back-to-heading) t)))
  8141. ;; we will sort the children of the current headline
  8142. (org-back-to-heading)
  8143. (setq start (point)
  8144. end (progn (org-end-of-subtree t t)
  8145. (or (bolp) (insert "\n"))
  8146. (when (>= (org-back-over-empty-lines) 1)
  8147. (forward-line 1))
  8148. (point))
  8149. what "children")
  8150. (goto-char start)
  8151. (outline-show-subtree)
  8152. (outline-next-heading))
  8153. (t
  8154. ;; we will sort the top-level entries in this file
  8155. (goto-char (point-min))
  8156. (or (org-at-heading-p) (outline-next-heading))
  8157. (setq start (point))
  8158. (goto-char (point-max))
  8159. (beginning-of-line 1)
  8160. (when (looking-at ".*?\\S-")
  8161. ;; File ends in a non-white line
  8162. (end-of-line 1)
  8163. (insert "\n"))
  8164. (setq end (point-max))
  8165. (setq what "top-level")
  8166. (goto-char start)
  8167. (outline-show-all)))
  8168. (setq beg (point))
  8169. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8170. (looking-at "\\(\\*+\\)")
  8171. (setq stars (match-string 1)
  8172. re (concat "^" (regexp-quote stars) " +")
  8173. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8174. txt (buffer-substring beg end))
  8175. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8176. (when (and (not (equal stars "*")) (string-match re2 txt))
  8177. (user-error "Region to sort contains a level above the first entry"))
  8178. (unless sorting-type
  8179. (message
  8180. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8181. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8182. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8183. what)
  8184. (setq sorting-type (read-char-exclusive))
  8185. (unless getkey-func
  8186. (and (= (downcase sorting-type) ?f)
  8187. (setq getkey-func
  8188. (completing-read "Sort using function: "
  8189. obarray 'fboundp t nil nil))
  8190. (setq getkey-func (intern getkey-func))))
  8191. (and (= (downcase sorting-type) ?r)
  8192. (not property)
  8193. (setq property
  8194. (completing-read "Property: "
  8195. (mapcar #'list (org-buffer-property-keys t))
  8196. nil t))))
  8197. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8198. (message "Sorting entries...")
  8199. (save-restriction
  8200. (narrow-to-region start end)
  8201. (let ((dcst (downcase sorting-type))
  8202. (case-fold-search nil)
  8203. (now (current-time)))
  8204. (sort-subr
  8205. (/= dcst sorting-type)
  8206. ;; This function moves to the beginning character of the "record" to
  8207. ;; be sorted.
  8208. (lambda nil
  8209. (if (re-search-forward re nil t)
  8210. (goto-char (match-beginning 0))
  8211. (goto-char (point-max))))
  8212. ;; This function moves to the last character of the "record" being
  8213. ;; sorted.
  8214. (lambda nil
  8215. (save-match-data
  8216. (condition-case nil
  8217. (outline-forward-same-level 1)
  8218. (error
  8219. (goto-char (point-max))))))
  8220. ;; This function returns the value that gets sorted against.
  8221. (lambda nil
  8222. (cond
  8223. ((= dcst ?n)
  8224. (if (looking-at org-complex-heading-regexp)
  8225. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8226. nil))
  8227. ((= dcst ?a)
  8228. (if (looking-at org-complex-heading-regexp)
  8229. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8230. nil))
  8231. ((= dcst ?k)
  8232. (or (get-text-property (point) :org-clock-minutes) 0))
  8233. ((= dcst ?t)
  8234. (let ((end (save-excursion (outline-next-heading) (point))))
  8235. (if (or (re-search-forward org-ts-regexp end t)
  8236. (re-search-forward org-ts-regexp-both end t))
  8237. (org-time-string-to-seconds (match-string 0))
  8238. (float-time now))))
  8239. ((= dcst ?c)
  8240. (let ((end (save-excursion (outline-next-heading) (point))))
  8241. (if (re-search-forward
  8242. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8243. end t)
  8244. (org-time-string-to-seconds (match-string 0))
  8245. (float-time now))))
  8246. ((= dcst ?s)
  8247. (let ((end (save-excursion (outline-next-heading) (point))))
  8248. (if (re-search-forward org-scheduled-time-regexp end t)
  8249. (org-time-string-to-seconds (match-string 1))
  8250. (float-time now))))
  8251. ((= dcst ?d)
  8252. (let ((end (save-excursion (outline-next-heading) (point))))
  8253. (if (re-search-forward org-deadline-time-regexp end t)
  8254. (org-time-string-to-seconds (match-string 1))
  8255. (float-time now))))
  8256. ((= dcst ?p)
  8257. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8258. (string-to-char (match-string 2))
  8259. org-default-priority))
  8260. ((= dcst ?r)
  8261. (or (org-entry-get nil property) ""))
  8262. ((= dcst ?o)
  8263. (when (looking-at org-complex-heading-regexp)
  8264. (let* ((m (match-string 2))
  8265. (s (if (member m org-done-keywords) '- '+)))
  8266. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8267. ((= dcst ?f)
  8268. (if getkey-func
  8269. (progn
  8270. (setq tmp (funcall getkey-func))
  8271. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8272. tmp)
  8273. (error "Invalid key function `%s'" getkey-func)))
  8274. (t (error "Invalid sorting type `%c'" sorting-type))))
  8275. nil
  8276. (cond
  8277. ((= dcst ?a) 'string<)
  8278. ((= dcst ?f) compare-func)
  8279. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8280. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8281. ;; Reset the clock marker if needed
  8282. (when cmstr
  8283. (save-excursion
  8284. (goto-char start)
  8285. (search-forward cmstr nil t)
  8286. (move-marker org-clock-marker (point))))
  8287. (message "Sorting entries...done")))
  8288. ;;; The orgstruct minor mode
  8289. ;; Define a minor mode which can be used in other modes in order to
  8290. ;; integrate the Org mode structure editing commands.
  8291. ;; This is really a hack, because the Org mode structure commands use
  8292. ;; keys which normally belong to the major mode. Here is how it
  8293. ;; works: The minor mode defines all the keys necessary to operate the
  8294. ;; structure commands, but wraps the commands into a function which
  8295. ;; tests if the cursor is currently at a headline or a plain list
  8296. ;; item. If that is the case, the structure command is used,
  8297. ;; temporarily setting many Org mode variables like regular
  8298. ;; expressions for filling etc. However, when any of those keys is
  8299. ;; used at a different location, function uses `key-binding' to look
  8300. ;; up if the key has an associated command in another currently active
  8301. ;; keymap (minor modes, major mode, global), and executes that
  8302. ;; command. There might be problems if any of the keys is otherwise
  8303. ;; used as a prefix key.
  8304. (defcustom orgstruct-heading-prefix-regexp ""
  8305. "Regexp that matches the custom prefix of Org headlines in
  8306. orgstruct(++)-mode."
  8307. :group 'org
  8308. :version "24.4"
  8309. :package-version '(Org . "8.3")
  8310. :type 'regexp)
  8311. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8312. (defcustom orgstruct-setup-hook nil
  8313. "Hook run after orgstruct-mode-map is filled."
  8314. :group 'org
  8315. :version "24.4"
  8316. :package-version '(Org . "8.0")
  8317. :type 'hook)
  8318. (defvar orgstruct-initialized nil)
  8319. (defvar org-local-vars nil
  8320. "List of local variables, for use by `orgstruct-mode'.")
  8321. ;;;###autoload
  8322. (define-minor-mode orgstruct-mode
  8323. "Toggle the minor mode `orgstruct-mode'.
  8324. This mode is for using Org mode structure commands in other
  8325. modes. The following keys behave as if Org mode were active, if
  8326. the cursor is on a headline, or on a plain list item (both as
  8327. defined by Org-mode)."
  8328. nil " OrgStruct" (make-sparse-keymap)
  8329. (funcall (if orgstruct-mode
  8330. 'add-to-invisibility-spec
  8331. 'remove-from-invisibility-spec)
  8332. '(outline . t))
  8333. (when orgstruct-mode
  8334. (org-load-modules-maybe)
  8335. (unless orgstruct-initialized
  8336. (orgstruct-setup)
  8337. (setq orgstruct-initialized t))))
  8338. ;;;###autoload
  8339. (defun turn-on-orgstruct ()
  8340. "Unconditionally turn on `orgstruct-mode'."
  8341. (orgstruct-mode 1))
  8342. (defvar-local orgstruct-is-++ nil
  8343. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8344. (defvar-local org-fb-vars nil)
  8345. (defun orgstruct++-mode (&optional arg)
  8346. "Toggle `orgstruct-mode', the enhanced version of it.
  8347. In addition to setting orgstruct-mode, this also exports all
  8348. indentation and autofilling variables from Org mode into the
  8349. buffer. It will also recognize item context in multiline items."
  8350. (interactive "P")
  8351. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8352. (if (< arg 1)
  8353. (progn (orgstruct-mode -1)
  8354. (dolist (v org-fb-vars)
  8355. (set (make-local-variable (car v))
  8356. (if (eq (car-safe (cadr v)) 'quote)
  8357. (cl-cadadr v)
  8358. (nth 1 v)))))
  8359. (orgstruct-mode 1)
  8360. (setq org-fb-vars nil)
  8361. (unless org-local-vars
  8362. (setq org-local-vars (org-get-local-variables)))
  8363. (let (var val)
  8364. (dolist (x org-local-vars)
  8365. (when (string-match
  8366. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8367. \\|fill-prefix\\|indent-\\)"
  8368. (symbol-name (car x)))
  8369. (setq var (car x) val (nth 1 x))
  8370. (push (list var `(quote ,(eval var))) org-fb-vars)
  8371. (set (make-local-variable var)
  8372. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8373. (setq-local orgstruct-is-++ t))))
  8374. ;;;###autoload
  8375. (defun turn-on-orgstruct++ ()
  8376. "Unconditionally turn on `orgstruct++-mode'."
  8377. (orgstruct++-mode 1))
  8378. (defun orgstruct-error ()
  8379. "Error when there is no default binding for a structure key."
  8380. (interactive)
  8381. (funcall (if (fboundp 'user-error)
  8382. 'user-error
  8383. 'error)
  8384. "This key has no function outside structure elements"))
  8385. (defun orgstruct-setup ()
  8386. "Setup orgstruct keymap."
  8387. (dolist (cell '((org-demote . t)
  8388. (org-metaleft . t)
  8389. (org-metaright . t)
  8390. (org-promote . t)
  8391. (org-shiftmetaleft . t)
  8392. (org-shiftmetaright . t)
  8393. org-backward-element
  8394. org-backward-heading-same-level
  8395. org-ctrl-c-ret
  8396. org-ctrl-c-minus
  8397. org-ctrl-c-star
  8398. org-cycle
  8399. org-force-cycle-archived
  8400. org-forward-heading-same-level
  8401. org-insert-heading
  8402. org-insert-heading-respect-content
  8403. org-kill-note-or-show-branches
  8404. org-mark-subtree
  8405. org-meta-return
  8406. org-metadown
  8407. org-metaup
  8408. org-narrow-to-subtree
  8409. org-promote-subtree
  8410. org-reveal
  8411. org-shiftdown
  8412. org-shiftleft
  8413. org-shiftmetadown
  8414. org-shiftmetaup
  8415. org-shiftright
  8416. org-shifttab
  8417. org-shifttab
  8418. org-shiftup
  8419. org-show-children
  8420. org-show-subtree
  8421. org-sort
  8422. org-up-element
  8423. outline-demote
  8424. outline-next-visible-heading
  8425. outline-previous-visible-heading
  8426. outline-promote
  8427. outline-up-heading))
  8428. (let ((f (or (car-safe cell) cell))
  8429. (disable-when-heading-prefix (cdr-safe cell)))
  8430. (when (fboundp f)
  8431. (let ((new-bindings))
  8432. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8433. (where-is-internal f outline-mode-map)))
  8434. (push binding new-bindings)
  8435. ;; TODO use local-function-key-map
  8436. (dolist (rep '(("<tab>" . "TAB")
  8437. ("<return>" . "RET")
  8438. ("<escape>" . "ESC")
  8439. ("<delete>" . "DEL")))
  8440. (setq binding (read-kbd-macro
  8441. (let ((case-fold-search))
  8442. (replace-regexp-in-string
  8443. (regexp-quote (cdr rep))
  8444. (car rep)
  8445. (key-description binding)))))
  8446. (cl-pushnew binding new-bindings :test 'equal)))
  8447. (dolist (binding new-bindings)
  8448. (let ((key (lookup-key orgstruct-mode-map binding)))
  8449. (when (or (not key) (numberp key))
  8450. (ignore-errors
  8451. (org-defkey orgstruct-mode-map
  8452. binding
  8453. (orgstruct-make-binding
  8454. f binding disable-when-heading-prefix))))))))))
  8455. (run-hooks 'orgstruct-setup-hook))
  8456. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8457. "Create a function for binding in the structure minor mode.
  8458. FUN is the command to call inside a table. KEY is the key that
  8459. should be checked in for a command to execute outside of tables.
  8460. Non-nil `disable-when-heading-prefix' means to disable the command
  8461. if `orgstruct-heading-prefix-regexp' is not empty."
  8462. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8463. (let ((nname name)
  8464. (i 0))
  8465. (while (fboundp (intern nname))
  8466. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8467. (setq name (intern nname)))
  8468. (eval
  8469. (let ((bindings '((org-heading-regexp
  8470. (concat "^"
  8471. orgstruct-heading-prefix-regexp
  8472. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8473. (org-outline-regexp
  8474. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8475. (org-outline-regexp-bol
  8476. (concat "^" org-outline-regexp))
  8477. (outline-regexp org-outline-regexp)
  8478. (outline-heading-end-regexp "\n")
  8479. (outline-level 'org-outline-level)
  8480. (outline-heading-alist))))
  8481. `(defun ,name (arg)
  8482. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8483. "Outside of structure, run the binding of `"
  8484. (key-description key) "'."
  8485. (when disable-when-heading-prefix
  8486. (concat
  8487. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8488. "back to the default binding due to limitations of Org's implementation of\n"
  8489. "`" (symbol-name fun) "'.")))
  8490. (interactive "p")
  8491. (let* ((disable
  8492. ,(and disable-when-heading-prefix
  8493. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8494. (fallback
  8495. (or disable
  8496. (not
  8497. (let* ,bindings
  8498. (org-context-p 'headline 'item
  8499. ,(when (memq fun
  8500. '(org-insert-heading
  8501. org-insert-heading-respect-content
  8502. org-meta-return))
  8503. '(when orgstruct-is-++
  8504. 'item-body))))))))
  8505. (if fallback
  8506. (let* ((orgstruct-mode)
  8507. (binding
  8508. (let ((key ,key))
  8509. (catch 'exit
  8510. (dolist
  8511. (rep
  8512. '(nil
  8513. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8514. ("<\\([^>]*\\)return>" . "\\1RET")
  8515. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8516. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8517. nil)
  8518. (when rep
  8519. (setq key (read-kbd-macro
  8520. (let ((case-fold-search))
  8521. (replace-regexp-in-string
  8522. (car rep)
  8523. (cdr rep)
  8524. (key-description key))))))
  8525. (when (key-binding key)
  8526. (throw 'exit (key-binding key))))))))
  8527. (if (keymapp binding)
  8528. (org-set-transient-map binding)
  8529. (let ((func (or binding
  8530. (unless disable
  8531. 'orgstruct-error))))
  8532. (when func
  8533. (call-interactively func)))))
  8534. (org-run-like-in-org-mode
  8535. (lambda ()
  8536. (interactive)
  8537. (let* ,bindings
  8538. (call-interactively ',fun)))))))))
  8539. name))
  8540. (defun org-contextualize-keys (alist contexts)
  8541. "Return valid elements in ALIST depending on CONTEXTS.
  8542. `org-agenda-custom-commands' or `org-capture-templates' are the
  8543. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8544. or `org-capture-templates-contexts' are the associated contexts
  8545. definitions."
  8546. (let ((contexts
  8547. ;; normalize contexts
  8548. (mapcar
  8549. (lambda(c) (cond ((listp (cadr c))
  8550. (list (car c) (car c) (nth 1 c)))
  8551. ((string= "" (cadr c))
  8552. (list (car c) (car c) (nth 2 c)))
  8553. (t c)))
  8554. contexts))
  8555. (a alist) r s)
  8556. ;; loop over all commands or templates
  8557. (dolist (c a)
  8558. (let (vrules repl)
  8559. (cond
  8560. ((not (assoc (car c) contexts))
  8561. (push c r))
  8562. ((and (assoc (car c) contexts)
  8563. (setq vrules (org-contextualize-validate-key
  8564. (car c) contexts)))
  8565. (mapc (lambda (vr)
  8566. (unless (equal (car vr) (cadr vr))
  8567. (setq repl vr)))
  8568. vrules)
  8569. (if (not repl) (push c r)
  8570. (push (cadr repl) s)
  8571. (push
  8572. (cons (car c)
  8573. (cdr (or (assoc (cadr repl) alist)
  8574. (error "Undefined key `%s' as contextual replacement for `%s'"
  8575. (cadr repl) (car c)))))
  8576. r))))))
  8577. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8578. (delq
  8579. nil
  8580. (delete-dups
  8581. (mapcar (lambda (x)
  8582. (let ((tpl (car x)))
  8583. (unless (delq
  8584. nil
  8585. (mapcar (lambda (y)
  8586. (equal y tpl))
  8587. s))
  8588. x)))
  8589. (reverse r))))))
  8590. (defun org-contextualize-validate-key (key contexts)
  8591. "Check CONTEXTS for agenda or capture KEY."
  8592. (let (res)
  8593. (dolist (r contexts)
  8594. (dolist (rr (car (last r)))
  8595. (when
  8596. (and (equal key (car r))
  8597. (if (functionp rr) (funcall rr)
  8598. (or (and (eq (car rr) 'in-file)
  8599. (buffer-file-name)
  8600. (string-match (cdr rr) (buffer-file-name)))
  8601. (and (eq (car rr) 'in-mode)
  8602. (string-match (cdr rr) (symbol-name major-mode)))
  8603. (and (eq (car rr) 'in-buffer)
  8604. (string-match (cdr rr) (buffer-name)))
  8605. (when (and (eq (car rr) 'not-in-file)
  8606. (buffer-file-name))
  8607. (not (string-match (cdr rr) (buffer-file-name))))
  8608. (when (eq (car rr) 'not-in-mode)
  8609. (not (string-match (cdr rr) (symbol-name major-mode))))
  8610. (when (eq (car rr) 'not-in-buffer)
  8611. (not (string-match (cdr rr) (buffer-name)))))))
  8612. (push r res))))
  8613. (delete-dups (delq nil res))))
  8614. (defun org-context-p (&rest contexts)
  8615. "Check if local context is any of CONTEXTS.
  8616. Possible values in the list of contexts are `table', `headline', and `item'."
  8617. (let ((pos (point)))
  8618. (goto-char (point-at-bol))
  8619. (prog1 (or (and (memq 'table contexts)
  8620. (looking-at "[ \t]*|"))
  8621. (and (memq 'headline contexts)
  8622. (looking-at org-outline-regexp))
  8623. (and (memq 'item contexts)
  8624. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8625. (and (memq 'item-body contexts)
  8626. (org-in-item-p)))
  8627. (goto-char pos))))
  8628. (defconst org-unique-local-variables
  8629. '(org-element--cache
  8630. org-element--cache-objects
  8631. org-element--cache-sync-keys
  8632. org-element--cache-sync-requests
  8633. org-element--cache-sync-timer)
  8634. "List of local variables that cannot be transferred to another buffer.")
  8635. (defun org-get-local-variables ()
  8636. "Return a list of all local variables in an Org mode buffer."
  8637. (delq nil
  8638. (mapcar
  8639. (lambda (x)
  8640. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8641. (name (car binding)))
  8642. (and (not (get name 'org-state))
  8643. (not (memq name org-unique-local-variables))
  8644. (string-match-p
  8645. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8646. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8647. (symbol-name name))
  8648. binding)))
  8649. (with-temp-buffer
  8650. (org-mode)
  8651. (buffer-local-variables)))))
  8652. (defun org-clone-local-variables (from-buffer &optional regexp)
  8653. "Clone local variables from FROM-BUFFER.
  8654. Optional argument REGEXP selects variables to clone."
  8655. (dolist (pair (buffer-local-variables from-buffer))
  8656. (let ((name (car pair)))
  8657. (when (and (symbolp name)
  8658. (not (memq name org-unique-local-variables))
  8659. (or (null regexp) (string-match regexp (symbol-name name))))
  8660. (set (make-local-variable name) (cdr pair))))))
  8661. ;;;###autoload
  8662. (defun org-run-like-in-org-mode (cmd)
  8663. "Run a command, pretending that the current buffer is in Org-mode.
  8664. This will temporarily bind local variables that are typically bound in
  8665. Org mode to the values they have in Org-mode, and then interactively
  8666. call CMD."
  8667. (org-load-modules-maybe)
  8668. (unless org-local-vars
  8669. (setq org-local-vars (org-get-local-variables)))
  8670. (let (binds)
  8671. (dolist (var org-local-vars)
  8672. (when (or (not (boundp (car var)))
  8673. (eq (symbol-value (car var))
  8674. (default-value (car var))))
  8675. (push (list (car var) `(quote ,(cadr var))) binds)))
  8676. (eval `(let ,binds
  8677. (call-interactively (quote ,cmd))))))
  8678. (defun org-get-category (&optional pos force-refresh)
  8679. "Get the category applying to position POS."
  8680. (save-match-data
  8681. (when force-refresh (org-refresh-category-properties))
  8682. (let ((pos (or pos (point))))
  8683. (or (get-text-property pos 'org-category)
  8684. (progn (org-refresh-category-properties)
  8685. (get-text-property pos 'org-category))))))
  8686. ;;; Refresh properties
  8687. (defun org-refresh-properties (dprop tprop)
  8688. "Refresh buffer text properties.
  8689. DPROP is the drawer property and TPROP is either the
  8690. corresponding text property to set, or an alist with each element
  8691. being a text property (as a symbol) and a function to apply to
  8692. the value of the drawer property."
  8693. (let ((case-fold-search t)
  8694. (inhibit-read-only t))
  8695. (org-with-silent-modifications
  8696. (save-excursion
  8697. (save-restriction
  8698. (widen)
  8699. (goto-char (point-min))
  8700. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8701. (org-refresh-property tprop (match-string-no-properties 1))))))))
  8702. (defun org-refresh-property (tprop p)
  8703. "Refresh the buffer text property TPROP from the drawer property P.
  8704. The refresh happens only for the current tree (not subtree)."
  8705. (unless (org-before-first-heading-p)
  8706. (save-excursion
  8707. (org-back-to-heading t)
  8708. (if (symbolp tprop)
  8709. ;; TPROP is a text property symbol
  8710. (put-text-property
  8711. (point) (or (outline-next-heading) (point-max)) tprop p)
  8712. ;; TPROP is an alist with (properties . function) elements
  8713. (dolist (al tprop)
  8714. (save-excursion
  8715. (put-text-property
  8716. (line-beginning-position) (or (outline-next-heading) (point-max))
  8717. (car al)
  8718. (funcall (cdr al) p))))))))
  8719. (defun org-refresh-category-properties ()
  8720. "Refresh category text properties in the buffer."
  8721. (let ((case-fold-search t)
  8722. (inhibit-read-only t)
  8723. (default-category
  8724. (cond ((null org-category)
  8725. (if buffer-file-name
  8726. (file-name-sans-extension
  8727. (file-name-nondirectory buffer-file-name))
  8728. "???"))
  8729. ((symbolp org-category) (symbol-name org-category))
  8730. (t org-category))))
  8731. (org-with-silent-modifications
  8732. (org-with-wide-buffer
  8733. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8734. ;; This is the default category for the buffer. If none is
  8735. ;; found, fall-back to `org-category' or buffer file name.
  8736. (put-text-property
  8737. (point-min) (point-max)
  8738. 'org-category
  8739. (catch 'buffer-category
  8740. (goto-char (point-max))
  8741. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8742. (let ((element (org-element-at-point)))
  8743. (when (eq (org-element-type element) 'keyword)
  8744. (throw 'buffer-category
  8745. (org-element-property :value element)))))
  8746. default-category))
  8747. ;; Set sub-tree specific categories.
  8748. (goto-char (point-min))
  8749. (let ((regexp (org-re-property "CATEGORY")))
  8750. (while (re-search-forward regexp nil t)
  8751. (let ((value (match-string-no-properties 3)))
  8752. (when (org-at-property-p)
  8753. (put-text-property
  8754. (save-excursion (org-back-to-heading t) (point))
  8755. (save-excursion (org-end-of-subtree t t) (point))
  8756. 'org-category
  8757. value)))))))))
  8758. (defun org-refresh-stats-properties ()
  8759. "Refresh stats text properties in the buffer."
  8760. (let (stats)
  8761. (org-with-silent-modifications
  8762. (save-excursion
  8763. (save-restriction
  8764. (widen)
  8765. (goto-char (point-min))
  8766. (while (re-search-forward
  8767. (concat org-outline-regexp-bol ".*"
  8768. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8769. nil t)
  8770. (setq stats (cond ((equal (match-string 3) "0") 0)
  8771. ((match-string 2)
  8772. (/ (* (string-to-number (match-string 2)) 100)
  8773. (string-to-number (match-string 3))))
  8774. (t (string-to-number (match-string 1)))))
  8775. (org-back-to-heading t)
  8776. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8777. 'org-stats stats)))))))
  8778. (defun org-refresh-effort-properties ()
  8779. "Refresh effort properties"
  8780. (org-refresh-properties
  8781. org-effort-property
  8782. '((effort . identity)
  8783. (effort-minutes . org-duration-string-to-minutes))))
  8784. ;;;; Link Stuff
  8785. ;;; Link abbreviations
  8786. (defun org-link-expand-abbrev (link)
  8787. "Apply replacements as defined in `org-link-abbrev-alist'."
  8788. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8789. (let* ((key (match-string 1 link))
  8790. (as (or (assoc key org-link-abbrev-alist-local)
  8791. (assoc key org-link-abbrev-alist)))
  8792. (tag (and (match-end 2) (match-string 3 link)))
  8793. rpl)
  8794. (if (not as)
  8795. link
  8796. (setq rpl (cdr as))
  8797. (cond
  8798. ((symbolp rpl) (funcall rpl tag))
  8799. ((string-match "%(\\([^)]+\\))" rpl)
  8800. (replace-match
  8801. (save-match-data
  8802. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8803. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8804. ((string-match "%h" rpl)
  8805. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8806. (t (concat rpl tag)))))
  8807. link))
  8808. ;;; Storing and inserting links
  8809. (defvar org-insert-link-history nil
  8810. "Minibuffer history for links inserted with `org-insert-link'.")
  8811. (defvar org-stored-links nil
  8812. "Contains the links stored with `org-store-link'.")
  8813. (defvar org-store-link-plist nil
  8814. "Plist with info about the most recently link created with `org-store-link'.")
  8815. (defun org-store-link-functions ()
  8816. "Return a list of functions that are called to create and store a link.
  8817. The functions defined in the :store property of
  8818. `org-link-parameters'.
  8819. Each function will be called in turn until one returns a non-nil
  8820. value. Each function should check if it is responsible for
  8821. creating this link (for example by looking at the major mode).
  8822. If not, it must exit and return nil. If yes, it should return
  8823. a non-nil value after calling `org-store-link-props' with a list
  8824. of properties and values. Special properties are:
  8825. :type The link prefix, like \"http\". This must be given.
  8826. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8827. This is obligatory as well.
  8828. :description Optional default description for the second pair
  8829. of brackets in an Org mode link. The user can still change
  8830. this when inserting this link into an Org mode buffer.
  8831. In addition to these, any additional properties can be specified
  8832. and then used in capture templates."
  8833. (cl-loop for link in org-link-parameters
  8834. with store-func
  8835. do (setq store-func (org-link-get-parameter (car link) :store))
  8836. if store-func
  8837. collect store-func))
  8838. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8839. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8840. ;;;###autoload
  8841. (defun org-store-link (arg)
  8842. "\\<org-mode-map>Store an org-link to the current location.
  8843. This link is added to `org-stored-links' and can later be inserted
  8844. into an Org buffer with \\[org-insert-link].
  8845. For some link types, a prefix ARG is interpreted.
  8846. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8847. For file links, ARG negates `org-context-in-file-links'.
  8848. A double prefix ARG force skipping storing functions that are not
  8849. part of Org's core.
  8850. A triple prefix ARG force storing a link for each line in the
  8851. active region."
  8852. (interactive "P")
  8853. (org-load-modules-maybe)
  8854. (if (and (equal arg '(64)) (org-region-active-p))
  8855. (save-excursion
  8856. (let ((end (region-end)))
  8857. (goto-char (region-beginning))
  8858. (set-mark (point))
  8859. (while (< (point-at-eol) end)
  8860. (move-end-of-line 1) (activate-mark)
  8861. (let (current-prefix-arg)
  8862. (call-interactively 'org-store-link))
  8863. (move-beginning-of-line 2)
  8864. (set-mark (point)))))
  8865. (setq org-store-link-plist nil)
  8866. (let (link cpltxt desc description search
  8867. txt custom-id agenda-link sfuns sfunsn)
  8868. (cond
  8869. ;; Store a link using an external link type
  8870. ((and (not (equal arg '(16)))
  8871. (setq sfuns
  8872. (delq
  8873. nil (mapcar (lambda (f)
  8874. (let (fs) (if (funcall f) (push f fs))))
  8875. (org-store-link-functions)))
  8876. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8877. (or (and (cdr sfuns)
  8878. (funcall (intern
  8879. (completing-read
  8880. "Which function for creating the link? "
  8881. sfunsn nil t (car sfunsn)))))
  8882. (funcall (caar sfuns)))
  8883. (setq link (plist-get org-store-link-plist :link)
  8884. desc (or (plist-get org-store-link-plist
  8885. :description)
  8886. link))))
  8887. ;; Store a link from a source code buffer.
  8888. ((org-src-edit-buffer-p)
  8889. (let ((coderef-format (org-src-coderef-format)))
  8890. (cond ((save-excursion
  8891. (beginning-of-line)
  8892. (looking-at (org-src-coderef-regexp coderef-format)))
  8893. (setq link (format "(%s)" (match-string-no-properties 3))))
  8894. ((called-interactively-p 'any)
  8895. (let ((label (read-string "Code line label: ")))
  8896. (end-of-line)
  8897. (setq link (format coderef-format label))
  8898. (let ((gc (- 79 (length link))))
  8899. (if (< (current-column) gc)
  8900. (org-move-to-column gc t)
  8901. (insert " ")))
  8902. (insert link)
  8903. (setq link (concat "(" label ")"))
  8904. (setq desc nil)))
  8905. (t (setq link nil)))))
  8906. ;; We are in the agenda, link to referenced location
  8907. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8908. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8909. (get-text-property (point) 'org-marker))))
  8910. (when m
  8911. (org-with-point-at m
  8912. (setq agenda-link
  8913. (if (called-interactively-p 'any)
  8914. (call-interactively 'org-store-link)
  8915. (org-store-link nil)))))))
  8916. ((eq major-mode 'calendar-mode)
  8917. (let ((cd (calendar-cursor-to-date)))
  8918. (setq link
  8919. (format-time-string
  8920. (car org-time-stamp-formats)
  8921. (apply 'encode-time
  8922. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8923. nil nil nil))))
  8924. (org-store-link-props :type "calendar" :date cd)))
  8925. ((eq major-mode 'help-mode)
  8926. (setq link (concat "help:" (save-excursion
  8927. (goto-char (point-min))
  8928. (looking-at "^[^ ]+")
  8929. (match-string 0))))
  8930. (org-store-link-props :type "help"))
  8931. ((eq major-mode 'w3-mode)
  8932. (setq cpltxt (if (and (buffer-name)
  8933. (not (string-match "Untitled" (buffer-name))))
  8934. (buffer-name)
  8935. (url-view-url t))
  8936. link (url-view-url t))
  8937. (org-store-link-props :type "w3" :url (url-view-url t)))
  8938. ((eq major-mode 'image-mode)
  8939. (setq cpltxt (concat "file:"
  8940. (abbreviate-file-name buffer-file-name))
  8941. link cpltxt)
  8942. (org-store-link-props :type "image" :file buffer-file-name))
  8943. ;; In dired, store a link to the file of the current line
  8944. ((derived-mode-p 'dired-mode)
  8945. (let ((file (dired-get-filename nil t)))
  8946. (setq file (if file
  8947. (abbreviate-file-name
  8948. (expand-file-name (dired-get-filename nil t)))
  8949. ;; otherwise, no file so use current directory.
  8950. default-directory))
  8951. (setq cpltxt (concat "file:" file)
  8952. link cpltxt)))
  8953. ((setq search (run-hook-with-args-until-success
  8954. 'org-create-file-search-functions))
  8955. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8956. "::" search))
  8957. (setq cpltxt (or description link)))
  8958. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8959. (org-with-limited-levels
  8960. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8961. (cond
  8962. ;; Store a link using the target at point
  8963. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8964. (setq cpltxt
  8965. (concat "file:"
  8966. (abbreviate-file-name
  8967. (buffer-file-name (buffer-base-buffer)))
  8968. "::" (match-string 1))
  8969. link cpltxt))
  8970. ((and (featurep 'org-id)
  8971. (or (eq org-id-link-to-org-use-id t)
  8972. (and (called-interactively-p 'any)
  8973. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8974. (and (eq org-id-link-to-org-use-id
  8975. 'create-if-interactive-and-no-custom-id)
  8976. (not custom-id))))
  8977. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8978. ;; Store a link using the ID at point
  8979. (setq link (condition-case nil
  8980. (prog1 (org-id-store-link)
  8981. (setq desc (or (plist-get org-store-link-plist
  8982. :description)
  8983. "")))
  8984. (error
  8985. ;; Probably before first headline, link only to file
  8986. (concat "file:"
  8987. (abbreviate-file-name
  8988. (buffer-file-name (buffer-base-buffer))))))))
  8989. (t
  8990. ;; Just link to current headline
  8991. (setq cpltxt (concat "file:"
  8992. (abbreviate-file-name
  8993. (buffer-file-name (buffer-base-buffer)))))
  8994. ;; Add a context search string
  8995. (when (org-xor org-context-in-file-links arg)
  8996. (let* ((element (org-element-at-point))
  8997. (name (org-element-property :name element)))
  8998. (setq txt (cond
  8999. ((org-at-heading-p) nil)
  9000. (name)
  9001. ((org-region-active-p)
  9002. (buffer-substring (region-beginning) (region-end)))))
  9003. (when (or (null txt) (string-match "\\S-" txt))
  9004. (setq cpltxt
  9005. (concat cpltxt "::"
  9006. (condition-case nil
  9007. (org-make-org-heading-search-string txt)
  9008. (error "")))
  9009. desc (or name
  9010. (nth 4 (ignore-errors (org-heading-components)))
  9011. "NONE")))))
  9012. (when (string-match "::\\'" cpltxt)
  9013. (setq cpltxt (substring cpltxt 0 -2)))
  9014. (setq link cpltxt)))))
  9015. ((buffer-file-name (buffer-base-buffer))
  9016. ;; Just link to this file here.
  9017. (setq cpltxt (concat "file:"
  9018. (abbreviate-file-name
  9019. (buffer-file-name (buffer-base-buffer)))))
  9020. ;; Add a context string.
  9021. (when (org-xor org-context-in-file-links arg)
  9022. (setq txt (if (org-region-active-p)
  9023. (buffer-substring (region-beginning) (region-end))
  9024. (buffer-substring (point-at-bol) (point-at-eol))))
  9025. ;; Only use search option if there is some text.
  9026. (when (string-match "\\S-" txt)
  9027. (setq cpltxt
  9028. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  9029. desc "NONE")))
  9030. (setq link cpltxt))
  9031. ((called-interactively-p 'interactive)
  9032. (user-error "No method for storing a link from this buffer"))
  9033. (t (setq link nil)))
  9034. ;; We're done setting link and desc, clean up
  9035. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9036. (setq link (or link cpltxt)
  9037. desc (or desc cpltxt))
  9038. (cond ((not desc))
  9039. ((equal desc "NONE") (setq desc nil))
  9040. (t (setq desc
  9041. (replace-regexp-in-string
  9042. org-bracket-link-analytic-regexp
  9043. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9044. desc))))
  9045. ;; Return the link
  9046. (if (not (and (or (called-interactively-p 'any)
  9047. executing-kbd-macro)
  9048. link))
  9049. (or agenda-link (and link (org-make-link-string link desc)))
  9050. (push (list link desc) org-stored-links)
  9051. (message "Stored: %s" (or desc link))
  9052. (when custom-id
  9053. (setq link (concat "file:" (abbreviate-file-name
  9054. (buffer-file-name)) "::#" custom-id))
  9055. (push (list link desc) org-stored-links))
  9056. (car org-stored-links)))))
  9057. (defun org-store-link-props (&rest plist)
  9058. "Store link properties, extract names, addresses and dates."
  9059. (let ((x (plist-get plist :from)))
  9060. (when x
  9061. (let ((adr (mail-extract-address-components x)))
  9062. (setq plist (plist-put plist :fromname (car adr)))
  9063. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9064. (let ((x (plist-get plist :to)))
  9065. (when x
  9066. (let ((adr (mail-extract-address-components x)))
  9067. (setq plist (plist-put plist :toname (car adr)))
  9068. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9069. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9070. (when x
  9071. (setq plist (plist-put plist :date-timestamp
  9072. (format-time-string
  9073. (org-time-stamp-format t) x)))
  9074. (setq plist (plist-put plist :date-timestamp-inactive
  9075. (format-time-string
  9076. (org-time-stamp-format t t) x)))))
  9077. (let ((from (plist-get plist :from))
  9078. (to (plist-get plist :to)))
  9079. (when (and from to org-from-is-user-regexp)
  9080. (setq plist
  9081. (plist-put plist :fromto
  9082. (if (string-match org-from-is-user-regexp from)
  9083. (concat "to %t")
  9084. (concat "from %f"))))))
  9085. (setq org-store-link-plist plist))
  9086. (defun org-add-link-props (&rest plist)
  9087. "Add these properties to the link property list."
  9088. (let (key value)
  9089. (while plist
  9090. (setq key (pop plist) value (pop plist))
  9091. (setq org-store-link-plist
  9092. (plist-put org-store-link-plist key value)))))
  9093. (defun org-email-link-description (&optional fmt)
  9094. "Return the description part of an email link.
  9095. This takes information from `org-store-link-plist' and formats it
  9096. according to FMT (default from `org-email-link-description-format')."
  9097. (setq fmt (or fmt org-email-link-description-format))
  9098. (let* ((p org-store-link-plist)
  9099. (to (plist-get p :toaddress))
  9100. (from (plist-get p :fromaddress))
  9101. (table
  9102. (list
  9103. (cons "%c" (plist-get p :fromto))
  9104. (cons "%F" (plist-get p :from))
  9105. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9106. (cons "%T" (plist-get p :to))
  9107. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9108. (cons "%s" (plist-get p :subject))
  9109. (cons "%d" (plist-get p :date))
  9110. (cons "%m" (plist-get p :message-id)))))
  9111. (when (string-match "%c" fmt)
  9112. ;; Check if the user wrote this message
  9113. (if (and org-from-is-user-regexp from to
  9114. (save-match-data (string-match org-from-is-user-regexp from)))
  9115. (setq fmt (replace-match "to %t" t t fmt))
  9116. (setq fmt (replace-match "from %f" t t fmt))))
  9117. (org-replace-escapes fmt table)))
  9118. (defun org-make-org-heading-search-string (&optional string)
  9119. "Make search string for the current headline or STRING."
  9120. (let ((s (or string
  9121. (and (derived-mode-p 'org-mode)
  9122. (save-excursion
  9123. (org-back-to-heading t)
  9124. (org-element-property :raw-value (org-element-at-point))))))
  9125. (lines org-context-in-file-links))
  9126. (or string (setq s (concat "*" s))) ; Add * for headlines
  9127. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9128. (when (and string (integerp lines) (> lines 0))
  9129. (let ((slines (org-split-string s "\n")))
  9130. (when (< lines (length slines))
  9131. (setq s (mapconcat
  9132. 'identity
  9133. (reverse (nthcdr (- (length slines) lines)
  9134. (reverse slines))) "\n")))))
  9135. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9136. (defun org-make-link-string (link &optional description)
  9137. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9138. (unless (org-string-nw-p link) (error "Empty link"))
  9139. (let ((uri (cond ((string-match org-link-types-re link)
  9140. (concat (match-string 1 link)
  9141. (org-link-escape (substring link (match-end 1)))))
  9142. ;; For readability, url-encode internal links only
  9143. ;; when absolutely needed (i.e, when they contain
  9144. ;; square brackets). File links however, are
  9145. ;; encoded since, e.g., spaces are significant.
  9146. ((or (file-name-absolute-p link)
  9147. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9148. (org-link-escape link))
  9149. (t link)))
  9150. (description
  9151. (and (org-string-nw-p description)
  9152. ;; Remove brackets from description, as they are fatal.
  9153. (replace-regexp-in-string
  9154. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9155. (org-trim description)))))
  9156. (format "[[%s]%s]"
  9157. uri
  9158. (if description (format "[%s]" description) ""))))
  9159. (defconst org-link-escape-chars
  9160. ;;%20 %5B %5D %25
  9161. '(?\s ?\[ ?\] ?%)
  9162. "List of characters that should be escaped in a link when stored to Org.
  9163. This is the list that is used for internal purposes.")
  9164. (defun org-link-escape (text &optional table merge)
  9165. "Return percent escaped representation of TEXT.
  9166. TEXT is a string with the text to escape.
  9167. Optional argument TABLE is a list with characters that should be
  9168. escaped. When nil, `org-link-escape-chars' is used.
  9169. If optional argument MERGE is set, merge TABLE into
  9170. `org-link-escape-chars'."
  9171. (let ((characters-to-encode
  9172. (cond ((null table) org-link-escape-chars)
  9173. (merge (append org-link-escape-chars table))
  9174. (t table))))
  9175. (mapconcat
  9176. (lambda (c)
  9177. (if (or (memq c characters-to-encode)
  9178. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9179. (mapconcat (lambda (e) (format "%%%.2X" e))
  9180. (or (encode-coding-char c 'utf-8)
  9181. (error "Unable to percent escape character: %c" c))
  9182. "")
  9183. (char-to-string c)))
  9184. text "")))
  9185. (defun org-link-unescape (str)
  9186. "Unhex hexified Unicode parts in string STR.
  9187. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9188. reciprocal of `org-link-escape', which see."
  9189. (if (org-string-nw-p str)
  9190. (replace-regexp-in-string
  9191. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9192. str))
  9193. (defun org-link-unescape-compound (hex)
  9194. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9195. Note: this function also decodes single byte encodings like
  9196. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9197. (save-match-data
  9198. (let* ((bytes (cdr (split-string hex "%")))
  9199. (ret "")
  9200. (eat 0)
  9201. (sum 0))
  9202. (while bytes
  9203. (let* ((val (string-to-number (pop bytes) 16))
  9204. (shift-xor
  9205. (if (= 0 eat)
  9206. (cond
  9207. ((>= val 252) (cons 6 252))
  9208. ((>= val 248) (cons 5 248))
  9209. ((>= val 240) (cons 4 240))
  9210. ((>= val 224) (cons 3 224))
  9211. ((>= val 192) (cons 2 192))
  9212. (t (cons 0 0)))
  9213. (cons 6 128))))
  9214. (when (>= val 192) (setq eat (car shift-xor)))
  9215. (setq val (logxor val (cdr shift-xor)))
  9216. (setq sum (+ (lsh sum (car shift-xor)) val))
  9217. (when (> eat 0) (setq eat (- eat 1)))
  9218. (cond
  9219. ((= 0 eat) ;multi byte
  9220. (setq ret (concat ret (char-to-string sum)))
  9221. (setq sum 0))
  9222. ((not bytes) ; single byte(s)
  9223. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9224. ret)))
  9225. (defun org-link-unescape-single-byte-sequence (hex)
  9226. "Unhexify hex-encoded single byte character sequences."
  9227. (mapconcat (lambda (byte)
  9228. (char-to-string (string-to-number byte 16)))
  9229. (cdr (split-string hex "%")) ""))
  9230. (defun org-xor (a b)
  9231. "Exclusive or."
  9232. (if a (not b) b))
  9233. (defun org-fixup-message-id-for-http (s)
  9234. "Replace special characters in a message id, so it can be used in an http query."
  9235. (when (string-match "%" s)
  9236. (setq s (mapconcat (lambda (c)
  9237. (if (eq c ?%)
  9238. "%25"
  9239. (char-to-string c)))
  9240. s "")))
  9241. (while (string-match "<" s)
  9242. (setq s (replace-match "%3C" t t s)))
  9243. (while (string-match ">" s)
  9244. (setq s (replace-match "%3E" t t s)))
  9245. (while (string-match "@" s)
  9246. (setq s (replace-match "%40" t t s)))
  9247. s)
  9248. (defun org-link-prettify (link)
  9249. "Return a human-readable representation of LINK.
  9250. The car of LINK must be a raw link.
  9251. The cdr of LINK must be either a link description or nil."
  9252. (let ((desc (or (cadr link) "<no description>")))
  9253. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9254. "<" (car link) ">")))
  9255. ;;;###autoload
  9256. (defun org-insert-link-global ()
  9257. "Insert a link like Org mode does.
  9258. This command can be called in any mode to insert a link in Org syntax."
  9259. (interactive)
  9260. (org-load-modules-maybe)
  9261. (org-run-like-in-org-mode 'org-insert-link))
  9262. (defun org-insert-all-links (arg &optional pre post)
  9263. "Insert all links in `org-stored-links'.
  9264. When a universal prefix, do not delete the links from `org-stored-links'.
  9265. When `ARG' is a number, insert the last N link(s).
  9266. `PRE' and `POST' are optional arguments to define a string to
  9267. prepend or to append."
  9268. (interactive "P")
  9269. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9270. (links (copy-sequence org-stored-links))
  9271. (pr (or pre "- "))
  9272. (po (or post "\n"))
  9273. (cnt 1) l)
  9274. (if (null org-stored-links)
  9275. (message "No link to insert")
  9276. (while (and (or (listp arg) (>= arg cnt))
  9277. (setq l (if (listp arg)
  9278. (pop links)
  9279. (pop org-stored-links))))
  9280. (setq cnt (1+ cnt))
  9281. (insert pr)
  9282. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9283. (insert po)))))
  9284. (defun org-insert-last-stored-link (arg)
  9285. "Insert the last link stored in `org-stored-links'."
  9286. (interactive "p")
  9287. (org-insert-all-links arg "" "\n"))
  9288. (defun org-link-fontify-links-to-this-file ()
  9289. "Fontify links to the current file in `org-stored-links'."
  9290. (let ((f (buffer-file-name)) a b)
  9291. (setq a (mapcar (lambda(l)
  9292. (let ((ll (car l)))
  9293. (when (and (string-match "^file:\\(.+\\)::" ll)
  9294. (equal f (expand-file-name (match-string 1 ll))))
  9295. ll)))
  9296. org-stored-links))
  9297. (when (featurep 'org-id)
  9298. (setq b (mapcar (lambda(l)
  9299. (let ((ll (car l)))
  9300. (when (and (string-match "^id:\\(.+\\)$" ll)
  9301. (equal f (expand-file-name
  9302. (or (org-id-find-id-file
  9303. (match-string 1 ll)) ""))))
  9304. ll)))
  9305. org-stored-links)))
  9306. (mapcar (lambda(l)
  9307. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9308. (delq nil (append a b)))))
  9309. (defvar org--links-history nil)
  9310. (defun org-insert-link (&optional complete-file link-location default-description)
  9311. "Insert a link. At the prompt, enter the link.
  9312. Completion can be used to insert any of the link protocol prefixes like
  9313. http or ftp in use.
  9314. The history can be used to select a link previously stored with
  9315. `org-store-link'. When the empty string is entered (i.e. if you just
  9316. press RET at the prompt), the link defaults to the most recently
  9317. stored link. As SPC triggers completion in the minibuffer, you need to
  9318. use M-SPC or C-q SPC to force the insertion of a space character.
  9319. You will also be prompted for a description, and if one is given, it will
  9320. be displayed in the buffer instead of the link.
  9321. If there is already a link at point, this command will allow you to edit link
  9322. and description parts.
  9323. With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
  9324. be selected using completion. The path to the file will be relative to the
  9325. current directory if the file is in the current directory or a subdirectory.
  9326. Otherwise, the link will be the absolute path as completed in the minibuffer
  9327. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9328. option `org-link-file-path-type'.
  9329. With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
  9330. the current directory or below.
  9331. With three \\[universal-argument] prefixes, negate the meaning of
  9332. `org-keep-stored-link-after-insertion'.
  9333. If `org-make-link-description-function' is non-nil, this function will be
  9334. called with the link target, and the result will be the default
  9335. link description.
  9336. If the LINK-LOCATION parameter is non-nil, this value will be
  9337. used as the link location instead of reading one interactively.
  9338. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
  9339. be used as the default description."
  9340. (interactive "P")
  9341. (let* ((wcf (current-window-configuration))
  9342. (origbuf (current-buffer))
  9343. (region (when (org-region-active-p)
  9344. (buffer-substring (region-beginning) (region-end))))
  9345. (remove (and region (list (region-beginning) (region-end))))
  9346. (desc region)
  9347. (link link-location)
  9348. (abbrevs org-link-abbrev-alist-local)
  9349. entry all-prefixes auto-desc)
  9350. (cond
  9351. (link-location) ; specified by arg, just use it.
  9352. ((org-in-regexp org-bracket-link-regexp 1)
  9353. ;; We do have a link at point, and we are going to edit it.
  9354. (setq remove (list (match-beginning 0) (match-end 0)))
  9355. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9356. (setq link (read-string "Link: "
  9357. (org-link-unescape
  9358. (match-string-no-properties 1)))))
  9359. ((or (org-in-regexp org-angle-link-re)
  9360. (org-in-regexp org-plain-link-re))
  9361. ;; Convert to bracket link
  9362. (setq remove (list (match-beginning 0) (match-end 0))
  9363. link (read-string "Link: "
  9364. (org-remove-angle-brackets (match-string 0)))))
  9365. ((member complete-file '((4) (16)))
  9366. ;; Completing read for file names.
  9367. (setq link (org-file-complete-link complete-file)))
  9368. (t
  9369. ;; Read link, with completion for stored links.
  9370. (org-link-fontify-links-to-this-file)
  9371. (org-switch-to-buffer-other-window "*Org Links*")
  9372. (with-current-buffer "*Org Links*"
  9373. (erase-buffer)
  9374. (insert "Insert a link.
  9375. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9376. (when org-stored-links
  9377. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9378. (insert (mapconcat 'org-link-prettify
  9379. (reverse org-stored-links) "\n")))
  9380. (goto-char (point-min)))
  9381. (let ((cw (selected-window)))
  9382. (select-window (get-buffer-window "*Org Links*" 'visible))
  9383. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9384. (unless (pos-visible-in-window-p (point-max))
  9385. (org-fit-window-to-buffer))
  9386. (and (window-live-p cw) (select-window cw)))
  9387. (setq all-prefixes (append (mapcar 'car abbrevs)
  9388. (mapcar 'car org-link-abbrev-alist)
  9389. (org-link-types)))
  9390. (unwind-protect
  9391. ;; Fake a link history, containing the stored links.
  9392. (let ((org--links-history
  9393. (append (mapcar #'car org-stored-links)
  9394. org-insert-link-history)))
  9395. (setq link
  9396. (org-completing-read
  9397. "Link: "
  9398. (append
  9399. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9400. (mapcar #'car org-stored-links))
  9401. nil nil nil
  9402. 'org--links-history
  9403. (caar org-stored-links)))
  9404. (unless (org-string-nw-p link) (user-error "No link selected"))
  9405. (dolist (l org-stored-links)
  9406. (when (equal link (cadr l))
  9407. (setq link (car l))
  9408. (setq auto-desc t)))
  9409. (when (or (member link all-prefixes)
  9410. (and (equal ":" (substring link -1))
  9411. (member (substring link 0 -1) all-prefixes)
  9412. (setq link (substring link 0 -1))))
  9413. (setq link (with-current-buffer origbuf
  9414. (org-link-try-special-completion link)))))
  9415. (set-window-configuration wcf)
  9416. (kill-buffer "*Org Links*"))
  9417. (setq entry (assoc link org-stored-links))
  9418. (or entry (push link org-insert-link-history))
  9419. (setq desc (or desc (nth 1 entry)))))
  9420. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9421. (not org-keep-stored-link-after-insertion))
  9422. (setq org-stored-links (delq (assoc link org-stored-links)
  9423. org-stored-links)))
  9424. (when (and (string-match org-plain-link-re link)
  9425. (not (string-match org-ts-regexp link)))
  9426. ;; URL-like link, normalize the use of angular brackets.
  9427. (setq link (org-remove-angle-brackets link)))
  9428. ;; Check if we are linking to the current file with a search
  9429. ;; option If yes, simplify the link by using only the search
  9430. ;; option.
  9431. (when (and buffer-file-name
  9432. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9433. (let* ((path (match-string 1 link))
  9434. (case-fold-search nil)
  9435. (search (match-string 2 link)))
  9436. (save-match-data
  9437. (when (equal (file-truename buffer-file-name) (file-truename path))
  9438. ;; We are linking to this same file, with a search option
  9439. (setq link search)))))
  9440. ;; Check if we can/should use a relative path. If yes, simplify the link
  9441. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9442. (let* ((type (match-string 1 link))
  9443. (path (match-string 2 link))
  9444. (origpath path)
  9445. (case-fold-search nil))
  9446. (cond
  9447. ((or (eq org-link-file-path-type 'absolute)
  9448. (equal complete-file '(16)))
  9449. (setq path (abbreviate-file-name (expand-file-name path))))
  9450. ((eq org-link-file-path-type 'noabbrev)
  9451. (setq path (expand-file-name path)))
  9452. ((eq org-link-file-path-type 'relative)
  9453. (setq path (file-relative-name path)))
  9454. (t
  9455. (save-match-data
  9456. (if (string-match (concat "^" (regexp-quote
  9457. (expand-file-name
  9458. (file-name-as-directory
  9459. default-directory))))
  9460. (expand-file-name path))
  9461. ;; We are linking a file with relative path name.
  9462. (setq path (substring (expand-file-name path)
  9463. (match-end 0)))
  9464. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9465. (setq link (concat type path))
  9466. (when (equal desc origpath)
  9467. (setq desc path))))
  9468. (if org-make-link-description-function
  9469. (setq desc
  9470. (or (condition-case nil
  9471. (funcall org-make-link-description-function link desc)
  9472. (error (progn (message "Can't get link description from `%s'"
  9473. (symbol-name org-make-link-description-function))
  9474. (sit-for 2) nil)))
  9475. (read-string "Description: " default-description)))
  9476. (if default-description (setq desc default-description)
  9477. (setq desc (or (and auto-desc desc)
  9478. (read-string "Description: " desc)))))
  9479. (unless (string-match "\\S-" desc) (setq desc nil))
  9480. (when remove (apply 'delete-region remove))
  9481. (insert (org-make-link-string link desc))
  9482. ;; Redisplay so as the new link has proper invisible characters.
  9483. (sit-for 0)))
  9484. (defun org-link-try-special-completion (type)
  9485. "If there is completion support for link type TYPE, offer it."
  9486. (let ((fun (org-link-get-parameter type :complete)))
  9487. (if (functionp fun)
  9488. (funcall fun)
  9489. (read-string "Link (no completion support): " (concat type ":")))))
  9490. (defun org-file-complete-link (&optional arg)
  9491. "Create a file link using completion."
  9492. (let ((file (read-file-name "File: "))
  9493. (pwd (file-name-as-directory (expand-file-name ".")))
  9494. (pwd1 (file-name-as-directory (abbreviate-file-name
  9495. (expand-file-name ".")))))
  9496. (cond ((equal arg '(16))
  9497. (concat "file:"
  9498. (abbreviate-file-name (expand-file-name file))))
  9499. ((string-match
  9500. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9501. (concat "file:" (match-string 1 file)))
  9502. ((string-match
  9503. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9504. (expand-file-name file))
  9505. (concat "file:"
  9506. (match-string 1 (expand-file-name file))))
  9507. (t (concat "file:" file)))))
  9508. (defun org-completing-read (&rest args)
  9509. "Completing-read with SPACE being a normal character."
  9510. (let ((enable-recursive-minibuffers t)
  9511. (minibuffer-local-completion-map
  9512. (copy-keymap minibuffer-local-completion-map)))
  9513. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9514. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9515. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9516. 'org-time-stamp-inactive)
  9517. (apply #'completing-read args)))
  9518. ;;; Opening/following a link
  9519. (defvar org-link-search-failed nil)
  9520. (defvar org-open-link-functions nil
  9521. "Hook for functions finding a plain text link.
  9522. These functions must take a single argument, the link content.
  9523. They will be called for links that look like [[link text][description]]
  9524. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9525. like a filename (e.g. \"./blue.png\").
  9526. These functions will be called *before* Org attempts to resolve the
  9527. link by doing text searches in the current buffer - so if you want a
  9528. link \"[[target]]\" to still find \"<<target>>\", your function should
  9529. handle this as a special case.
  9530. When the function does handle the link, it must return a non-nil value.
  9531. If it decides that it is not responsible for this link, it must return
  9532. nil to indicate that that Org can continue with other options like
  9533. exact and fuzzy text search.")
  9534. (defun org-next-link (&optional search-backward)
  9535. "Move forward to the next link.
  9536. If the link is in hidden text, expose it."
  9537. (interactive "P")
  9538. (when (and org-link-search-failed (eq this-command last-command))
  9539. (goto-char (point-min))
  9540. (message "Link search wrapped back to beginning of buffer"))
  9541. (setq org-link-search-failed nil)
  9542. (let* ((pos (point))
  9543. (ct (org-context))
  9544. (a (assoc :link ct))
  9545. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9546. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9547. ((looking-at org-any-link-re)
  9548. ;; Don't stay stuck at link without an org-link face
  9549. (forward-char (if search-backward -1 1))))
  9550. (if (funcall srch-fun org-any-link-re nil t)
  9551. (progn
  9552. (goto-char (match-beginning 0))
  9553. (when (outline-invisible-p) (org-show-context)))
  9554. (goto-char pos)
  9555. (setq org-link-search-failed t)
  9556. (message "No further link found"))))
  9557. (defun org-previous-link ()
  9558. "Move backward to the previous link.
  9559. If the link is in hidden text, expose it."
  9560. (interactive)
  9561. (funcall 'org-next-link t))
  9562. (defun org-translate-link (s)
  9563. "Translate a link string if a translation function has been defined."
  9564. (with-temp-buffer
  9565. (insert (org-trim s))
  9566. (org-trim (org-element-interpret-data (org-element-context)))))
  9567. (defun org-translate-link-from-planner (type path)
  9568. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9569. This is still an experimental function, your mileage may vary."
  9570. (cond
  9571. ((member type '("http" "https" "news" "ftp"))
  9572. ;; standard Internet links are the same.
  9573. nil)
  9574. ((and (equal type "irc") (string-match "^//" path))
  9575. ;; Planner has two / at the beginning of an irc link, we have 1.
  9576. ;; We should have zero, actually....
  9577. (setq path (substring path 1)))
  9578. ((and (equal type "lisp") (string-match "^/" path))
  9579. ;; Planner has a slash, we do not.
  9580. (setq type "elisp" path (substring path 1)))
  9581. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9582. ;; A typical message link. Planner has the id after the final slash,
  9583. ;; we separate it with a hash mark
  9584. (setq path (concat (match-string 1 path) "#"
  9585. (org-remove-angle-brackets (match-string 2 path))))))
  9586. (cons type path))
  9587. (defun org-find-file-at-mouse (ev)
  9588. "Open file link or URL at mouse."
  9589. (interactive "e")
  9590. (mouse-set-point ev)
  9591. (org-open-at-point 'in-emacs))
  9592. (defun org-open-at-mouse (ev)
  9593. "Open file link or URL at mouse.
  9594. See the docstring of `org-open-file' for details."
  9595. (interactive "e")
  9596. (mouse-set-point ev)
  9597. (when (eq major-mode 'org-agenda-mode)
  9598. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9599. (org-open-at-point))
  9600. (defvar org-window-config-before-follow-link nil
  9601. "The window configuration before following a link.
  9602. This is saved in case the need arises to restore it.")
  9603. ;;;###autoload
  9604. (defun org-open-at-point-global ()
  9605. "Follow a link or time-stamp like Org mode does.
  9606. This command can be called in any mode to follow an external link
  9607. or a time-stamp that has Org mode syntax. Its behavior is
  9608. undefined when called on internal links (e.g., fuzzy links).
  9609. Raise an error when there is nothing to follow. "
  9610. (interactive)
  9611. (cond ((org-in-regexp org-any-link-re)
  9612. (org-open-link-from-string (match-string-no-properties 0)))
  9613. ((or (org-in-regexp org-ts-regexp-both nil t)
  9614. (org-in-regexp org-tsr-regexp-both nil t))
  9615. (org-follow-timestamp-link))
  9616. (t (user-error "No link found"))))
  9617. ;;;###autoload
  9618. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9619. "Open a link in the string S, as if it was in Org-mode."
  9620. (interactive "sLink: \nP")
  9621. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9622. (with-temp-buffer
  9623. (let ((org-inhibit-startup (not reference-buffer)))
  9624. (org-mode)
  9625. (insert s)
  9626. (goto-char (point-min))
  9627. (when reference-buffer
  9628. (setq org-link-abbrev-alist-local
  9629. (with-current-buffer reference-buffer
  9630. org-link-abbrev-alist-local)))
  9631. (org-open-at-point arg reference-buffer)))))
  9632. (defvar org-open-at-point-functions nil
  9633. "Hook that is run when following a link at point.
  9634. Functions in this hook must return t if they identify and follow
  9635. a link at point. If they don't find anything interesting at point,
  9636. they must return nil.")
  9637. (defvar org-link-search-inhibit-query nil)
  9638. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9639. (defun org--open-doi-link (path)
  9640. "Open a \"doi\" type link.
  9641. PATH is a the path to search for, as a string."
  9642. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9643. (defun org--open-elisp-link (path)
  9644. "Open a \"elisp\" type link.
  9645. PATH is the sexp to evaluate, as a string."
  9646. (let ((cmd path))
  9647. (if (or (and (org-string-nw-p
  9648. org-confirm-elisp-link-not-regexp)
  9649. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9650. (not org-confirm-elisp-link-function)
  9651. (funcall org-confirm-elisp-link-function
  9652. (format "Execute \"%s\" as elisp? "
  9653. (org-add-props cmd nil 'face 'org-warning))))
  9654. (message "%s => %s" cmd
  9655. (if (eq (string-to-char cmd) ?\()
  9656. (eval (read cmd))
  9657. (call-interactively (read cmd))))
  9658. (user-error "Abort"))))
  9659. (defun org--open-help-link (path)
  9660. "Open a \"help\" type link.
  9661. PATH is a symbol name, as a string."
  9662. (pcase (intern path)
  9663. ((and (pred fboundp) variable) (describe-function variable))
  9664. ((and (pred boundp) function) (describe-variable function))
  9665. (name (user-error "Unknown function or variable: %s" name))))
  9666. (defun org--open-shell-link (path)
  9667. "Open a \"shell\" type link.
  9668. PATH is the command to execute, as a string."
  9669. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9670. (cmd path))
  9671. (if (or (and (org-string-nw-p
  9672. org-confirm-shell-link-not-regexp)
  9673. (string-match
  9674. org-confirm-shell-link-not-regexp cmd))
  9675. (not org-confirm-shell-link-function)
  9676. (funcall org-confirm-shell-link-function
  9677. (format "Execute \"%s\" in shell? "
  9678. (org-add-props cmd nil
  9679. 'face 'org-warning))))
  9680. (progn
  9681. (message "Executing %s" cmd)
  9682. (shell-command cmd buf)
  9683. (when (featurep 'midnight)
  9684. (setq clean-buffer-list-kill-buffer-names
  9685. (cons (buffer-name buf)
  9686. clean-buffer-list-kill-buffer-names))))
  9687. (user-error "Abort"))))
  9688. (defun org-open-at-point (&optional arg reference-buffer)
  9689. "Open link, timestamp, footnote or tags at point.
  9690. When point is on a link, follow it. Normally, files will be
  9691. opened by an appropriate application. If the optional prefix
  9692. argument ARG is non-nil, Emacs will visit the file. With
  9693. a double prefix argument, try to open outside of Emacs, in the
  9694. application the system uses for this file type.
  9695. When point is on a timestamp, open the agenda at the day
  9696. specified.
  9697. When point is a footnote definition, move to the first reference
  9698. found. If it is on a reference, move to the associated
  9699. definition.
  9700. When point is on a headline, display a list of every link in the
  9701. entry, so it is possible to pick one, or all, of them. If point
  9702. is on a tag, call `org-tags-view' instead.
  9703. When optional argument REFERENCE-BUFFER is non-nil, it should
  9704. specify a buffer from where the link search should happen. This
  9705. is used internally by `org-open-link-from-string'.
  9706. On top of syntactically correct links, this function will open
  9707. the link at point in comments or comment blocks and the first
  9708. link in a property drawer line."
  9709. (interactive "P")
  9710. ;; On a code block, open block's results.
  9711. (unless (call-interactively 'org-babel-open-src-block-result)
  9712. (org-load-modules-maybe)
  9713. (setq org-window-config-before-follow-link (current-window-configuration))
  9714. (org-remove-occur-highlights nil nil t)
  9715. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9716. (let* ((context
  9717. ;; Only consider supported types, even if they are not
  9718. ;; the closest one.
  9719. (org-element-lineage
  9720. (org-element-context)
  9721. '(clock comment comment-block footnote-definition
  9722. footnote-reference headline inlinetask keyword link
  9723. node-property timestamp)
  9724. t))
  9725. (type (org-element-type context))
  9726. (value (org-element-property :value context)))
  9727. (cond
  9728. ((not context) (user-error "No link found"))
  9729. ;; Exception: open timestamps and links in properties
  9730. ;; drawers, keywords and comments.
  9731. ((memq type '(comment comment-block keyword node-property))
  9732. (call-interactively #'org-open-at-point-global))
  9733. ;; On a headline or an inlinetask, but not on a timestamp,
  9734. ;; a link, a footnote reference or on tags.
  9735. ((and (memq type '(headline inlinetask))
  9736. ;; Not on tags.
  9737. (progn (save-excursion (beginning-of-line)
  9738. (looking-at org-complex-heading-regexp))
  9739. (or (not (match-beginning 5))
  9740. (< (point) (match-beginning 5)))))
  9741. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9742. (links (car data))
  9743. (links-end (cdr data)))
  9744. (if links
  9745. (dolist (link (if (stringp links) (list links) links))
  9746. (search-forward link nil links-end)
  9747. (goto-char (match-beginning 0))
  9748. (org-open-at-point))
  9749. (require 'org-attach)
  9750. (org-attach-reveal 'if-exists))))
  9751. ;; On a clock line, make sure point is on the timestamp
  9752. ;; before opening it.
  9753. ((and (eq type 'clock)
  9754. value
  9755. (>= (point) (org-element-property :begin value))
  9756. (<= (point) (org-element-property :end value)))
  9757. (org-follow-timestamp-link))
  9758. ;; Do nothing on white spaces after an object.
  9759. ((>= (point)
  9760. (save-excursion
  9761. (goto-char (org-element-property :end context))
  9762. (skip-chars-backward " \t")
  9763. (point)))
  9764. (user-error "No link found"))
  9765. ((eq type 'timestamp) (org-follow-timestamp-link))
  9766. ;; On tags within a headline or an inlinetask.
  9767. ((and (memq type '(headline inlinetask))
  9768. (progn (save-excursion (beginning-of-line)
  9769. (looking-at org-complex-heading-regexp))
  9770. (and (match-beginning 5)
  9771. (>= (point) (match-beginning 5)))))
  9772. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9773. ((eq type 'link)
  9774. ;; When link is located within the description of another
  9775. ;; link (e.g., an inline image), always open the parent
  9776. ;; link.
  9777. (let* ((link (let ((up (org-element-property :parent context)))
  9778. (if (eq (org-element-type up) 'link) up context)))
  9779. (type (org-element-property :type link))
  9780. (path (org-link-unescape (org-element-property :path link))))
  9781. ;; Switch back to REFERENCE-BUFFER needed when called in
  9782. ;; a temporary buffer through `org-open-link-from-string'.
  9783. (with-current-buffer (or reference-buffer (current-buffer))
  9784. (cond
  9785. ((equal type "file")
  9786. (if (string-match "[*?{]" (file-name-nondirectory path))
  9787. (dired path)
  9788. ;; Look into `org-link-parameters' in order to find
  9789. ;; a DEDICATED-FUNCTION to open file. The function
  9790. ;; will be applied on raw link instead of parsed
  9791. ;; link due to the limitation in `org-add-link-type'
  9792. ;; ("open" function called with a single argument).
  9793. ;; If no such function is found, fallback to
  9794. ;; `org-open-file'.
  9795. (let* ((option (org-element-property :search-option link))
  9796. (app (org-element-property :application link))
  9797. (dedicated-function
  9798. (org-link-get-parameter
  9799. (if app (concat type "+" app) type)
  9800. :follow)))
  9801. (if dedicated-function
  9802. (funcall dedicated-function
  9803. (concat path
  9804. (and option (concat "::" option))))
  9805. (apply #'org-open-file
  9806. path
  9807. (cond (arg)
  9808. ((equal app "emacs") 'emacs)
  9809. ((equal app "sys") 'system))
  9810. (cond ((not option) nil)
  9811. ((string-match-p "\\`[0-9]+\\'" option)
  9812. (list (string-to-number option)))
  9813. (t (list nil
  9814. (org-link-unescape option)))))))))
  9815. ((functionp (org-link-get-parameter type :follow))
  9816. (funcall (org-link-get-parameter type :follow) path))
  9817. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9818. (unless (run-hook-with-args-until-success
  9819. 'org-open-link-functions path)
  9820. (if (not arg) (org-mark-ring-push)
  9821. (switch-to-buffer-other-window
  9822. (org-get-buffer-for-internal-link (current-buffer))))
  9823. (let ((destination
  9824. (org-with-wide-buffer
  9825. (if (equal type "radio")
  9826. (org-search-radio-target
  9827. (org-element-property :path link))
  9828. (org-link-search
  9829. (if (member type '("custom-id" "coderef"))
  9830. (org-element-property :raw-link link)
  9831. path)
  9832. ;; Prevent fuzzy links from matching
  9833. ;; themselves.
  9834. (and (equal type "fuzzy")
  9835. (+ 2 (org-element-property :begin link)))))
  9836. (point))))
  9837. (unless (and (<= (point-min) destination)
  9838. (>= (point-max) destination))
  9839. (widen))
  9840. (goto-char destination))))
  9841. (t (browse-url-at-point))))))
  9842. ;; On a footnote reference or at a footnote definition's label.
  9843. ((or (eq type 'footnote-reference)
  9844. (and (eq type 'footnote-definition)
  9845. (save-excursion
  9846. ;; Do not validate action when point is on the
  9847. ;; spaces right after the footnote label, in
  9848. ;; order to be on par with behaviour on links.
  9849. (skip-chars-forward " \t")
  9850. (let ((begin
  9851. (org-element-property :contents-begin context)))
  9852. (if begin (< (point) begin)
  9853. (= (org-element-property :post-affiliated context)
  9854. (line-beginning-position)))))))
  9855. (org-footnote-action))
  9856. (t (user-error "No link found")))))
  9857. (run-hook-with-args 'org-follow-link-hook)))
  9858. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9859. "Offer links in the current entry and return the selected link.
  9860. If there is only one link, return it.
  9861. If NTH is an integer, return the NTH link found.
  9862. If ZERO is a string, check also this string for a link, and if
  9863. there is one, return it."
  9864. (with-current-buffer buffer
  9865. (save-excursion
  9866. (save-restriction
  9867. (widen)
  9868. (goto-char marker)
  9869. (let ((cnt ?0)
  9870. have-zero end links link c)
  9871. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9872. (push (match-string 0 zero) links)
  9873. (setq cnt (1- cnt) have-zero t))
  9874. (save-excursion
  9875. (org-back-to-heading t)
  9876. (setq end (save-excursion (outline-next-heading) (point)))
  9877. (while (re-search-forward org-any-link-re end t)
  9878. (push (match-string 0) links))
  9879. (setq links (org-uniquify (reverse links))))
  9880. (cond
  9881. ((null links)
  9882. (message "No links"))
  9883. ((equal (length links) 1)
  9884. (setq link (car links)))
  9885. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9886. (setq link (nth (if have-zero nth (1- nth)) links)))
  9887. (t ; we have to select a link
  9888. (save-excursion
  9889. (save-window-excursion
  9890. (delete-other-windows)
  9891. (with-output-to-temp-buffer "*Select Link*"
  9892. (dolist (l links)
  9893. (cond
  9894. ((not (string-match org-bracket-link-regexp l))
  9895. (princ (format "[%c] %s\n" (cl-incf cnt)
  9896. (org-remove-angle-brackets l))))
  9897. ((match-end 3)
  9898. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9899. (match-string 3 l) (match-string 1 l))))
  9900. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9901. (match-string 1 l)))))))
  9902. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9903. (message "Select link to open, RET to open all:")
  9904. (setq c (read-char-exclusive))
  9905. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9906. (when (equal c ?q) (user-error "Abort"))
  9907. (if (equal c ?\C-m)
  9908. (setq link links)
  9909. (setq nth (- c ?0))
  9910. (when have-zero (setq nth (1+ nth)))
  9911. (unless (and (integerp nth) (>= (length links) nth))
  9912. (user-error "Invalid link selection"))
  9913. (setq link (nth (1- nth) links)))))
  9914. (cons link end))))))
  9915. ;; TODO: These functions are deprecated since `org-open-at-point'
  9916. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9917. (defun org-open-file-with-system (path)
  9918. "Open file at PATH using the system way of opening it."
  9919. (org-open-file path 'system))
  9920. (defun org-open-file-with-emacs (path)
  9921. "Open file at PATH in Emacs."
  9922. (org-open-file path 'emacs))
  9923. ;;; File search
  9924. (defvar org-create-file-search-functions nil
  9925. "List of functions to construct the right search string for a file link.
  9926. These functions are called in turn with point at the location to
  9927. which the link should point.
  9928. A function in the hook should first test if it would like to
  9929. handle this file type, for example by checking the `major-mode'
  9930. or the file extension. If it decides not to handle this file, it
  9931. should just return nil to give other functions a chance. If it
  9932. does handle the file, it must return the search string to be used
  9933. when following the link. The search string will be part of the
  9934. file link, given after a double colon, and `org-open-at-point'
  9935. will automatically search for it. If special measures must be
  9936. taken to make the search successful, another function should be
  9937. added to the companion hook `org-execute-file-search-functions',
  9938. which see.
  9939. A function in this hook may also use `setq' to set the variable
  9940. `description' to provide a suggestion for the descriptive text to
  9941. be used for this link when it gets inserted into an Org buffer
  9942. with \\[org-insert-link].")
  9943. (defvar org-execute-file-search-functions nil
  9944. "List of functions to execute a file search triggered by a link.
  9945. Functions added to this hook must accept a single argument, the
  9946. search string that was part of the file link, the part after the
  9947. double colon. The function must first check if it would like to
  9948. handle this search, for example by checking the `major-mode' or
  9949. the file extension. If it decides not to handle this search, it
  9950. should just return nil to give other functions a chance. If it
  9951. does handle the search, it must return a non-nil value to keep
  9952. other functions from trying.
  9953. Each function can access the current prefix argument through the
  9954. variable `current-prefix-arg'. Note that a single prefix is used
  9955. to force opening a link in Emacs, so it may be good to only use a
  9956. numeric or double prefix to guide the search function.
  9957. In case this is needed, a function in this hook can also restore
  9958. the window configuration before `org-open-at-point' was called using:
  9959. \(set-window-configuration org-window-config-before-follow-link)")
  9960. (defun org-search-radio-target (target)
  9961. "Search a radio target matching TARGET in current buffer.
  9962. White spaces are not significant."
  9963. (let ((re (format "<<<%s>>>"
  9964. (mapconcat #'regexp-quote
  9965. (org-split-string target "[ \t\n]+")
  9966. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9967. (origin (point)))
  9968. (goto-char (point-min))
  9969. (catch :radio-match
  9970. (while (re-search-forward re nil t)
  9971. (backward-char)
  9972. (let ((object (org-element-context)))
  9973. (when (eq (org-element-type object) 'radio-target)
  9974. (goto-char (org-element-property :begin object))
  9975. (org-show-context 'link-search)
  9976. (throw :radio-match nil))))
  9977. (goto-char origin)
  9978. (user-error "No match for radio target: %s" target))))
  9979. (defun org-link-search (s &optional avoid-pos stealth)
  9980. "Search for a search string S.
  9981. If S starts with \"#\", it triggers a custom ID search.
  9982. If S is enclosed within parenthesis, it initiates a coderef
  9983. search.
  9984. If S is surrounded by forward slashes, it is interpreted as
  9985. a regular expression. In Org mode files, this will create an
  9986. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9987. to list matches. If the current buffer is in `dired-mode', grep
  9988. will be used to search in all files.
  9989. When AVOID-POS is given, ignore matches near that position.
  9990. When optional argument STEALTH is non-nil, do not modify
  9991. visibility around point, thus ignoring `org-show-context-detail'
  9992. variable.
  9993. Search is case-insensitive and ignores white spaces. Return type
  9994. of matched result, with is either `dedicated' or `fuzzy'."
  9995. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9996. (let* ((case-fold-search t)
  9997. (origin (point))
  9998. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9999. (words (org-split-string s "[ \t\n]+"))
  10000. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  10001. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  10002. type)
  10003. (cond
  10004. ;; Check if there are any special search functions.
  10005. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  10006. ((eq (string-to-char s) ?#)
  10007. ;; Look for a custom ID S if S starts with "#".
  10008. (let* ((id (substring normalized 1))
  10009. (match (org-find-property "CUSTOM_ID" id)))
  10010. (if match (progn (goto-char match) (setf type 'dedicated))
  10011. (error "No match for custom ID: %s" id))))
  10012. ((string-match "\\`(\\(.*\\))\\'" normalized)
  10013. ;; Look for coderef targets if S is enclosed within parenthesis.
  10014. (let ((coderef (match-string-no-properties 1 normalized))
  10015. (re (substring s-single-re 1 -1)))
  10016. (goto-char (point-min))
  10017. (catch :coderef-match
  10018. (while (re-search-forward re nil t)
  10019. (let ((element (org-element-at-point)))
  10020. (when (and (memq (org-element-type element)
  10021. '(example-block src-block))
  10022. ;; Build proper regexp according to current
  10023. ;; block's label format.
  10024. (let ((label-fmt
  10025. (regexp-quote
  10026. (or (org-element-property :label-fmt element)
  10027. org-coderef-label-format))))
  10028. (save-excursion
  10029. (beginning-of-line)
  10030. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  10031. (format label-fmt coderef))))))
  10032. (setq type 'dedicated)
  10033. (goto-char (match-beginning 1))
  10034. (throw :coderef-match nil))))
  10035. (goto-char origin)
  10036. (error "No match for coderef: %s" coderef))))
  10037. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10038. ;; Look for a regular expression.
  10039. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10040. (match-string 1 s)))
  10041. ;; Fuzzy links.
  10042. (t
  10043. (let ((starred (eq (string-to-char normalized) ?*)))
  10044. (cond
  10045. ;; Look for targets, only if not in a headline search.
  10046. ((and (not starred)
  10047. (let ((target (format "<<%s>>" s-multi-re)))
  10048. (catch :target-match
  10049. (goto-char (point-min))
  10050. (while (re-search-forward target nil t)
  10051. (backward-char)
  10052. (let ((context (org-element-context)))
  10053. (when (eq (org-element-type context) 'target)
  10054. (setq type 'dedicated)
  10055. (goto-char (org-element-property :begin context))
  10056. (throw :target-match t))))
  10057. nil))))
  10058. ;; Look for elements named after S, only if not in a headline
  10059. ;; search.
  10060. ((and (not starred)
  10061. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10062. (catch :name-match
  10063. (goto-char (point-min))
  10064. (while (re-search-forward name nil t)
  10065. (let ((element (org-element-at-point)))
  10066. (when (equal (org-split-string
  10067. (org-element-property :name element)
  10068. "[ \t]+")
  10069. words)
  10070. (setq type 'dedicated)
  10071. (beginning-of-line)
  10072. (throw :name-match t))))
  10073. nil))))
  10074. ;; Regular text search. Prefer headlines in Org mode
  10075. ;; buffers.
  10076. ((and (derived-mode-p 'org-mode)
  10077. (let* ((wspace "[ \t]")
  10078. (wspaceopt (concat wspace "*"))
  10079. (cookie (concat "\\(?:"
  10080. wspaceopt
  10081. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  10082. wspaceopt
  10083. "\\)"))
  10084. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10085. (re (concat
  10086. org-outline-regexp-bol
  10087. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  10088. "\\(?:\\[#.\\][ \t]+\\)?"
  10089. "\\(?:" org-comment-string "[ \t]+\\)?"
  10090. sep "?"
  10091. (let ((title (mapconcat #'regexp-quote
  10092. words
  10093. sep)))
  10094. (if starred (substring title 1) title))
  10095. sep "?"
  10096. "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
  10097. "[ \t]*$")))
  10098. (goto-char (point-min))
  10099. (re-search-forward re nil t)))
  10100. (goto-char (match-beginning 0))
  10101. (setq type 'dedicated))
  10102. ;; Offer to create non-existent headline depending on
  10103. ;; `org-link-search-must-match-exact-headline'.
  10104. ((and (derived-mode-p 'org-mode)
  10105. (not org-link-search-inhibit-query)
  10106. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10107. (yes-or-no-p "No match - create this as a new heading? "))
  10108. (goto-char (point-max))
  10109. (unless (bolp) (newline))
  10110. (org-insert-heading nil t t)
  10111. (insert s "\n")
  10112. (beginning-of-line 0))
  10113. ;; Only headlines are looked after. No need to process
  10114. ;; further: throw an error.
  10115. ((and (derived-mode-p 'org-mode)
  10116. (or starred org-link-search-must-match-exact-headline))
  10117. (goto-char origin)
  10118. (error "No match for fuzzy expression: %s" normalized))
  10119. ;; Regular text search.
  10120. ((catch :fuzzy-match
  10121. (goto-char (point-min))
  10122. (while (re-search-forward s-multi-re nil t)
  10123. ;; Skip match if it contains AVOID-POS or it is included
  10124. ;; in a link with a description but outside the
  10125. ;; description.
  10126. (unless (or (and avoid-pos
  10127. (<= (match-beginning 0) avoid-pos)
  10128. (> (match-end 0) avoid-pos))
  10129. (and (save-match-data
  10130. (org-in-regexp org-bracket-link-regexp))
  10131. (match-beginning 3)
  10132. (or (> (match-beginning 3) (point))
  10133. (<= (match-end 3) (point)))
  10134. (org-element-lineage
  10135. (save-match-data (org-element-context))
  10136. '(link) t)))
  10137. (goto-char (match-beginning 0))
  10138. (setq type 'fuzzy)
  10139. (throw :fuzzy-match t)))
  10140. nil))
  10141. ;; All failed. Throw an error.
  10142. (t (goto-char origin)
  10143. (error "No match for fuzzy expression: %s" normalized))))))
  10144. ;; Disclose surroundings of match, if appropriate.
  10145. (when (and (derived-mode-p 'org-mode) (not stealth))
  10146. (org-show-context 'link-search))
  10147. type))
  10148. (defun org-get-buffer-for-internal-link (buffer)
  10149. "Return a buffer to be used for displaying the link target of internal links."
  10150. (cond
  10151. ((not org-display-internal-link-with-indirect-buffer)
  10152. buffer)
  10153. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10154. (message "Buffer is already a clone, not making another one")
  10155. ;; we also do not modify visibility in this case
  10156. buffer)
  10157. (t ; make a new indirect buffer for displaying the link
  10158. (let* ((bn (buffer-name buffer))
  10159. (ibn (concat bn "(Clone)"))
  10160. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10161. (with-current-buffer ib (org-overview))
  10162. ib))))
  10163. (defun org-do-occur (regexp &optional cleanup)
  10164. "Call the Emacs command `occur'.
  10165. If CLEANUP is non-nil, remove the printout of the regular expression
  10166. in the *Occur* buffer. This is useful if the regex is long and not useful
  10167. to read."
  10168. (occur regexp)
  10169. (when cleanup
  10170. (let ((cwin (selected-window)) win beg end)
  10171. (when (setq win (get-buffer-window "*Occur*"))
  10172. (select-window win))
  10173. (goto-char (point-min))
  10174. (when (re-search-forward "match[a-z]+" nil t)
  10175. (setq beg (match-end 0))
  10176. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10177. (setq end (1- (match-beginning 0)))))
  10178. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10179. (goto-char (point-min))
  10180. (select-window cwin))))
  10181. ;;; The mark ring for links jumps
  10182. (defvar org-mark-ring nil
  10183. "Mark ring for positions before jumps in Org-mode.")
  10184. (defvar org-mark-ring-last-goto nil
  10185. "Last position in the mark ring used to go back.")
  10186. ;; Fill and close the ring
  10187. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10188. (dotimes (_ org-mark-ring-length)
  10189. (push (make-marker) org-mark-ring))
  10190. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10191. org-mark-ring)
  10192. (defun org-mark-ring-push (&optional pos buffer)
  10193. "Put the current position or POS into the mark ring and rotate it."
  10194. (interactive)
  10195. (setq pos (or pos (point)))
  10196. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10197. (move-marker (car org-mark-ring)
  10198. (or pos (point))
  10199. (or buffer (current-buffer)))
  10200. (message "%s"
  10201. (substitute-command-keys
  10202. "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
  10203. (defun org-mark-ring-goto (&optional n)
  10204. "Jump to the previous position in the mark ring.
  10205. With prefix arg N, jump back that many stored positions. When
  10206. called several times in succession, walk through the entire ring.
  10207. Org mode commands jumping to a different position in the current file,
  10208. or to another Org file, automatically push the old position onto the ring."
  10209. (interactive "p")
  10210. (let (p m)
  10211. (if (eq last-command this-command)
  10212. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10213. (setq p org-mark-ring))
  10214. (setq org-mark-ring-last-goto p)
  10215. (setq m (car p))
  10216. (pop-to-buffer-same-window (marker-buffer m))
  10217. (goto-char m)
  10218. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10219. ;;; TODO: Use string-remove-prefix and -suffix once we only support
  10220. ;;; Emacs 24.4+
  10221. (defun org-remove-angle-brackets (s)
  10222. (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
  10223. (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
  10224. s)
  10225. (defun org-add-angle-brackets (s)
  10226. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10227. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10228. s)
  10229. (defun org-remove-double-quotes (s)
  10230. (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
  10231. (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
  10232. s)
  10233. ;;; Following specific links
  10234. (defvar org-agenda-buffer-tmp-name)
  10235. (defvar org-agenda-start-on-weekday)
  10236. (defun org-follow-timestamp-link ()
  10237. "Open an agenda view for the time-stamp date/range at point."
  10238. (cond
  10239. ((org-at-date-range-p t)
  10240. (let ((org-agenda-start-on-weekday)
  10241. (t1 (match-string 1))
  10242. (t2 (match-string 2)) tt1 tt2)
  10243. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10244. tt2 (time-to-days (org-time-string-to-time t2)))
  10245. (let ((org-agenda-buffer-tmp-name
  10246. (format "*Org Agenda(a:%s)"
  10247. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10248. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10249. ((org-at-timestamp-p t)
  10250. (let ((org-agenda-buffer-tmp-name
  10251. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10252. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10253. (substring (match-string 1) 0 10)))
  10254. 1)))
  10255. (t (error "This should not happen"))))
  10256. ;;; Following file links
  10257. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10258. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10259. (declare-function mailcap-mime-info
  10260. "mailcap" (string &optional request no-decode))
  10261. (defvar org-wait nil)
  10262. (defun org-open-file (path &optional in-emacs line search)
  10263. "Open the file at PATH.
  10264. First, this expands any special file name abbreviations. Then the
  10265. configuration variable `org-file-apps' is checked if it contains an
  10266. entry for this file type, and if yes, the corresponding command is launched.
  10267. If no application is found, Emacs simply visits the file.
  10268. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10269. With a double \\[universal-argument] \\[universal-argument] \
  10270. prefix arg, Org tries to avoid opening in Emacs
  10271. and to use an external application to visit the file.
  10272. Optional LINE specifies a line to go to, optional SEARCH a string
  10273. to search for. If LINE or SEARCH is given, the file will be
  10274. opened in Emacs, unless an entry from org-file-apps that makes
  10275. use of groups in a regexp matches.
  10276. If you want to change the way frames are used when following a
  10277. link, please customize `org-link-frame-setup'.
  10278. If the file does not exist, an error is thrown."
  10279. (let* ((file (if (equal path "")
  10280. buffer-file-name
  10281. (substitute-in-file-name (expand-file-name path))))
  10282. (file-apps (append org-file-apps (org-default-apps)))
  10283. (apps (cl-remove-if
  10284. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10285. (apps-dlink (cl-remove-if-not
  10286. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10287. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10288. (dirp (unless remp (file-directory-p file)))
  10289. (file (if (and dirp org-open-directory-means-index-dot-org)
  10290. (concat (file-name-as-directory file) "index.org")
  10291. file))
  10292. (a-m-a-p (assq 'auto-mode apps))
  10293. (dfile (downcase file))
  10294. ;; Reconstruct the original link from the PATH, LINE and
  10295. ;; SEARCH args.
  10296. (link (cond (line (concat file "::" (number-to-string line)))
  10297. (search (concat file "::" search))
  10298. (t file)))
  10299. (dlink (downcase link))
  10300. (old-buffer (current-buffer))
  10301. (old-pos (point))
  10302. (old-mode major-mode)
  10303. (ext
  10304. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10305. (match-string 1 dfile)))
  10306. cmd link-match-data)
  10307. (cond
  10308. ((member in-emacs '((16) system))
  10309. (setq cmd (cdr (assq 'system apps))))
  10310. (in-emacs (setq cmd 'emacs))
  10311. (t
  10312. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10313. (and dirp (cdr (assq 'directory apps)))
  10314. ;; First, try matching against apps-dlink if we
  10315. ;; get a match here, store the match data for
  10316. ;; later.
  10317. (let ((match (assoc-default dlink apps-dlink
  10318. 'string-match)))
  10319. (if match
  10320. (progn (setq link-match-data (match-data))
  10321. match)
  10322. (progn (setq in-emacs (or in-emacs line search))
  10323. nil))) ; if we have no match in apps-dlink,
  10324. ; always open the file in emacs if line or search
  10325. ; is given (for backwards compatibility)
  10326. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10327. 'string-match)
  10328. (cdr (assoc ext apps))
  10329. (cdr (assq t apps))))))
  10330. (when (eq cmd 'system)
  10331. (setq cmd (cdr (assoc 'system apps))))
  10332. (when (eq cmd 'default)
  10333. (setq cmd (cdr (assoc t apps))))
  10334. (when (eq cmd 'mailcap)
  10335. (require 'mailcap)
  10336. (mailcap-parse-mailcaps)
  10337. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10338. (command (mailcap-mime-info mime-type)))
  10339. (if (stringp command)
  10340. (setq cmd command)
  10341. (setq cmd 'emacs))))
  10342. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10343. (not (file-exists-p file))
  10344. (not org-open-non-existing-files))
  10345. (user-error "No such file: %s" file))
  10346. (cond
  10347. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10348. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10349. (while (string-match "['\"]%s['\"]" cmd)
  10350. (setq cmd (replace-match "%s" t t cmd)))
  10351. (while (string-match "%s" cmd)
  10352. (setq cmd (replace-match
  10353. (save-match-data
  10354. (shell-quote-argument
  10355. (convert-standard-filename file)))
  10356. t t cmd)))
  10357. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10358. (save-match-data
  10359. (let ((match-index 1)
  10360. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10361. (set-match-data link-match-data)
  10362. (while (<= match-index number-of-groups)
  10363. (let ((regex (concat "%" (number-to-string match-index)))
  10364. (replace-with (match-string match-index dlink)))
  10365. (while (string-match regex cmd)
  10366. (setq cmd (replace-match replace-with t t cmd))))
  10367. (setq match-index (+ match-index 1)))))
  10368. (save-window-excursion
  10369. (message "Running %s...done" cmd)
  10370. (start-process-shell-command cmd nil cmd)
  10371. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10372. ((or (stringp cmd)
  10373. (eq cmd 'emacs))
  10374. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10375. (widen)
  10376. (cond (line (org-goto-line line)
  10377. (when (derived-mode-p 'org-mode) (org-reveal)))
  10378. (search (org-link-search search))))
  10379. ((functionp cmd)
  10380. (save-match-data
  10381. (set-match-data link-match-data)
  10382. (condition-case nil
  10383. (funcall cmd file link)
  10384. ;; FIXME: Remove this check when most default installations
  10385. ;; of Emacs have at least Org 9.0.
  10386. ((debug wrong-number-of-arguments wrong-type-argument
  10387. invalid-function)
  10388. (user-error "Please see Org News for version 9.0 about \
  10389. `org-file-apps'--Lisp error: %S" cmd)))))
  10390. ((consp cmd)
  10391. ;; FIXME: Remove this check when most default installations of
  10392. ;; Emacs have at least Org 9.0.
  10393. ;; Heads-up instead of silently fall back to
  10394. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10395. ;; with sexp instead of a function for `cmd'.
  10396. (user-error "Please see Org News for version 9.0 about \
  10397. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10398. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10399. (and (derived-mode-p 'org-mode)
  10400. (eq old-mode 'org-mode)
  10401. (or (not (eq old-buffer (current-buffer)))
  10402. (not (eq old-pos (point))))
  10403. (org-mark-ring-push old-pos old-buffer))))
  10404. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10405. "This function returns non-nil if `entry' uses a regular
  10406. expression which should be matched against the whole link by
  10407. org-open-file.
  10408. It assumes that is the case when the entry uses a regular
  10409. expression which has at least one grouping construct and the
  10410. action is either a lisp form or a command string containing
  10411. `%1', i.e. using at least one subexpression match as a
  10412. parameter."
  10413. (let ((selector (car entry))
  10414. (action (cdr entry)))
  10415. (if (stringp selector)
  10416. (and (> (regexp-opt-depth selector) 0)
  10417. (or (and (stringp action)
  10418. (string-match "%[0-9]" action))
  10419. (consp action)))
  10420. nil)))
  10421. (defun org-default-apps ()
  10422. "Return the default applications for this operating system."
  10423. (cond
  10424. ((eq system-type 'darwin)
  10425. org-file-apps-defaults-macosx)
  10426. ((eq system-type 'windows-nt)
  10427. org-file-apps-defaults-windowsnt)
  10428. (t org-file-apps-defaults-gnu)))
  10429. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10430. "Convert extensions to regular expressions in the cars of LIST.
  10431. Also, weed out any non-string entries, because the return value is used
  10432. only for regexp matching.
  10433. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10434. point to the symbol `emacs', indicating that the file should
  10435. be opened in Emacs."
  10436. (append
  10437. (delq nil
  10438. (mapcar (lambda (x)
  10439. (unless (not (stringp (car x)))
  10440. (if (string-match "\\W" (car x))
  10441. x
  10442. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10443. list))
  10444. (when add-auto-mode
  10445. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10446. (defvar ange-ftp-name-format)
  10447. (defun org-file-remote-p (file)
  10448. "Test whether FILE specifies a location on a remote system.
  10449. Return non-nil if the location is indeed remote.
  10450. For example, the filename \"/user@host:/foo\" specifies a location
  10451. on the system \"/user@host:\"."
  10452. (cond ((fboundp 'file-remote-p)
  10453. (file-remote-p file))
  10454. ((fboundp 'tramp-handle-file-remote-p)
  10455. (tramp-handle-file-remote-p file))
  10456. ((and (boundp 'ange-ftp-name-format)
  10457. (string-match (car ange-ftp-name-format) file))
  10458. t)))
  10459. ;;;; Refiling
  10460. (defun org-get-org-file ()
  10461. "Read a filename, with default directory `org-directory'."
  10462. (let ((default (or org-default-notes-file remember-data-file)))
  10463. (read-file-name (format "File name [%s]: " default)
  10464. (file-name-as-directory org-directory)
  10465. default)))
  10466. (defun org-notes-order-reversed-p ()
  10467. "Check if the current file should receive notes in reversed order."
  10468. (cond
  10469. ((not org-reverse-note-order) nil)
  10470. ((eq t org-reverse-note-order) t)
  10471. ((not (listp org-reverse-note-order)) nil)
  10472. (t (catch 'exit
  10473. (dolist (entry org-reverse-note-order)
  10474. (when (string-match (car entry) buffer-file-name)
  10475. (throw 'exit (cdr entry))))))))
  10476. (defvar org-refile-target-table nil
  10477. "The list of refile targets, created by `org-refile'.")
  10478. (defvar org-agenda-new-buffers nil
  10479. "Buffers created to visit agenda files.")
  10480. (defvar org-refile-cache nil
  10481. "Cache for refile targets.")
  10482. (defvar org-refile-markers nil
  10483. "All the markers used for caching refile locations.")
  10484. (defun org-refile-marker (pos)
  10485. "Get a new refile marker, but only if caching is in use."
  10486. (if (not org-refile-use-cache)
  10487. pos
  10488. (let ((m (make-marker)))
  10489. (move-marker m pos)
  10490. (push m org-refile-markers)
  10491. m)))
  10492. (defun org-refile-cache-clear ()
  10493. "Clear the refile cache and disable all the markers."
  10494. (dolist (m org-refile-markers) (move-marker m nil))
  10495. (setq org-refile-markers nil)
  10496. (setq org-refile-cache nil)
  10497. (message "Refile cache has been cleared"))
  10498. (defun org-refile-cache-check-set (set)
  10499. "Check if all the markers in the cache still have live buffers."
  10500. (let (marker)
  10501. (catch 'exit
  10502. (while (and set (setq marker (nth 3 (pop set))))
  10503. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10504. (when (and marker (null (marker-buffer marker)))
  10505. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10506. (sit-for 3)
  10507. (throw 'exit nil)))
  10508. t)))
  10509. (defun org-refile-cache-put (set &rest identifiers)
  10510. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10511. (let* ((key (sha1 (prin1-to-string identifiers)))
  10512. (entry (assoc key org-refile-cache)))
  10513. (if entry
  10514. (setcdr entry set)
  10515. (push (cons key set) org-refile-cache))))
  10516. (defun org-refile-cache-get (&rest identifiers)
  10517. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10518. (cond
  10519. ((not org-refile-cache) nil)
  10520. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10521. (t
  10522. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10523. org-refile-cache))))
  10524. (and set (org-refile-cache-check-set set) set)))))
  10525. (defvar org-outline-path-cache nil
  10526. "Alist between buffer positions and outline paths.
  10527. It value is an alist (POSITION . PATH) where POSITION is the
  10528. buffer position at the beginning of an entry and PATH is a list
  10529. of strings describing the outline path for that entry, in reverse
  10530. order.")
  10531. (defun org-refile-get-targets (&optional default-buffer)
  10532. "Produce a table with refile targets."
  10533. (let ((case-fold-search nil)
  10534. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10535. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10536. targets tgs files desc descre)
  10537. (message "Getting targets...")
  10538. (with-current-buffer (or default-buffer (current-buffer))
  10539. (dolist (entry entries)
  10540. (setq files (car entry) desc (cdr entry))
  10541. (cond
  10542. ((null files) (setq files (list (current-buffer))))
  10543. ((eq files 'org-agenda-files)
  10544. (setq files (org-agenda-files 'unrestricted)))
  10545. ((and (symbolp files) (fboundp files))
  10546. (setq files (funcall files)))
  10547. ((and (symbolp files) (boundp files))
  10548. (setq files (symbol-value files))))
  10549. (when (stringp files) (setq files (list files)))
  10550. (cond
  10551. ((eq (car desc) :tag)
  10552. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10553. ((eq (car desc) :todo)
  10554. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10555. ((eq (car desc) :regexp)
  10556. (setq descre (cdr desc)))
  10557. ((eq (car desc) :level)
  10558. (setq descre (concat "^\\*\\{" (number-to-string
  10559. (if org-odd-levels-only
  10560. (1- (* 2 (cdr desc)))
  10561. (cdr desc)))
  10562. "\\}[ \t]")))
  10563. ((eq (car desc) :maxlevel)
  10564. (setq descre (concat "^\\*\\{1," (number-to-string
  10565. (if org-odd-levels-only
  10566. (1- (* 2 (cdr desc)))
  10567. (cdr desc)))
  10568. "\\}[ \t]")))
  10569. (t (error "Bad refiling target description %s" desc)))
  10570. (dolist (f files)
  10571. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10572. (or
  10573. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10574. (progn
  10575. (when (bufferp f)
  10576. (setq f (buffer-file-name (buffer-base-buffer f))))
  10577. (setq f (and f (expand-file-name f)))
  10578. (when (eq org-refile-use-outline-path 'file)
  10579. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10580. (org-with-wide-buffer
  10581. (goto-char (point-min))
  10582. (setq org-outline-path-cache nil)
  10583. (while (re-search-forward descre nil t)
  10584. (beginning-of-line)
  10585. (looking-at org-complex-heading-regexp)
  10586. (let ((begin (point))
  10587. (heading (match-string-no-properties 4)))
  10588. (unless (or (and
  10589. org-refile-target-verify-function
  10590. (not
  10591. (funcall org-refile-target-verify-function)))
  10592. (not heading))
  10593. (let ((re (format org-complex-heading-regexp-format
  10594. (regexp-quote heading)))
  10595. (target
  10596. (if (not org-refile-use-outline-path) heading
  10597. (mapconcat
  10598. #'org-protect-slash
  10599. (append
  10600. (pcase org-refile-use-outline-path
  10601. (`file (list (file-name-nondirectory
  10602. (buffer-file-name
  10603. (buffer-base-buffer)))))
  10604. (`full-file-path
  10605. (list (buffer-file-name
  10606. (buffer-base-buffer))))
  10607. (_ nil))
  10608. (org-get-outline-path t t))
  10609. "/"))))
  10610. (push (list target f re (org-refile-marker (point)))
  10611. tgs)))
  10612. (when (= (point) begin)
  10613. ;; Verification function has not moved point.
  10614. (end-of-line)))))))
  10615. (when org-refile-use-cache
  10616. (org-refile-cache-put tgs (buffer-file-name) descre))
  10617. (setq targets (append tgs targets))))))
  10618. (message "Getting targets...done")
  10619. (nreverse targets)))
  10620. (defun org-protect-slash (s)
  10621. (while (string-match "/" s)
  10622. (setq s (replace-match "\\" t t s)))
  10623. s)
  10624. (defun org--get-outline-path-1 (&optional use-cache)
  10625. "Return outline path to current headline.
  10626. Outline path is a list of strings, in reverse order. When
  10627. optional argument USE-CACHE is non-nil, make use of a cache. See
  10628. `org-get-outline-path' for details.
  10629. Assume buffer is widened and point is on a headline."
  10630. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10631. (let ((p (point))
  10632. (heading (progn
  10633. (looking-at org-complex-heading-regexp)
  10634. (if (not (match-end 4)) ""
  10635. ;; Remove statistics cookies.
  10636. (org-trim
  10637. (org-link-display-format
  10638. (replace-regexp-in-string
  10639. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10640. (match-string-no-properties 4))))))))
  10641. (if (org-up-heading-safe)
  10642. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10643. (when use-cache
  10644. (push (cons p path) org-outline-path-cache))
  10645. path)
  10646. ;; This is a new root node. Since we assume we are moving
  10647. ;; forward, we can drop previous cache so as to limit number
  10648. ;; of associations there.
  10649. (let ((path (list heading)))
  10650. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10651. path)))))
  10652. (defun org-get-outline-path (&optional with-self use-cache)
  10653. "Return the outline path to the current entry.
  10654. An outline path is a list of ancestors for current headline, as
  10655. a list of strings. Statistics cookies are removed and links are
  10656. replaced with their description, if any, or their path otherwise.
  10657. When optional argument WITH-SELF is non-nil, the path also
  10658. includes the current headline.
  10659. When optional argument USE-CACHE is non-nil, cache outline paths
  10660. between calls to this function so as to avoid backtracking. This
  10661. argument is useful when planning to find more than one outline
  10662. path in the same document. In that case, there are two
  10663. conditions to satisfy:
  10664. - `org-outline-path-cache' is set to nil before starting the
  10665. process;
  10666. - outline paths are computed by increasing buffer positions."
  10667. (org-with-wide-buffer
  10668. (and (or (and with-self (org-back-to-heading t))
  10669. (org-up-heading-safe))
  10670. (reverse (org--get-outline-path-1 use-cache)))))
  10671. (defun org-format-outline-path (path &optional width prefix separator)
  10672. "Format the outline path PATH for display.
  10673. WIDTH is the maximum number of characters that is available.
  10674. PREFIX is a prefix to be included in the returned string,
  10675. such as the file name.
  10676. SEPARATOR is inserted between the different parts of the path,
  10677. the default is \"/\"."
  10678. (setq width (or width 79))
  10679. (setq path (delq nil path))
  10680. (unless (> width 0)
  10681. (user-error "Argument `width' must be positive"))
  10682. (setq separator (or separator "/"))
  10683. (let* ((org-odd-levels-only nil)
  10684. (fpath (concat
  10685. prefix (and prefix path separator)
  10686. (mapconcat
  10687. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10688. (cl-loop for head in path
  10689. for n from 0
  10690. collect (org-add-props
  10691. head nil 'face
  10692. (nth (% n org-n-level-faces) org-level-faces)))
  10693. separator))))
  10694. (when (> (length fpath) width)
  10695. (if (< width 7)
  10696. ;; It's unlikely that `width' will be this small, but don't
  10697. ;; waste characters by adding ".." if it is.
  10698. (setq fpath (substring fpath 0 width))
  10699. (setf (substring fpath (- width 2)) "..")))
  10700. fpath))
  10701. (defun org-display-outline-path (&optional file current separator just-return-string)
  10702. "Display the current outline path in the echo area.
  10703. If FILE is non-nil, prepend the output with the file name.
  10704. If CURRENT is non-nil, append the current heading to the output.
  10705. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10706. the different parts of the path and defaults to \"/\".
  10707. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10708. (interactive "P")
  10709. (let* (case-fold-search
  10710. (bfn (buffer-file-name (buffer-base-buffer)))
  10711. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10712. res)
  10713. (when current (setq path (append path
  10714. (save-excursion
  10715. (org-back-to-heading t)
  10716. (when (looking-at org-complex-heading-regexp)
  10717. (list (match-string 4)))))))
  10718. (setq res
  10719. (org-format-outline-path
  10720. path
  10721. (1- (frame-width))
  10722. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10723. separator))
  10724. (if just-return-string
  10725. (org-no-properties res)
  10726. (org-unlogged-message "%s" res))))
  10727. (defvar org-refile-history nil
  10728. "History for refiling operations.")
  10729. (defvar org-after-refile-insert-hook nil
  10730. "Hook run after `org-refile' has inserted its stuff at the new location.
  10731. Note that this is still *before* the stuff will be removed from
  10732. the *old* location.")
  10733. (defvar org-capture-last-stored-marker)
  10734. (defvar org-refile-keep nil
  10735. "Non-nil means `org-refile' will copy instead of refile.")
  10736. (defun org-copy ()
  10737. "Like `org-refile', but copy."
  10738. (interactive)
  10739. (let ((org-refile-keep t))
  10740. (funcall 'org-refile nil nil nil "Copy")))
  10741. (defun org-refile (&optional arg default-buffer rfloc msg)
  10742. "Move the entry or entries at point to another heading.
  10743. The list of target headings is compiled using the information in
  10744. `org-refile-targets', which see.
  10745. At the target location, the entry is filed as a subitem of the
  10746. target heading. Depending on `org-reverse-note-order', the new
  10747. subitem will either be the first or the last subitem.
  10748. If there is an active region, all entries in that region will be
  10749. refiled. However, the region must fulfill the requirement that
  10750. the first heading sets the top-level of the moved text.
  10751. With prefix arg ARG, the command will only visit the target
  10752. location and not actually move anything.
  10753. With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
  10754. refiling operation has put the subtree.
  10755. With a numeric prefix argument of `2', refile to the running clock.
  10756. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10757. being set to t and copy to the target location, don't move it.
  10758. Beware that keeping refiled entries may result in duplicated ID
  10759. properties.
  10760. RFLOC can be a refile location obtained in a different way.
  10761. MSG is a string to replace \"Refile\" in the default prompt with
  10762. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10763. See also `org-refile-use-outline-path'.
  10764. If you are using target caching (see `org-refile-use-cache'), you
  10765. have to clear the target cache in order to find new targets.
  10766. This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
  10767. prefix argument (`C-u C-u C-u C-c C-w')."
  10768. (interactive "P")
  10769. (if (member arg '(0 (64)))
  10770. (org-refile-cache-clear)
  10771. (let* ((actionmsg (cond (msg msg)
  10772. ((equal arg 3) "Refile (and keep)")
  10773. (t "Refile")))
  10774. (regionp (org-region-active-p))
  10775. (region-start (and regionp (region-beginning)))
  10776. (region-end (and regionp (region-end)))
  10777. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10778. pos it nbuf file level reversed)
  10779. (setq last-command nil)
  10780. (when regionp
  10781. (goto-char region-start)
  10782. (or (bolp) (goto-char (point-at-bol)))
  10783. (setq region-start (point))
  10784. (unless (or (org-kill-is-subtree-p
  10785. (buffer-substring region-start region-end))
  10786. (prog1 org-refile-active-region-within-subtree
  10787. (let ((s (point-at-eol)))
  10788. (org-toggle-heading)
  10789. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10790. (user-error "The region is not a (sequence of) subtree(s)")))
  10791. (if (equal arg '(16))
  10792. (org-refile-goto-last-stored)
  10793. (when (or
  10794. (and (equal arg 2)
  10795. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10796. (prog1
  10797. (setq it (list (or org-clock-heading "running clock")
  10798. (buffer-file-name
  10799. (marker-buffer org-clock-hd-marker))
  10800. ""
  10801. (marker-position org-clock-hd-marker)))
  10802. (setq arg nil)))
  10803. (setq it
  10804. (or rfloc
  10805. (let (heading-text)
  10806. (save-excursion
  10807. (unless (and arg (listp arg))
  10808. (org-back-to-heading t)
  10809. (setq heading-text
  10810. (replace-regexp-in-string
  10811. org-bracket-link-regexp
  10812. "\\3"
  10813. (or (nth 4 (org-heading-components))
  10814. ""))))
  10815. (org-refile-get-location
  10816. (cond ((and arg (listp arg)) "Goto")
  10817. (regionp (concat actionmsg " region to"))
  10818. (t (concat actionmsg " subtree \""
  10819. heading-text "\" to")))
  10820. default-buffer
  10821. (and (not (equal '(4) arg))
  10822. org-refile-allow-creating-parent-nodes)))))))
  10823. (setq file (nth 1 it)
  10824. pos (nth 3 it))
  10825. (when (and (not arg)
  10826. pos
  10827. (equal (buffer-file-name) file)
  10828. (if regionp
  10829. (and (>= pos region-start)
  10830. (<= pos region-end))
  10831. (and (>= pos (point))
  10832. (< pos (save-excursion
  10833. (org-end-of-subtree t t))))))
  10834. (error "Cannot refile to position inside the tree or region"))
  10835. (setq nbuf (or (find-buffer-visiting file)
  10836. (find-file-noselect file)))
  10837. (if (and arg (not (equal arg 3)))
  10838. (progn
  10839. (pop-to-buffer-same-window nbuf)
  10840. (goto-char pos)
  10841. (org-show-context 'org-goto))
  10842. (if regionp
  10843. (progn
  10844. (org-kill-new (buffer-substring region-start region-end))
  10845. (org-save-markers-in-region region-start region-end))
  10846. (org-copy-subtree 1 nil t))
  10847. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10848. (find-file-noselect file)))
  10849. (setq reversed (org-notes-order-reversed-p))
  10850. (save-excursion
  10851. (save-restriction
  10852. (widen)
  10853. (if pos
  10854. (progn
  10855. (goto-char pos)
  10856. (looking-at org-outline-regexp)
  10857. (setq level (org-get-valid-level (funcall outline-level) 1))
  10858. (goto-char
  10859. (if reversed
  10860. (or (outline-next-heading) (point-max))
  10861. (or (save-excursion (org-get-next-sibling))
  10862. (org-end-of-subtree t t)
  10863. (point-max)))))
  10864. (setq level 1)
  10865. (if (not reversed)
  10866. (goto-char (point-max))
  10867. (goto-char (point-min))
  10868. (or (outline-next-heading) (goto-char (point-max)))))
  10869. (unless (bolp) (newline))
  10870. (org-paste-subtree level nil nil t)
  10871. (when org-log-refile
  10872. (org-add-log-setup 'refile nil nil org-log-refile)
  10873. (unless (eq org-log-refile 'note)
  10874. (save-excursion (org-add-log-note))))
  10875. (and org-auto-align-tags
  10876. (let ((org-loop-over-headlines-in-active-region nil))
  10877. (org-set-tags nil t)))
  10878. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10879. :last-refile)))
  10880. (when bookmark-name
  10881. (with-demoted-errors
  10882. (bookmark-set bookmark-name))))
  10883. ;; If we are refiling for capture, make sure that the
  10884. ;; last-capture pointers point here
  10885. (when (bound-and-true-p org-capture-is-refiling)
  10886. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10887. :last-capture-marker)))
  10888. (when bookmark-name
  10889. (with-demoted-errors
  10890. (bookmark-set bookmark-name))))
  10891. (move-marker org-capture-last-stored-marker (point)))
  10892. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10893. (run-hooks 'org-after-refile-insert-hook))))
  10894. (unless org-refile-keep
  10895. (if regionp
  10896. (delete-region (point) (+ (point) (- region-end region-start)))
  10897. (delete-region
  10898. (and (org-back-to-heading t) (point))
  10899. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10900. (when (featurep 'org-inlinetask)
  10901. (org-inlinetask-remove-END-maybe))
  10902. (setq org-markers-to-move nil)
  10903. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10904. (defun org-refile-goto-last-stored ()
  10905. "Go to the location where the last refile was stored."
  10906. (interactive)
  10907. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10908. (message "This is the location of the last refile"))
  10909. (defun org-refile--get-location (refloc tbl)
  10910. "When user refile to REFLOC, find the associated target in TBL.
  10911. Also check `org-refile-target-table'."
  10912. (car (delq
  10913. nil
  10914. (mapcar
  10915. (lambda (r) (or (assoc r tbl)
  10916. (assoc r org-refile-target-table)))
  10917. (list (replace-regexp-in-string "/$" "" refloc)
  10918. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10919. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10920. "Prompt the user for a refile location, using PROMPT.
  10921. PROMPT should not be suffixed with a colon and a space, because
  10922. this function appends the default value from
  10923. `org-refile-history' automatically, if that is not empty."
  10924. (let ((org-refile-targets org-refile-targets)
  10925. (org-refile-use-outline-path org-refile-use-outline-path))
  10926. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10927. (unless org-refile-target-table
  10928. (user-error "No refile targets"))
  10929. (let* ((cbuf (current-buffer))
  10930. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10931. (cfunc (if (and org-refile-use-outline-path
  10932. org-outline-path-complete-in-steps)
  10933. #'org-olpath-completing-read
  10934. #'completing-read))
  10935. (extra (if org-refile-use-outline-path "/" ""))
  10936. (cbnex (concat (buffer-name) extra))
  10937. (filename (and cfn (expand-file-name cfn)))
  10938. (tbl (mapcar
  10939. (lambda (x)
  10940. (if (and (not (member org-refile-use-outline-path
  10941. '(file full-file-path)))
  10942. (not (equal filename (nth 1 x))))
  10943. (cons (concat (car x) extra " ("
  10944. (file-name-nondirectory (nth 1 x)) ")")
  10945. (cdr x))
  10946. (cons (concat (car x) extra) (cdr x))))
  10947. org-refile-target-table))
  10948. (completion-ignore-case t)
  10949. cdef
  10950. (prompt (concat prompt
  10951. (or (and (car org-refile-history)
  10952. (concat " (default " (car org-refile-history) ")"))
  10953. (and (assoc cbnex tbl) (setq cdef cbnex)
  10954. (concat " (default " cbnex ")"))) ": "))
  10955. pa answ parent-target child parent old-hist)
  10956. (setq old-hist org-refile-history)
  10957. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10958. nil 'org-refile-history (or cdef (car org-refile-history))))
  10959. (if (setq pa (org-refile--get-location answ tbl))
  10960. (progn
  10961. (org-refile-check-position pa)
  10962. (when (or (not org-refile-history)
  10963. (not (eq old-hist org-refile-history))
  10964. (not (equal (car pa) (car org-refile-history))))
  10965. (setq org-refile-history
  10966. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10967. org-refile-history
  10968. (cdr org-refile-history))))
  10969. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10970. (pop org-refile-history)))
  10971. pa)
  10972. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10973. (progn
  10974. (setq parent (match-string 1 answ)
  10975. child (match-string 2 answ))
  10976. (setq parent-target (org-refile--get-location parent tbl))
  10977. (when (and parent-target
  10978. (or (eq new-nodes t)
  10979. (and (eq new-nodes 'confirm)
  10980. (y-or-n-p (format "Create new node \"%s\"? "
  10981. child)))))
  10982. (org-refile-new-child parent-target child)))
  10983. (user-error "Invalid target location")))))
  10984. (declare-function org-string-nw-p "org-macs" (s))
  10985. (defun org-refile-check-position (refile-pointer)
  10986. "Check if the refile pointer matches the headline to which it points."
  10987. (let* ((file (nth 1 refile-pointer))
  10988. (re (nth 2 refile-pointer))
  10989. (pos (nth 3 refile-pointer))
  10990. buffer)
  10991. (if (and (not (markerp pos)) (not file))
  10992. (user-error "Please indicate a target file in the refile path")
  10993. (when (org-string-nw-p re)
  10994. (setq buffer (if (markerp pos)
  10995. (marker-buffer pos)
  10996. (or (find-buffer-visiting file)
  10997. (find-file-noselect file))))
  10998. (with-current-buffer buffer
  10999. (save-excursion
  11000. (save-restriction
  11001. (widen)
  11002. (goto-char pos)
  11003. (beginning-of-line 1)
  11004. (unless (looking-at-p re)
  11005. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
  11006. (defun org-refile-new-child (parent-target child)
  11007. "Use refile target PARENT-TARGET to add new CHILD below it."
  11008. (unless parent-target
  11009. (error "Cannot find parent for new node"))
  11010. (let ((file (nth 1 parent-target))
  11011. (pos (nth 3 parent-target))
  11012. level)
  11013. (with-current-buffer (or (find-buffer-visiting file)
  11014. (find-file-noselect file))
  11015. (save-excursion
  11016. (save-restriction
  11017. (widen)
  11018. (if pos
  11019. (goto-char pos)
  11020. (goto-char (point-max))
  11021. (unless (bolp) (newline)))
  11022. (when (looking-at org-outline-regexp)
  11023. (setq level (funcall outline-level))
  11024. (org-end-of-subtree t t))
  11025. (org-back-over-empty-lines)
  11026. (insert "\n" (make-string
  11027. (if pos (org-get-valid-level level 1) 1) ?*)
  11028. " " child "\n")
  11029. (beginning-of-line 0)
  11030. (list (concat (car parent-target) "/" child) file "" (point)))))))
  11031. (defun org-olpath-completing-read (prompt collection &rest args)
  11032. "Read an outline path like a file name."
  11033. (let ((thetable collection))
  11034. (apply #'completing-read
  11035. prompt
  11036. (lambda (string predicate &optional flag)
  11037. (cond
  11038. ((eq flag nil) (try-completion string thetable))
  11039. ((eq flag t)
  11040. (let ((l (length string)))
  11041. (mapcar (lambda (x)
  11042. (let ((r (substring x l))
  11043. (f (if (string-match " ([^)]*)$" x)
  11044. (match-string 0 x)
  11045. "")))
  11046. (if (string-match "/" r)
  11047. (concat string (substring r 0 (match-end 0)) f)
  11048. x)))
  11049. (all-completions string thetable predicate))))
  11050. ;; Exact match?
  11051. ((eq flag 'lambda) (assoc string thetable))))
  11052. args)))
  11053. ;;;; Dynamic blocks
  11054. (defun org-find-dblock (name)
  11055. "Find the first dynamic block with name NAME in the buffer.
  11056. If not found, stay at current position and return nil."
  11057. (let ((case-fold-search t) pos)
  11058. (save-excursion
  11059. (goto-char (point-min))
  11060. (setq pos (and (re-search-forward
  11061. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11062. (match-beginning 0))))
  11063. (when pos (goto-char pos))
  11064. pos))
  11065. (defun org-create-dblock (plist)
  11066. "Create a dynamic block section, with parameters taken from PLIST.
  11067. PLIST must contain a :name entry which is used as the name of the block."
  11068. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11069. (end-of-line 1)
  11070. (newline))
  11071. (let ((col (current-column))
  11072. (name (plist-get plist :name)))
  11073. (insert "#+BEGIN: " name)
  11074. (while plist
  11075. (if (eq (car plist) :name)
  11076. (setq plist (cddr plist))
  11077. (insert " " (prin1-to-string (pop plist)))))
  11078. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11079. (beginning-of-line -2)))
  11080. (defun org-prepare-dblock ()
  11081. "Prepare dynamic block for refresh.
  11082. This empties the block, puts the cursor at the insert position and returns
  11083. the property list including an extra property :name with the block name."
  11084. (unless (looking-at org-dblock-start-re)
  11085. (user-error "Not at a dynamic block"))
  11086. (let* ((begdel (1+ (match-end 0)))
  11087. (name (org-no-properties (match-string 1)))
  11088. (params (append (list :name name)
  11089. (read (concat "(" (match-string 3) ")")))))
  11090. (save-excursion
  11091. (beginning-of-line 1)
  11092. (skip-chars-forward " \t")
  11093. (setq params (plist-put params :indentation-column (current-column))))
  11094. (unless (re-search-forward org-dblock-end-re nil t)
  11095. (error "Dynamic block not terminated"))
  11096. (setq params
  11097. (append params
  11098. (list :content (buffer-substring
  11099. begdel (match-beginning 0)))))
  11100. (delete-region begdel (match-beginning 0))
  11101. (goto-char begdel)
  11102. (open-line 1)
  11103. params))
  11104. (defun org-map-dblocks (&optional command)
  11105. "Apply COMMAND to all dynamic blocks in the current buffer.
  11106. If COMMAND is not given, use `org-update-dblock'."
  11107. (let ((cmd (or command 'org-update-dblock)))
  11108. (save-excursion
  11109. (goto-char (point-min))
  11110. (while (re-search-forward org-dblock-start-re nil t)
  11111. (goto-char (match-beginning 0))
  11112. (save-excursion
  11113. (condition-case nil
  11114. (funcall cmd)
  11115. (error (message "Error during update of dynamic block"))))
  11116. (unless (re-search-forward org-dblock-end-re nil t)
  11117. (error "Dynamic block not terminated"))))))
  11118. (defun org-dblock-update (&optional arg)
  11119. "User command for updating dynamic blocks.
  11120. Update the dynamic block at point. With prefix ARG, update all dynamic
  11121. blocks in the buffer."
  11122. (interactive "P")
  11123. (if arg
  11124. (org-update-all-dblocks)
  11125. (or (looking-at org-dblock-start-re)
  11126. (org-beginning-of-dblock))
  11127. (org-update-dblock)))
  11128. (defun org-update-dblock ()
  11129. "Update the dynamic block at point.
  11130. This means to empty the block, parse for parameters and then call
  11131. the correct writing function."
  11132. (interactive)
  11133. (save-excursion
  11134. (let* ((win (selected-window))
  11135. (pos (point))
  11136. (line (org-current-line))
  11137. (params (org-prepare-dblock))
  11138. (name (plist-get params :name))
  11139. (indent (plist-get params :indentation-column))
  11140. (cmd (intern (concat "org-dblock-write:" name))))
  11141. (message "Updating dynamic block `%s' at line %d..." name line)
  11142. (funcall cmd params)
  11143. (message "Updating dynamic block `%s' at line %d...done" name line)
  11144. (goto-char pos)
  11145. (when (and indent (> indent 0))
  11146. (setq indent (make-string indent ?\ ))
  11147. (save-excursion
  11148. (select-window win)
  11149. (org-beginning-of-dblock)
  11150. (forward-line 1)
  11151. (while (not (looking-at org-dblock-end-re))
  11152. (insert indent)
  11153. (beginning-of-line 2))
  11154. (when (looking-at org-dblock-end-re)
  11155. (and (looking-at "[ \t]+")
  11156. (replace-match ""))
  11157. (insert indent)))))))
  11158. (defun org-beginning-of-dblock ()
  11159. "Find the beginning of the dynamic block at point.
  11160. Error if there is no such block at point."
  11161. (let ((pos (point))
  11162. beg)
  11163. (end-of-line 1)
  11164. (if (and (re-search-backward org-dblock-start-re nil t)
  11165. (setq beg (match-beginning 0))
  11166. (re-search-forward org-dblock-end-re nil t)
  11167. (> (match-end 0) pos))
  11168. (goto-char beg)
  11169. (goto-char pos)
  11170. (error "Not in a dynamic block"))))
  11171. (defun org-update-all-dblocks ()
  11172. "Update all dynamic blocks in the buffer.
  11173. This function can be used in a hook."
  11174. (interactive)
  11175. (when (derived-mode-p 'org-mode)
  11176. (org-map-dblocks 'org-update-dblock)))
  11177. ;;;; Completion
  11178. (declare-function org-export-backend-options "ox" (cl-x) t)
  11179. (defun org-get-export-keywords ()
  11180. "Return a list of all currently understood export keywords.
  11181. Export keywords include options, block names, attributes and
  11182. keywords relative to each registered export back-end."
  11183. (let (keywords)
  11184. (dolist (backend
  11185. (bound-and-true-p org-export-registered-backends)
  11186. (delq nil keywords))
  11187. ;; Back-end name (for keywords, like #+LATEX:)
  11188. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11189. (dolist (option-entry (org-export-backend-options backend))
  11190. ;; Back-end options.
  11191. (push (nth 1 option-entry) keywords)))))
  11192. (defconst org-options-keywords
  11193. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11194. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11195. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11196. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11197. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11198. (defcustom org-structure-template-alist
  11199. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11200. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11201. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11202. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11203. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11204. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11205. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11206. ("L" "#+LaTeX: ")
  11207. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11208. ("H" "#+HTML: ")
  11209. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11210. ("A" "#+ASCII: ")
  11211. ("i" "#+INDEX: ?")
  11212. ("I" "#+INCLUDE: %file ?"))
  11213. "Structure completion elements.
  11214. This is a list of abbreviation keys and values. The value gets inserted
  11215. if you type `<' followed by the key and then press the completion key,
  11216. usually `TAB'. %file will be replaced by a file name after prompting
  11217. for the file using completion. The cursor will be placed at the position
  11218. of the `?' in the template.
  11219. There are two templates for each key, the first uses the original Org syntax,
  11220. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11221. the default when the /org-mtags.el/ module has been loaded. See also the
  11222. variable `org-mtags-prefer-muse-templates'."
  11223. :group 'org-completion
  11224. :type '(repeat
  11225. (list
  11226. (string :tag "Key")
  11227. (string :tag "Template")))
  11228. :version "25.1"
  11229. :package-version '(Org . "8.3"))
  11230. (defun org-try-structure-completion ()
  11231. "Try to complete a structure template before point.
  11232. This looks for strings like \"<e\" on an otherwise empty line and
  11233. expands them."
  11234. (let ((l (buffer-substring (point-at-bol) (point)))
  11235. a)
  11236. (when (and (looking-at "[ \t]*$")
  11237. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11238. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11239. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11240. (match-beginning 1)) a)
  11241. t)))
  11242. (defun org-complete-expand-structure-template (start cell)
  11243. "Expand a structure template."
  11244. (let ((rpl (nth 1 cell))
  11245. (ind ""))
  11246. (delete-region start (point))
  11247. (when (string-match "\\`[ \t]*#\\+" rpl)
  11248. (cond
  11249. ((bolp))
  11250. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11251. (setq ind (buffer-substring (point-at-bol) (point))))
  11252. (t (newline))))
  11253. (setq start (point))
  11254. (when (string-match "%file" rpl)
  11255. (setq rpl (replace-match
  11256. (concat
  11257. "\""
  11258. (save-match-data
  11259. (abbreviate-file-name (read-file-name "Include file: ")))
  11260. "\"")
  11261. t t rpl)))
  11262. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11263. (concat "\n" ind)))
  11264. (insert rpl)
  11265. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11266. ;;;; TODO, DEADLINE, Comments
  11267. (defun org-toggle-comment ()
  11268. "Change the COMMENT state of an entry."
  11269. (interactive)
  11270. (save-excursion
  11271. (org-back-to-heading)
  11272. (looking-at org-complex-heading-regexp)
  11273. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11274. (skip-chars-forward " \t")
  11275. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11276. (if (org-in-commented-heading-p t)
  11277. (delete-region (point)
  11278. (progn (search-forward " " (line-end-position) 'move)
  11279. (skip-chars-forward " \t")
  11280. (point)))
  11281. (insert org-comment-string)
  11282. (unless (eolp) (insert " ")))))
  11283. (defvar org-last-todo-state-is-todo nil
  11284. "This is non-nil when the last TODO state change led to a TODO state.
  11285. If the last change removed the TODO tag or switched to DONE, then
  11286. this is nil.")
  11287. (defvar org-setting-tags nil) ; dynamically skipped
  11288. (defvar org-todo-setup-filter-hook nil
  11289. "Hook for functions that pre-filter todo specs.
  11290. Each function takes a todo spec and returns either nil or the spec
  11291. transformed into canonical form." )
  11292. (defvar org-todo-get-default-hook nil
  11293. "Hook for functions that get a default item for todo.
  11294. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11295. nil or a string to be used for the todo mark." )
  11296. (defvar org-agenda-headline-snapshot-before-repeat)
  11297. (defun org-current-effective-time ()
  11298. "Return current time adjusted for `org-extend-today-until' variable."
  11299. (let* ((ct (org-current-time))
  11300. (dct (decode-time ct))
  11301. (ct1
  11302. (cond
  11303. (org-use-last-clock-out-time-as-effective-time
  11304. (or (org-clock-get-last-clock-out-time) ct))
  11305. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11306. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11307. (t ct))))
  11308. ct1))
  11309. (defun org-todo-yesterday (&optional arg)
  11310. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11311. (interactive "P")
  11312. (if (eq major-mode 'org-agenda-mode)
  11313. (apply 'org-agenda-todo-yesterday arg)
  11314. (let* ((org-use-effective-time t)
  11315. (hour (nth 2 (decode-time (org-current-time))))
  11316. (org-extend-today-until (1+ hour)))
  11317. (org-todo arg))))
  11318. (defvar org-block-entry-blocking ""
  11319. "First entry preventing the TODO state change.")
  11320. (defun org-cancel-repeater ()
  11321. "Cancel a repeater by setting its numeric value to zero."
  11322. (interactive)
  11323. (save-excursion
  11324. (org-back-to-heading t)
  11325. (let ((bound1 (point))
  11326. (bound0 (save-excursion (outline-next-heading) (point))))
  11327. (when (and (re-search-forward
  11328. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11329. org-deadline-time-regexp "\\)\\|\\("
  11330. org-ts-regexp "\\)")
  11331. bound0 t)
  11332. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11333. bound1 t))
  11334. (replace-match "0" t nil nil 1)))))
  11335. (defvar org-state) ;; dynamically scoped into this function
  11336. (defun org-todo (&optional arg)
  11337. "Change the TODO state of an item.
  11338. The state of an item is given by a keyword at the start of the heading,
  11339. like
  11340. *** TODO Write paper
  11341. *** DONE Call mom
  11342. The different keywords are specified in the variable `org-todo-keywords'.
  11343. By default the available states are \"TODO\" and \"DONE\".
  11344. So for this example: when the item starts with TODO, it is changed to DONE.
  11345. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11346. DONE are present, add TODO at the beginning of the heading.
  11347. With \\[universal-argument] prefix arg, use completion to determine the new \
  11348. state.
  11349. With numeric prefix arg, switch to that state.
  11350. With a double \\[universal-argument] prefix, switch to the next set of TODO \
  11351. keywords (nextset).
  11352. With a triple \\[universal-argument] prefix, circumvent any state blocking.
  11353. With a numeric prefix arg of 0, inhibit note taking for the change.
  11354. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11355. When called through ELisp, arg is also interpreted in the following way:
  11356. `none' -> empty state
  11357. \"\"(empty string) -> switch to empty state
  11358. `done' -> switch to DONE
  11359. `nextset' -> switch to the next set of keywords
  11360. `previousset' -> switch to the previous set of keywords
  11361. \"WAITING\" -> switch to the specified keyword, but only if it
  11362. really is a member of `org-todo-keywords'."
  11363. (interactive "P")
  11364. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11365. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11366. 'region-start-level 'region))
  11367. org-loop-over-headlines-in-active-region)
  11368. (org-map-entries
  11369. `(org-todo ,arg)
  11370. org-loop-over-headlines-in-active-region
  11371. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11372. (when (equal arg '(16)) (setq arg 'nextset))
  11373. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11374. (let ((org-blocker-hook org-blocker-hook)
  11375. commentp
  11376. case-fold-search)
  11377. (when (equal arg '(64))
  11378. (setq arg nil org-blocker-hook nil))
  11379. (when (and org-blocker-hook
  11380. (or org-inhibit-blocking
  11381. (org-entry-get nil "NOBLOCKING")))
  11382. (setq org-blocker-hook nil))
  11383. (save-excursion
  11384. (catch 'exit
  11385. (org-back-to-heading t)
  11386. (when (org-in-commented-heading-p t)
  11387. (org-toggle-comment)
  11388. (setq commentp t))
  11389. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11390. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11391. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11392. (let* ((match-data (match-data))
  11393. (startpos (point-at-bol))
  11394. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11395. (org-log-done org-log-done)
  11396. (org-log-repeat org-log-repeat)
  11397. (org-todo-log-states org-todo-log-states)
  11398. (org-inhibit-logging
  11399. (if (equal arg 0)
  11400. (progn (setq arg nil) 'note) org-inhibit-logging))
  11401. (this (match-string 1))
  11402. (hl-pos (match-beginning 0))
  11403. (head (org-get-todo-sequence-head this))
  11404. (ass (assoc head org-todo-kwd-alist))
  11405. (interpret (nth 1 ass))
  11406. (done-word (nth 3 ass))
  11407. (final-done-word (nth 4 ass))
  11408. (org-last-state (or this ""))
  11409. (completion-ignore-case t)
  11410. (member (member this org-todo-keywords-1))
  11411. (tail (cdr member))
  11412. (org-state (cond
  11413. ((and org-todo-key-trigger
  11414. (or (and (equal arg '(4))
  11415. (eq org-use-fast-todo-selection 'prefix))
  11416. (and (not arg) org-use-fast-todo-selection
  11417. (not (eq org-use-fast-todo-selection
  11418. 'prefix)))))
  11419. ;; Use fast selection
  11420. (org-fast-todo-selection))
  11421. ((and (equal arg '(4))
  11422. (or (not org-use-fast-todo-selection)
  11423. (not org-todo-key-trigger)))
  11424. ;; Read a state with completion
  11425. (completing-read
  11426. "State: " (mapcar #'list org-todo-keywords-1)
  11427. nil t))
  11428. ((eq arg 'right)
  11429. (if this
  11430. (if tail (car tail) nil)
  11431. (car org-todo-keywords-1)))
  11432. ((eq arg 'left)
  11433. (unless (equal member org-todo-keywords-1)
  11434. (if this
  11435. (nth (- (length org-todo-keywords-1)
  11436. (length tail) 2)
  11437. org-todo-keywords-1)
  11438. (org-last org-todo-keywords-1))))
  11439. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11440. (setq arg nil))) ; hack to fall back to cycling
  11441. (arg
  11442. ;; user or caller requests a specific state
  11443. (cond
  11444. ((equal arg "") nil)
  11445. ((eq arg 'none) nil)
  11446. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11447. ((eq arg 'nextset)
  11448. (or (car (cdr (member head org-todo-heads)))
  11449. (car org-todo-heads)))
  11450. ((eq arg 'previousset)
  11451. (let ((org-todo-heads (reverse org-todo-heads)))
  11452. (or (car (cdr (member head org-todo-heads)))
  11453. (car org-todo-heads))))
  11454. ((car (member arg org-todo-keywords-1)))
  11455. ((stringp arg)
  11456. (user-error "State `%s' not valid in this file" arg))
  11457. ((nth (1- (prefix-numeric-value arg))
  11458. org-todo-keywords-1))))
  11459. ((null member) (or head (car org-todo-keywords-1)))
  11460. ((equal this final-done-word) nil) ;; -> make empty
  11461. ((null tail) nil) ;; -> first entry
  11462. ((memq interpret '(type priority))
  11463. (if (eq this-command last-command)
  11464. (car tail)
  11465. (if (> (length tail) 0)
  11466. (or done-word (car org-done-keywords))
  11467. nil)))
  11468. (t
  11469. (car tail))))
  11470. (org-state (or
  11471. (run-hook-with-args-until-success
  11472. 'org-todo-get-default-hook org-state org-last-state)
  11473. org-state))
  11474. (next (if org-state (concat " " org-state " ") " "))
  11475. (change-plist (list :type 'todo-state-change :from this :to org-state
  11476. :position startpos))
  11477. dolog now-done-p)
  11478. (when org-blocker-hook
  11479. (setq org-last-todo-state-is-todo
  11480. (not (member this org-done-keywords)))
  11481. (unless (save-excursion
  11482. (save-match-data
  11483. (org-with-wide-buffer
  11484. (run-hook-with-args-until-failure
  11485. 'org-blocker-hook change-plist))))
  11486. (if (called-interactively-p 'interactive)
  11487. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11488. this org-state org-block-entry-blocking)
  11489. ;; fail silently
  11490. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11491. this org-state org-block-entry-blocking)
  11492. (throw 'exit nil))))
  11493. (store-match-data match-data)
  11494. (replace-match next t t)
  11495. (cond ((equal this org-state)
  11496. (message "TODO state was already %s" (org-trim next)))
  11497. ((pos-visible-in-window-p hl-pos)
  11498. (message "TODO state changed to %s" (org-trim next))))
  11499. (unless head
  11500. (setq head (org-get-todo-sequence-head org-state)
  11501. ass (assoc head org-todo-kwd-alist)
  11502. interpret (nth 1 ass)
  11503. done-word (nth 3 ass)
  11504. final-done-word (nth 4 ass)))
  11505. (when (memq arg '(nextset previousset))
  11506. (message "Keyword-Set %d/%d: %s"
  11507. (- (length org-todo-sets) -1
  11508. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11509. (length org-todo-sets)
  11510. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11511. (setq org-last-todo-state-is-todo
  11512. (not (member org-state org-done-keywords)))
  11513. (setq now-done-p (and (member org-state org-done-keywords)
  11514. (not (member this org-done-keywords))))
  11515. (and logging (org-local-logging logging))
  11516. (when (and (or org-todo-log-states org-log-done)
  11517. (not (eq org-inhibit-logging t))
  11518. (not (memq arg '(nextset previousset))))
  11519. ;; we need to look at recording a time and note
  11520. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11521. (nth 2 (assoc this org-todo-log-states))))
  11522. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11523. (setq dolog 'time))
  11524. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11525. (and org-state
  11526. (member org-state org-not-done-keywords)
  11527. (not (member this org-not-done-keywords))))
  11528. ;; This is now a todo state and was not one before
  11529. ;; If there was a CLOSED time stamp, get rid of it.
  11530. (org-add-planning-info nil nil 'closed))
  11531. (when (and now-done-p org-log-done)
  11532. ;; It is now done, and it was not done before
  11533. (org-add-planning-info 'closed (org-current-effective-time))
  11534. (when (and (not dolog) (eq 'note org-log-done))
  11535. (org-add-log-setup 'done org-state this 'note)))
  11536. (when (and org-state dolog)
  11537. ;; This is a non-nil state, and we need to log it
  11538. (org-add-log-setup 'state org-state this dolog)))
  11539. ;; Fixup tag positioning
  11540. (org-todo-trigger-tag-changes org-state)
  11541. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11542. (when org-provide-todo-statistics
  11543. (org-update-parent-todo-statistics))
  11544. (run-hooks 'org-after-todo-state-change-hook)
  11545. (when (and arg (not (member org-state org-done-keywords)))
  11546. (setq head (org-get-todo-sequence-head org-state)))
  11547. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11548. ;; Do we need to trigger a repeat?
  11549. (when now-done-p
  11550. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11551. ;; This is for the agenda, take a snapshot of the headline.
  11552. (save-match-data
  11553. (setq org-agenda-headline-snapshot-before-repeat
  11554. (org-get-heading))))
  11555. (org-auto-repeat-maybe org-state))
  11556. ;; Fixup cursor location if close to the keyword
  11557. (when (and (outline-on-heading-p)
  11558. (not (bolp))
  11559. (save-excursion (beginning-of-line 1)
  11560. (looking-at org-todo-line-regexp))
  11561. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11562. (goto-char (or (match-end 2) (match-end 1)))
  11563. (and (looking-at " ") (just-one-space)))
  11564. (when org-trigger-hook
  11565. (save-excursion
  11566. (run-hook-with-args 'org-trigger-hook change-plist)))
  11567. (when commentp (org-toggle-comment))))))))
  11568. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11569. "Block turning an entry into a TODO, using the hierarchy.
  11570. This checks whether the current task should be blocked from state
  11571. changes. Such blocking occurs when:
  11572. 1. The task has children which are not all in a completed state.
  11573. 2. A task has a parent with the property :ORDERED:, and there
  11574. are siblings prior to the current task with incomplete
  11575. status.
  11576. 3. The parent of the task is blocked because it has siblings that should
  11577. be done first, or is child of a block grandparent TODO entry."
  11578. (if (not org-enforce-todo-dependencies)
  11579. t ; if locally turned off don't block
  11580. (catch 'dont-block
  11581. ;; If this is not a todo state change, or if this entry is already DONE,
  11582. ;; do not block
  11583. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11584. (member (plist-get change-plist :from)
  11585. (cons 'done org-done-keywords))
  11586. (member (plist-get change-plist :to)
  11587. (cons 'todo org-not-done-keywords))
  11588. (not (plist-get change-plist :to)))
  11589. (throw 'dont-block t))
  11590. ;; If this task has children, and any are undone, it's blocked
  11591. (save-excursion
  11592. (org-back-to-heading t)
  11593. (let ((this-level (funcall outline-level)))
  11594. (outline-next-heading)
  11595. (let ((child-level (funcall outline-level)))
  11596. (while (and (not (eobp))
  11597. (> child-level this-level))
  11598. ;; this todo has children, check whether they are all
  11599. ;; completed
  11600. (when (and (not (org-entry-is-done-p))
  11601. (org-entry-is-todo-p))
  11602. (setq org-block-entry-blocking (org-get-heading))
  11603. (throw 'dont-block nil))
  11604. (outline-next-heading)
  11605. (setq child-level (funcall outline-level))))))
  11606. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11607. ;; any previous siblings are undone, it's blocked
  11608. (save-excursion
  11609. (org-back-to-heading t)
  11610. (let* ((pos (point))
  11611. (parent-pos (and (org-up-heading-safe) (point))))
  11612. (unless parent-pos (throw 'dont-block t)) ; no parent
  11613. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11614. (forward-line 1)
  11615. (re-search-forward org-not-done-heading-regexp pos t))
  11616. (setq org-block-entry-blocking (match-string 0))
  11617. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11618. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11619. (while t
  11620. (goto-char parent-pos)
  11621. (unless (looking-at org-not-done-heading-regexp)
  11622. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11623. (setq pos (point))
  11624. (setq parent-pos (and (org-up-heading-safe) (point)))
  11625. (unless parent-pos (throw 'dont-block t)) ; no parent
  11626. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11627. (forward-line 1)
  11628. (re-search-forward org-not-done-heading-regexp pos t)
  11629. (setq org-block-entry-blocking (org-get-heading)))
  11630. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11631. (defcustom org-track-ordered-property-with-tag nil
  11632. "Should the ORDERED property also be shown as a tag?
  11633. The ORDERED property decides if an entry should require subtasks to be
  11634. completed in sequence. Since a property is not very visible, setting
  11635. this option means that toggling the ORDERED property with the command
  11636. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11637. not relevant for the behavior, but it makes things more visible.
  11638. Note that toggling the tag with tags commands will not change the property
  11639. and therefore not influence behavior!
  11640. This can be t, meaning the tag ORDERED should be used, It can also be a
  11641. string to select a different tag for this task."
  11642. :group 'org-todo
  11643. :type '(choice
  11644. (const :tag "No tracking" nil)
  11645. (const :tag "Track with ORDERED tag" t)
  11646. (string :tag "Use other tag")))
  11647. (defun org-toggle-ordered-property ()
  11648. "Toggle the ORDERED property of the current entry.
  11649. For better visibility, you can track the value of this property with a tag.
  11650. See variable `org-track-ordered-property-with-tag'."
  11651. (interactive)
  11652. (let* ((t1 org-track-ordered-property-with-tag)
  11653. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11654. (save-excursion
  11655. (org-back-to-heading)
  11656. (if (org-entry-get nil "ORDERED")
  11657. (progn
  11658. (org-delete-property "ORDERED")
  11659. (and tag (org-toggle-tag tag 'off))
  11660. (message "Subtasks can be completed in arbitrary order"))
  11661. (org-entry-put nil "ORDERED" "t")
  11662. (and tag (org-toggle-tag tag 'on))
  11663. (message "Subtasks must be completed in sequence")))))
  11664. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11665. (defun org-block-todo-from-checkboxes (change-plist)
  11666. "Block turning an entry into a TODO, using checkboxes.
  11667. This checks whether the current task should be blocked from state
  11668. changes because there are unchecked boxes in this entry."
  11669. (if (not org-enforce-todo-checkbox-dependencies)
  11670. t ; if locally turned off don't block
  11671. (catch 'dont-block
  11672. ;; If this is not a todo state change, or if this entry is already DONE,
  11673. ;; do not block
  11674. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11675. (member (plist-get change-plist :from)
  11676. (cons 'done org-done-keywords))
  11677. (member (plist-get change-plist :to)
  11678. (cons 'todo org-not-done-keywords))
  11679. (not (plist-get change-plist :to)))
  11680. (throw 'dont-block t))
  11681. ;; If this task has checkboxes that are not checked, it's blocked
  11682. (save-excursion
  11683. (org-back-to-heading t)
  11684. (let ((beg (point)) end)
  11685. (outline-next-heading)
  11686. (setq end (point))
  11687. (goto-char beg)
  11688. (when (org-list-search-forward
  11689. (concat (org-item-beginning-re)
  11690. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11691. "\\[[- ]\\]")
  11692. end t)
  11693. (when (boundp 'org-blocked-by-checkboxes)
  11694. (setq org-blocked-by-checkboxes t))
  11695. (throw 'dont-block nil))))
  11696. t))) ; do not block
  11697. (defun org-entry-blocked-p ()
  11698. "Non-nil if entry at point is blocked."
  11699. (and (not (org-entry-get nil "NOBLOCKING"))
  11700. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11701. (not (run-hook-with-args-until-failure
  11702. 'org-blocker-hook
  11703. (list :type 'todo-state-change
  11704. :position (point)
  11705. :from 'todo
  11706. :to 'done)))))
  11707. (defun org-update-statistics-cookies (all)
  11708. "Update the statistics cookie, either from TODO or from checkboxes.
  11709. This should be called with the cursor in a line with a statistics cookie."
  11710. (interactive "P")
  11711. (if all
  11712. (progn
  11713. (org-update-checkbox-count 'all)
  11714. (org-map-entries 'org-update-parent-todo-statistics))
  11715. (if (not (org-at-heading-p))
  11716. (org-update-checkbox-count)
  11717. (let ((pos (point-marker))
  11718. end l1 l2)
  11719. (ignore-errors (org-back-to-heading t))
  11720. (if (not (org-at-heading-p))
  11721. (org-update-checkbox-count)
  11722. (setq l1 (org-outline-level))
  11723. (setq end (save-excursion
  11724. (outline-next-heading)
  11725. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11726. (point)))
  11727. (if (and (save-excursion
  11728. (re-search-forward
  11729. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11730. (not (save-excursion (re-search-forward
  11731. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11732. (org-update-checkbox-count)
  11733. (if (and l2 (> l2 l1))
  11734. (progn
  11735. (goto-char end)
  11736. (org-update-parent-todo-statistics))
  11737. (goto-char pos)
  11738. (beginning-of-line 1)
  11739. (while (re-search-forward
  11740. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11741. (point-at-eol) t)
  11742. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11743. (goto-char pos)
  11744. (move-marker pos nil)))))
  11745. (defvar org-entry-property-inherited-from) ;; defined below
  11746. (defun org-update-parent-todo-statistics ()
  11747. "Update any statistics cookie in the parent of the current headline.
  11748. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11749. the entire subtree and this will travel up the hierarchy and update
  11750. statistics everywhere."
  11751. (let* ((prop (save-excursion (org-up-heading-safe)
  11752. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11753. (recursive (or (not org-hierarchical-todo-statistics)
  11754. (and prop (string-match "\\<recursive\\>" prop))))
  11755. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11756. 0))
  11757. (first t)
  11758. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11759. level ltoggle l1 new ndel
  11760. (cnt-all 0) (cnt-done 0) is-percent kwd
  11761. checkbox-beg cookie-present)
  11762. (catch 'exit
  11763. (save-excursion
  11764. (beginning-of-line 1)
  11765. (setq ltoggle (funcall outline-level))
  11766. ;; Three situations are to consider:
  11767. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11768. ;; to the top-level ancestor on the headline;
  11769. ;; 2. If parent has "recursive" property, repeat up to the
  11770. ;; headline setting that property, taking inheritance into
  11771. ;; account;
  11772. ;; 3. Else, move up to direct parent and proceed only once.
  11773. (while (and (setq level (org-up-heading-safe))
  11774. (or recursive first)
  11775. (>= (point) lim))
  11776. (setq first nil cookie-present nil)
  11777. (unless (and level
  11778. (not (string-match
  11779. "\\<checkbox\\>"
  11780. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11781. "")))))
  11782. (throw 'exit nil))
  11783. (while (re-search-forward box-re (point-at-eol) t)
  11784. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11785. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11786. (save-match-data
  11787. (unless (outline-next-heading) (throw 'exit nil))
  11788. (while (and (looking-at org-complex-heading-regexp)
  11789. (> (setq l1 (length (match-string 1))) level))
  11790. (setq kwd (and (or recursive (= l1 ltoggle))
  11791. (match-string 2)))
  11792. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11793. (and (eq org-provide-todo-statistics t)
  11794. (or (member kwd org-done-keywords)))
  11795. (and (listp org-provide-todo-statistics)
  11796. (stringp (car org-provide-todo-statistics))
  11797. (or (member kwd org-provide-todo-statistics)
  11798. (member kwd org-done-keywords)))
  11799. (and (listp org-provide-todo-statistics)
  11800. (listp (car org-provide-todo-statistics))
  11801. (or (member kwd (car org-provide-todo-statistics))
  11802. (and (member kwd org-done-keywords)
  11803. (member kwd (cadr org-provide-todo-statistics))))))
  11804. (setq cnt-all (1+ cnt-all))
  11805. (and (eq org-provide-todo-statistics t)
  11806. kwd
  11807. (setq cnt-all (1+ cnt-all))))
  11808. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11809. (member kwd org-done-keywords))
  11810. (and (listp org-provide-todo-statistics)
  11811. (listp (car org-provide-todo-statistics))
  11812. (member kwd org-done-keywords)
  11813. (member kwd (cadr org-provide-todo-statistics)))
  11814. (and (listp org-provide-todo-statistics)
  11815. (stringp (car org-provide-todo-statistics))
  11816. (member kwd org-done-keywords)))
  11817. (setq cnt-done (1+ cnt-done)))
  11818. (outline-next-heading)))
  11819. (setq new
  11820. (if is-percent
  11821. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11822. (max 1 cnt-all)))
  11823. (format "[%d/%d]" cnt-done cnt-all))
  11824. ndel (- (match-end 0) checkbox-beg))
  11825. (goto-char checkbox-beg)
  11826. (insert new)
  11827. (delete-region (point) (+ (point) ndel))
  11828. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11829. (when cookie-present
  11830. (run-hook-with-args 'org-after-todo-statistics-hook
  11831. cnt-done (- cnt-all cnt-done))))))
  11832. (run-hooks 'org-todo-statistics-hook)))
  11833. (defvar org-after-todo-statistics-hook nil
  11834. "Hook that is called after a TODO statistics cookie has been updated.
  11835. Each function is called with two arguments: the number of not-done entries
  11836. and the number of done entries.
  11837. For example, the following function, when added to this hook, will switch
  11838. an entry to DONE when all children are done, and back to TODO when new
  11839. entries are set to a TODO status. Note that this hook is only called
  11840. when there is a statistics cookie in the headline!
  11841. \(defun org-summary-todo (n-done n-not-done)
  11842. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11843. \(let (org-log-done org-log-states) ; turn off logging
  11844. \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11845. ")
  11846. (defvar org-todo-statistics-hook nil
  11847. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11848. This hook runs even if there is no statistics cookie present, in which case
  11849. `org-after-todo-statistics-hook' would not run.")
  11850. (defun org-todo-trigger-tag-changes (state)
  11851. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11852. (let ((l org-todo-state-tags-triggers)
  11853. changes)
  11854. (when (or (not state) (equal state ""))
  11855. (setq changes (append changes (cdr (assoc "" l)))))
  11856. (when (and (stringp state) (> (length state) 0))
  11857. (setq changes (append changes (cdr (assoc state l)))))
  11858. (when (member state org-not-done-keywords)
  11859. (setq changes (append changes (cdr (assoc 'todo l)))))
  11860. (when (member state org-done-keywords)
  11861. (setq changes (append changes (cdr (assoc 'done l)))))
  11862. (dolist (c changes)
  11863. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11864. (defun org-local-logging (value)
  11865. "Get logging settings from a property VALUE."
  11866. ;; Directly set the variables, they are already local.
  11867. (setq org-log-done nil
  11868. org-log-repeat nil
  11869. org-todo-log-states nil)
  11870. (dolist (w (org-split-string value))
  11871. (let (a)
  11872. (cond
  11873. ((setq a (assoc w org-startup-options))
  11874. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11875. (set (nth 1 a) (nth 2 a))))
  11876. ((setq a (org-extract-log-state-settings w))
  11877. (and (member (car a) org-todo-keywords-1)
  11878. (push a org-todo-log-states)))))))
  11879. (defun org-get-todo-sequence-head (kwd)
  11880. "Return the head of the TODO sequence to which KWD belongs.
  11881. If KWD is not set, check if there is a text property remembering the
  11882. right sequence."
  11883. (let (p)
  11884. (cond
  11885. ((not kwd)
  11886. (or (get-text-property (point-at-bol) 'org-todo-head)
  11887. (progn
  11888. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11889. nil (point-at-eol)))
  11890. (get-text-property p 'org-todo-head))))
  11891. ((not (member kwd org-todo-keywords-1))
  11892. (car org-todo-keywords-1))
  11893. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11894. (defun org-fast-todo-selection ()
  11895. "Fast TODO keyword selection with single keys.
  11896. Returns the new TODO keyword, or nil if no state change should occur."
  11897. (let* ((fulltable org-todo-key-alist)
  11898. (done-keywords org-done-keywords) ;; needed for the faces.
  11899. (maxlen (apply 'max (mapcar
  11900. (lambda (x)
  11901. (if (stringp (car x)) (string-width (car x)) 0))
  11902. fulltable)))
  11903. (expert nil)
  11904. (fwidth (+ maxlen 3 1 3))
  11905. (ncol (/ (- (window-width) 4) fwidth))
  11906. tg cnt e c tbl
  11907. groups ingroup)
  11908. (save-excursion
  11909. (save-window-excursion
  11910. (if expert
  11911. (set-buffer (get-buffer-create " *Org todo*"))
  11912. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11913. (erase-buffer)
  11914. (setq-local org-done-keywords done-keywords)
  11915. (setq tbl fulltable cnt 0)
  11916. (while (setq e (pop tbl))
  11917. (cond
  11918. ((equal e '(:startgroup))
  11919. (push '() groups) (setq ingroup t)
  11920. (unless (= cnt 0)
  11921. (setq cnt 0)
  11922. (insert "\n"))
  11923. (insert "{ "))
  11924. ((equal e '(:endgroup))
  11925. (setq ingroup nil cnt 0)
  11926. (insert "}\n"))
  11927. ((equal e '(:newline))
  11928. (unless (= cnt 0)
  11929. (setq cnt 0)
  11930. (insert "\n")
  11931. (setq e (car tbl))
  11932. (while (equal (car tbl) '(:newline))
  11933. (insert "\n")
  11934. (setq tbl (cdr tbl)))))
  11935. (t
  11936. (setq tg (car e) c (cdr e))
  11937. (when ingroup (push tg (car groups)))
  11938. (setq tg (org-add-props tg nil 'face
  11939. (org-get-todo-face tg)))
  11940. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11941. (insert "[" c "] " tg (make-string
  11942. (- fwidth 4 (length tg)) ?\ ))
  11943. (when (= (setq cnt (1+ cnt)) ncol)
  11944. (insert "\n")
  11945. (when ingroup (insert " "))
  11946. (setq cnt 0)))))
  11947. (insert "\n")
  11948. (goto-char (point-min))
  11949. (unless expert (org-fit-window-to-buffer))
  11950. (message "[a-z..]:Set [SPC]:clear")
  11951. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11952. (cond
  11953. ((or (= c ?\C-g)
  11954. (and (= c ?q) (not (rassoc c fulltable))))
  11955. (setq quit-flag t))
  11956. ((= c ?\ ) nil)
  11957. ((setq e (rassoc c fulltable) tg (car e))
  11958. tg)
  11959. (t (setq quit-flag t)))))))
  11960. (defun org-entry-is-todo-p ()
  11961. (member (org-get-todo-state) org-not-done-keywords))
  11962. (defun org-entry-is-done-p ()
  11963. (member (org-get-todo-state) org-done-keywords))
  11964. (defun org-get-todo-state ()
  11965. "Return the TODO keyword of the current subtree."
  11966. (save-excursion
  11967. (org-back-to-heading t)
  11968. (and (looking-at org-todo-line-regexp)
  11969. (match-end 2)
  11970. (match-string 2))))
  11971. (defun org-at-date-range-p (&optional inactive-ok)
  11972. "Non-nil if point is inside a date range.
  11973. When optional argument INACTIVE-OK is non-nil, also consider
  11974. inactive time ranges.
  11975. When this function returns a non-nil value, match data is set
  11976. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11977. on INACTIVE-OK."
  11978. (interactive)
  11979. (save-excursion
  11980. (catch 'exit
  11981. (let ((pos (point)))
  11982. (skip-chars-backward "^[<\r\n")
  11983. (skip-chars-backward "<[")
  11984. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11985. (>= (match-end 0) pos)
  11986. (throw 'exit t))
  11987. (skip-chars-backward "^<[\r\n")
  11988. (skip-chars-backward "<[")
  11989. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11990. (>= (match-end 0) pos)
  11991. (throw 'exit t)))
  11992. nil)))
  11993. (defun org-get-repeat (&optional tagline)
  11994. "Check if there is a deadline/schedule with repeater in this entry."
  11995. (save-match-data
  11996. (save-excursion
  11997. (org-back-to-heading t)
  11998. (and (re-search-forward (if tagline
  11999. (concat tagline "\\s-*" org-repeat-re)
  12000. org-repeat-re)
  12001. (org-entry-end-position) t)
  12002. (match-string-no-properties 1)))))
  12003. (defvar org-last-changed-timestamp)
  12004. (defvar org-last-inserted-timestamp)
  12005. (defvar org-log-post-message)
  12006. (defvar org-log-note-purpose)
  12007. (defvar org-log-note-how nil)
  12008. (defvar org-log-note-extra)
  12009. (defun org-auto-repeat-maybe (done-word)
  12010. "Check if the current headline contains a repeated time-stamp.
  12011. If yes, set TODO state back to what it was and change the base date
  12012. of repeating deadline/scheduled time stamps to new date.
  12013. This function is run automatically after each state change to a DONE state."
  12014. (let* ((repeat (org-get-repeat))
  12015. (aa (assoc org-last-state org-todo-kwd-alist))
  12016. (interpret (nth 1 aa))
  12017. (head (nth 2 aa))
  12018. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  12019. (msg "Entry repeats: ")
  12020. (org-log-done nil)
  12021. (org-todo-log-states nil))
  12022. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  12023. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  12024. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  12025. org-todo-repeat-to-state)))
  12026. (unless (and to-state (member to-state org-todo-keywords-1))
  12027. (setq to-state (if (eq interpret 'type) org-last-state head)))
  12028. (org-todo to-state))
  12029. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  12030. (org-entry-put nil "LAST_REPEAT" (format-time-string
  12031. (org-time-stamp-format t t))))
  12032. (when org-log-repeat
  12033. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  12034. (memq 'org-add-log-note post-command-hook))
  12035. ;; We are already setup for some record.
  12036. (when (eq org-log-repeat 'note)
  12037. ;; Make sure we take a note, not only a time stamp.
  12038. (setq org-log-note-how 'note))
  12039. ;; Set up for taking a record.
  12040. (org-add-log-setup 'state
  12041. (or done-word (car org-done-keywords))
  12042. org-last-state
  12043. org-log-repeat)))
  12044. (org-back-to-heading t)
  12045. (org-add-planning-info nil nil 'closed)
  12046. (let ((end (save-excursion (outline-next-heading) (point))))
  12047. (while (re-search-forward org-ts-regexp end t)
  12048. (when (save-match-data
  12049. (or (org-at-planning-p)
  12050. (org-at-property-p)
  12051. (eq (org-element-type (save-excursion
  12052. (backward-char)
  12053. (org-element-context)))
  12054. 'timestamp)))
  12055. (let ((type (cond ((match-end 1) org-scheduled-string)
  12056. ((match-end 3) org-deadline-string)
  12057. (t "Plain:")))
  12058. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  12059. (cond
  12060. ((not
  12061. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12062. ;; Time-stamps without a repeater are usually skipped.
  12063. ;; However, a SCHEDULED time-stamp without one is
  12064. ;; removed, as it is considered as no longer relevant.
  12065. (when (equal type org-scheduled-string)
  12066. (org-remove-timestamp-with-keyword type)))
  12067. (t
  12068. (let ((n (string-to-number (match-string 2 ts)))
  12069. (what (match-string 3 ts)))
  12070. (when (equal what "w") (setq n (* n 7) what "d"))
  12071. (when (and (equal what "h")
  12072. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12073. ts)))
  12074. (user-error
  12075. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12076. has been set"
  12077. n))
  12078. ;; Preparation, see if we need to modify the start
  12079. ;; date for the change.
  12080. (when (match-end 1)
  12081. (let ((time (save-match-data (org-time-string-to-time ts))))
  12082. (cond
  12083. ((equal (match-string 1 ts) ".")
  12084. ;; Shift starting date to today
  12085. (org-timestamp-change
  12086. (- (org-today) (time-to-days time))
  12087. 'day))
  12088. ((equal (match-string 1 ts) "+")
  12089. (let ((nshiftmax 10)
  12090. (nshift 0))
  12091. (while (or (= nshift 0)
  12092. (not (time-less-p (current-time) time)))
  12093. (when (= (cl-incf nshift) nshiftmax)
  12094. (or (y-or-n-p
  12095. (format "%d repeater intervals were not \
  12096. enough to shift date past today. Continue? "
  12097. nshift))
  12098. (user-error "Abort")))
  12099. (org-timestamp-change n (cdr (assoc what whata)))
  12100. (org-at-timestamp-p t)
  12101. (setq ts (match-string 1))
  12102. (setq time
  12103. (save-match-data
  12104. (org-time-string-to-time ts)))))
  12105. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12106. ;; Rematch, so that we have everything in
  12107. ;; place for the real shift.
  12108. (org-at-timestamp-p t)
  12109. (setq ts (match-string 1))
  12110. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12111. ts)))))
  12112. (save-excursion
  12113. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12114. (setq msg
  12115. (concat
  12116. msg type " " org-last-changed-timestamp " ")))))))))
  12117. (setq org-log-post-message msg)
  12118. (message "%s" msg))))
  12119. (defun org-show-todo-tree (arg)
  12120. "Make a compact tree which shows all headlines marked with TODO.
  12121. The tree will show the lines where the regexp matches, and all higher
  12122. headlines above the match.
  12123. With a \\[universal-argument] prefix, prompt for a regexp to match.
  12124. With a numeric prefix N, construct a sparse tree for the Nth element
  12125. of `org-todo-keywords-1'."
  12126. (interactive "P")
  12127. (let ((case-fold-search nil)
  12128. (kwd-re
  12129. (cond ((null arg) org-not-done-regexp)
  12130. ((equal arg '(4))
  12131. (let ((kwd
  12132. (completing-read "Keyword (or KWD1|KWD2|...): "
  12133. (mapcar #'list org-todo-keywords-1))))
  12134. (concat "\\("
  12135. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12136. "\\)\\>")))
  12137. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12138. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12139. org-todo-keywords-1)))
  12140. (t (user-error "Invalid prefix argument: %s" arg)))))
  12141. (message "%d TODO entries found"
  12142. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12143. (defun org-deadline (arg &optional time)
  12144. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12145. With one universal prefix argument, remove any deadline from the item.
  12146. With two universal prefix arguments, prompt for a warning delay.
  12147. With argument TIME, set the deadline at the corresponding date. TIME
  12148. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12149. (interactive "P")
  12150. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12151. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12152. 'region-start-level 'region))
  12153. org-loop-over-headlines-in-active-region)
  12154. (org-map-entries
  12155. `(org-deadline ',arg ,time)
  12156. org-loop-over-headlines-in-active-region
  12157. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12158. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12159. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12160. (repeater (and old-date
  12161. (string-match
  12162. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12163. old-date)
  12164. (match-string 1 old-date))))
  12165. (cond
  12166. ((equal arg '(4))
  12167. (when (and old-date org-log-redeadline)
  12168. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12169. (org-remove-timestamp-with-keyword org-deadline-string)
  12170. (message "Item no longer has a deadline."))
  12171. ((equal arg '(16))
  12172. (save-excursion
  12173. (org-back-to-heading t)
  12174. (if (re-search-forward
  12175. org-deadline-time-regexp
  12176. (save-excursion (outline-next-heading) (point)) t)
  12177. (let* ((rpl0 (match-string 1))
  12178. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12179. (replace-match
  12180. (concat org-deadline-string
  12181. " <" rpl
  12182. (format " -%dd"
  12183. (abs
  12184. (- (time-to-days
  12185. (save-match-data
  12186. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12187. (time-to-days old-date-time))))
  12188. ">") t t))
  12189. (user-error "No deadline information to update"))))
  12190. (t
  12191. (org-add-planning-info 'deadline time 'closed)
  12192. (when (and old-date
  12193. org-log-redeadline
  12194. (not (equal old-date org-last-inserted-timestamp)))
  12195. (org-add-log-setup
  12196. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12197. (when repeater
  12198. (save-excursion
  12199. (org-back-to-heading t)
  12200. (when (re-search-forward (concat org-deadline-string " "
  12201. org-last-inserted-timestamp)
  12202. (save-excursion
  12203. (outline-next-heading) (point)) t)
  12204. (goto-char (1- (match-end 0)))
  12205. (insert " " repeater)
  12206. (setq org-last-inserted-timestamp
  12207. (concat (substring org-last-inserted-timestamp 0 -1)
  12208. " " repeater
  12209. (substring org-last-inserted-timestamp -1))))))
  12210. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12211. (defun org-schedule (arg &optional time)
  12212. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12213. With one universal prefix argument, remove any scheduling date from the item.
  12214. With two universal prefix arguments, prompt for a delay cookie.
  12215. With argument TIME, scheduled at the corresponding date. TIME can
  12216. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12217. (interactive "P")
  12218. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12219. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12220. 'region-start-level 'region))
  12221. org-loop-over-headlines-in-active-region)
  12222. (org-map-entries
  12223. `(org-schedule ',arg ,time)
  12224. org-loop-over-headlines-in-active-region
  12225. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12226. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12227. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12228. (repeater (and old-date
  12229. (string-match
  12230. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12231. old-date)
  12232. (match-string 1 old-date))))
  12233. (cond
  12234. ((equal arg '(4))
  12235. (progn
  12236. (when (and old-date org-log-reschedule)
  12237. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12238. (org-remove-timestamp-with-keyword org-scheduled-string)
  12239. (message "Item is no longer scheduled.")))
  12240. ((equal arg '(16))
  12241. (save-excursion
  12242. (org-back-to-heading t)
  12243. (if (re-search-forward
  12244. org-scheduled-time-regexp
  12245. (save-excursion (outline-next-heading) (point)) t)
  12246. (let* ((rpl0 (match-string 1))
  12247. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12248. (replace-match
  12249. (concat org-scheduled-string
  12250. " <" rpl
  12251. (format " -%dd"
  12252. (abs
  12253. (- (time-to-days
  12254. (save-match-data
  12255. (org-read-date nil t nil "Delay until" old-date-time)))
  12256. (time-to-days old-date-time))))
  12257. ">") t t))
  12258. (user-error "No scheduled information to update"))))
  12259. (t
  12260. (org-add-planning-info 'scheduled time 'closed)
  12261. (when (and old-date
  12262. org-log-reschedule
  12263. (not (equal old-date org-last-inserted-timestamp)))
  12264. (org-add-log-setup
  12265. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12266. (when repeater
  12267. (save-excursion
  12268. (org-back-to-heading t)
  12269. (when (re-search-forward (concat org-scheduled-string " "
  12270. org-last-inserted-timestamp)
  12271. (save-excursion
  12272. (outline-next-heading) (point)) t)
  12273. (goto-char (1- (match-end 0)))
  12274. (insert " " repeater)
  12275. (setq org-last-inserted-timestamp
  12276. (concat (substring org-last-inserted-timestamp 0 -1)
  12277. " " repeater
  12278. (substring org-last-inserted-timestamp -1))))))
  12279. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12280. (defun org-get-scheduled-time (pom &optional inherit)
  12281. "Get the scheduled time as a time tuple, of a format suitable
  12282. for calling org-schedule with, or if there is no scheduling,
  12283. returns nil."
  12284. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12285. (when time
  12286. (apply 'encode-time (org-parse-time-string time)))))
  12287. (defun org-get-deadline-time (pom &optional inherit)
  12288. "Get the deadline as a time tuple, of a format suitable for
  12289. calling org-deadline with, or if there is no scheduling, returns
  12290. nil."
  12291. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12292. (when time
  12293. (apply 'encode-time (org-parse-time-string time)))))
  12294. (defun org-remove-timestamp-with-keyword (keyword)
  12295. "Remove all time stamps with KEYWORD in the current entry."
  12296. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12297. beg)
  12298. (save-excursion
  12299. (org-back-to-heading t)
  12300. (setq beg (point))
  12301. (outline-next-heading)
  12302. (while (re-search-backward re beg t)
  12303. (replace-match "")
  12304. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12305. (equal (char-before) ?\ ))
  12306. (backward-delete-char 1)
  12307. (when (string-match "^[ \t]*$" (buffer-substring
  12308. (point-at-bol) (point-at-eol)))
  12309. (delete-region (point-at-bol)
  12310. (min (point-max) (1+ (point-at-eol))))))))))
  12311. (defvar org-time-was-given) ; dynamically scoped parameter
  12312. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12313. (defun org-at-planning-p ()
  12314. "Non-nil when point is on a planning info line."
  12315. ;; This is as accurate and faster than `org-element-at-point' since
  12316. ;; planning info location is fixed in the section.
  12317. (org-with-wide-buffer
  12318. (beginning-of-line)
  12319. (and (looking-at-p org-planning-line-re)
  12320. (eq (point)
  12321. (ignore-errors
  12322. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12323. (org-back-to-heading t)
  12324. (org-with-limited-levels (org-back-to-heading t)))
  12325. (line-beginning-position 2))))))
  12326. (defun org-add-planning-info (what &optional time &rest remove)
  12327. "Insert new timestamp with keyword in the planning line.
  12328. WHAT indicates what kind of time stamp to add. It is a symbol
  12329. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12330. the time to use. If none is given, the user is prompted for
  12331. a date. REMOVE indicates what kind of entries to remove. An old
  12332. WHAT entry will also be removed."
  12333. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12334. (catch 'exit
  12335. (when (and (memq what '(scheduled deadline))
  12336. (or (not time)
  12337. (and (stringp time)
  12338. (string-match "^[-+]+[0-9]" time))))
  12339. ;; Try to get a default date/time from existing timestamp
  12340. (save-excursion
  12341. (org-back-to-heading t)
  12342. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12343. (when (re-search-forward (if (eq what 'scheduled)
  12344. org-scheduled-time-regexp
  12345. org-deadline-time-regexp)
  12346. end t)
  12347. (setq ts (match-string 1)
  12348. default-time (apply 'encode-time (org-parse-time-string ts))
  12349. default-input (and ts (org-get-compact-tod ts)))))))
  12350. (when what
  12351. (setq time
  12352. (if (stringp time)
  12353. ;; This is a string (relative or absolute), set
  12354. ;; proper date.
  12355. (apply #'encode-time
  12356. (org-read-date-analyze
  12357. time default-time (decode-time default-time)))
  12358. ;; If necessary, get the time from the user
  12359. (or time (org-read-date nil 'to-time nil nil
  12360. default-time default-input)))))
  12361. (org-with-wide-buffer
  12362. (org-back-to-heading t)
  12363. (forward-line)
  12364. (unless (bolp) (insert "\n"))
  12365. (cond ((looking-at-p org-planning-line-re)
  12366. ;; Move to current indentation.
  12367. (skip-chars-forward " \t")
  12368. ;; Check if we have to remove something.
  12369. (dolist (type (if what (cons what remove) remove))
  12370. (save-excursion
  12371. (when (re-search-forward
  12372. (cl-case type
  12373. (closed org-closed-time-regexp)
  12374. (deadline org-deadline-time-regexp)
  12375. (scheduled org-scheduled-time-regexp)
  12376. (otherwise
  12377. (error "Invalid planning type: %s" type)))
  12378. (line-end-position) t)
  12379. ;; Delete until next keyword or end of line.
  12380. (delete-region
  12381. (match-beginning 0)
  12382. (if (re-search-forward org-keyword-time-not-clock-regexp
  12383. (line-end-position)
  12384. t)
  12385. (match-beginning 0)
  12386. (line-end-position))))))
  12387. ;; If there is nothing more to add and no more keyword
  12388. ;; is left, remove the line completely.
  12389. (if (and (looking-at-p "[ \t]*$") (not what))
  12390. (delete-region (line-beginning-position)
  12391. (line-beginning-position 2))
  12392. ;; If we removed last keyword, do not leave trailing
  12393. ;; white space at the end of line.
  12394. (let ((p (point)))
  12395. (save-excursion
  12396. (end-of-line)
  12397. (unless (= (skip-chars-backward " \t" p) 0)
  12398. (delete-region (point) (line-end-position)))))))
  12399. ((not what) (throw 'exit nil)) ; Nothing to do.
  12400. (t (insert-before-markers "\n")
  12401. (backward-char 1)
  12402. (when org-adapt-indentation
  12403. (indent-to-column (1+ (org-outline-level))))))
  12404. (when what
  12405. ;; Insert planning keyword.
  12406. (insert (cl-case what
  12407. (closed org-closed-string)
  12408. (deadline org-deadline-string)
  12409. (scheduled org-scheduled-string)
  12410. (otherwise (error "Invalid planning type: %s" what)))
  12411. " ")
  12412. ;; Insert associated timestamp.
  12413. (let ((ts (org-insert-time-stamp
  12414. time
  12415. (or org-time-was-given
  12416. (and (eq what 'closed) org-log-done-with-time))
  12417. (eq what 'closed)
  12418. nil nil (list org-end-time-was-given))))
  12419. (unless (eolp) (insert " "))
  12420. ts))))))
  12421. (defvar org-log-note-marker (make-marker)
  12422. "Marker pointing at the entry where the note is to be inserted.")
  12423. (defvar org-log-note-purpose nil)
  12424. (defvar org-log-note-state nil)
  12425. (defvar org-log-note-previous-state nil)
  12426. (defvar org-log-note-extra nil)
  12427. (defvar org-log-note-window-configuration nil)
  12428. (defvar org-log-note-return-to (make-marker))
  12429. (defvar org-log-note-effective-time nil
  12430. "Remembered current time so that dynamically scoped
  12431. `org-extend-today-until' affects timestamps in state change log")
  12432. (defvar org-log-post-message nil
  12433. "Message to be displayed after a log note has been stored.
  12434. The auto-repeater uses this.")
  12435. (defun org-add-note ()
  12436. "Add a note to the current entry.
  12437. This is done in the same way as adding a state change note."
  12438. (interactive)
  12439. (org-add-log-setup 'note))
  12440. (defun org-log-beginning (&optional create)
  12441. "Return expected start of log notes in current entry.
  12442. When optional argument CREATE is non-nil, the function creates
  12443. a drawer to store notes, if necessary. Returned position ignores
  12444. narrowing."
  12445. (org-with-wide-buffer
  12446. (let ((drawer (org-log-into-drawer)))
  12447. (cond
  12448. (drawer
  12449. (org-end-of-meta-data)
  12450. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12451. (end (if (org-at-heading-p) (point)
  12452. (save-excursion (outline-next-heading) (point))))
  12453. (case-fold-search t))
  12454. (catch 'exit
  12455. ;; Try to find existing drawer.
  12456. (while (re-search-forward regexp end t)
  12457. (let ((element (org-element-at-point)))
  12458. (when (eq (org-element-type element) 'drawer)
  12459. (let ((cend (org-element-property :contents-end element)))
  12460. (when (and (not org-log-states-order-reversed) cend)
  12461. (goto-char cend)))
  12462. (throw 'exit nil))))
  12463. ;; No drawer found. Create one, if permitted.
  12464. (when create
  12465. (unless (bolp) (insert "\n"))
  12466. (let ((beg (point)))
  12467. (insert ":" drawer ":\n:END:\n")
  12468. (org-indent-region beg (point)))
  12469. (end-of-line -1)))))
  12470. (t
  12471. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12472. (skip-chars-forward " \t\n")
  12473. (beginning-of-line)
  12474. (unless org-log-states-order-reversed
  12475. (org-skip-over-state-notes)
  12476. (skip-chars-backward " \t\n")
  12477. (forward-line)))))
  12478. (if (bolp) (point) (line-beginning-position 2))))
  12479. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12480. "Set up the post command hook to take a note.
  12481. If this is about to TODO state change, the new state is expected in STATE.
  12482. HOW is an indicator what kind of note should be created.
  12483. EXTRA is additional text that will be inserted into the notes buffer."
  12484. (move-marker org-log-note-marker (point))
  12485. (setq org-log-note-purpose purpose
  12486. org-log-note-state state
  12487. org-log-note-previous-state prev-state
  12488. org-log-note-how how
  12489. org-log-note-extra extra
  12490. org-log-note-effective-time (org-current-effective-time))
  12491. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12492. (defun org-skip-over-state-notes ()
  12493. "Skip past the list of State notes in an entry."
  12494. (when (ignore-errors (goto-char (org-in-item-p)))
  12495. (let* ((struct (org-list-struct))
  12496. (prevs (org-list-prevs-alist struct))
  12497. (regexp
  12498. (concat "[ \t]*- +"
  12499. (replace-regexp-in-string
  12500. " +" " +"
  12501. (org-replace-escapes
  12502. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12503. `(("%d" . ,org-ts-regexp-inactive)
  12504. ("%D" . ,org-ts-regexp)
  12505. ("%s" . "\"\\S-+\"")
  12506. ("%S" . "\"\\S-+\"")
  12507. ("%t" . ,org-ts-regexp-inactive)
  12508. ("%T" . ,org-ts-regexp)
  12509. ("%u" . ".*?")
  12510. ("%U" . ".*?")))))))
  12511. (while (looking-at-p regexp)
  12512. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12513. (org-list-get-item-end (point) struct)))))))
  12514. (defun org-add-log-note (&optional _purpose)
  12515. "Pop up a window for taking a note, and add this note later."
  12516. (remove-hook 'post-command-hook 'org-add-log-note)
  12517. (setq org-log-note-window-configuration (current-window-configuration))
  12518. (delete-other-windows)
  12519. (move-marker org-log-note-return-to (point))
  12520. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12521. (goto-char org-log-note-marker)
  12522. (org-switch-to-buffer-other-window "*Org Note*")
  12523. (erase-buffer)
  12524. (if (memq org-log-note-how '(time state))
  12525. (let (current-prefix-arg) (org-store-log-note))
  12526. (let ((org-inhibit-startup t)) (org-mode))
  12527. (insert (format "# Insert note for %s.
  12528. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12529. (cond
  12530. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12531. ((eq org-log-note-purpose 'done) "closed todo item")
  12532. ((eq org-log-note-purpose 'state)
  12533. (format "state change from \"%s\" to \"%s\""
  12534. (or org-log-note-previous-state "")
  12535. (or org-log-note-state "")))
  12536. ((eq org-log-note-purpose 'reschedule)
  12537. "rescheduling")
  12538. ((eq org-log-note-purpose 'delschedule)
  12539. "no longer scheduled")
  12540. ((eq org-log-note-purpose 'redeadline)
  12541. "changing deadline")
  12542. ((eq org-log-note-purpose 'deldeadline)
  12543. "removing deadline")
  12544. ((eq org-log-note-purpose 'refile)
  12545. "refiling")
  12546. ((eq org-log-note-purpose 'note)
  12547. "this entry")
  12548. (t (error "This should not happen")))))
  12549. (when org-log-note-extra (insert org-log-note-extra))
  12550. (setq-local org-finish-function 'org-store-log-note)
  12551. (run-hooks 'org-log-buffer-setup-hook)))
  12552. (defvar org-note-abort nil) ; dynamically scoped
  12553. (defun org-store-log-note ()
  12554. "Finish taking a log note, and insert it to where it belongs."
  12555. (let ((txt (prog1 (buffer-string)
  12556. (kill-buffer)))
  12557. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12558. lines)
  12559. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12560. (setq txt (replace-match "" t t txt)))
  12561. (when (string-match "\\s-+\\'" txt)
  12562. (setq txt (replace-match "" t t txt)))
  12563. (setq lines (org-split-string txt "\n"))
  12564. (when (org-string-nw-p note)
  12565. (setq note
  12566. (org-replace-escapes
  12567. note
  12568. (list (cons "%u" (user-login-name))
  12569. (cons "%U" user-full-name)
  12570. (cons "%t" (format-time-string
  12571. (org-time-stamp-format 'long 'inactive)
  12572. org-log-note-effective-time))
  12573. (cons "%T" (format-time-string
  12574. (org-time-stamp-format 'long nil)
  12575. org-log-note-effective-time))
  12576. (cons "%d" (format-time-string
  12577. (org-time-stamp-format nil 'inactive)
  12578. org-log-note-effective-time))
  12579. (cons "%D" (format-time-string
  12580. (org-time-stamp-format nil nil)
  12581. org-log-note-effective-time))
  12582. (cons "%s" (cond
  12583. ((not org-log-note-state) "")
  12584. ((string-match-p org-ts-regexp
  12585. org-log-note-state)
  12586. (format "\"[%s]\""
  12587. (substring org-log-note-state 1 -1)))
  12588. (t (format "\"%s\"" org-log-note-state))))
  12589. (cons "%S"
  12590. (cond
  12591. ((not org-log-note-previous-state) "")
  12592. ((string-match-p org-ts-regexp
  12593. org-log-note-previous-state)
  12594. (format "\"[%s]\""
  12595. (substring
  12596. org-log-note-previous-state 1 -1)))
  12597. (t (format "\"%s\""
  12598. org-log-note-previous-state)))))))
  12599. (when lines (setq note (concat note " \\\\")))
  12600. (push note lines))
  12601. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12602. (with-current-buffer (marker-buffer org-log-note-marker)
  12603. (org-with-wide-buffer
  12604. ;; Find location for the new note.
  12605. (goto-char org-log-note-marker)
  12606. (set-marker org-log-note-marker nil)
  12607. (goto-char (org-log-beginning t))
  12608. ;; Make sure point is at the beginning of an empty line.
  12609. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12610. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12611. ;; In an existing list, add a new item at the top level.
  12612. ;; Otherwise, indent line like a regular one.
  12613. (let ((itemp (org-in-item-p)))
  12614. (if itemp
  12615. (indent-line-to
  12616. (let ((struct (save-excursion
  12617. (goto-char itemp) (org-list-struct))))
  12618. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12619. (org-indent-line)))
  12620. (insert (org-list-bullet-string "-") (pop lines))
  12621. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12622. (dolist (line lines)
  12623. (insert "\n")
  12624. (indent-line-to ind)
  12625. (insert line)))
  12626. (message "Note stored")
  12627. (org-back-to-heading t)
  12628. (org-cycle-hide-drawers 'children))
  12629. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12630. ;; from within `org-add-log-note' because `buffer-undo-list'
  12631. ;; is then modified outside of `org-with-remote-undo'.
  12632. (when (eq this-command 'org-agenda-todo)
  12633. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12634. ;; Don't add undo information when called from `org-agenda-todo'.
  12635. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12636. (set-window-configuration org-log-note-window-configuration)
  12637. (with-current-buffer (marker-buffer org-log-note-return-to)
  12638. (goto-char org-log-note-return-to))
  12639. (move-marker org-log-note-return-to nil)
  12640. (when org-log-post-message (message "%s" org-log-post-message))))
  12641. (defun org-remove-empty-drawer-at (pos)
  12642. "Remove an empty drawer at position POS.
  12643. POS may also be a marker."
  12644. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12645. (org-with-wide-buffer
  12646. (goto-char pos)
  12647. (let ((drawer (org-element-at-point)))
  12648. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12649. (not (org-element-property :contents-begin drawer)))
  12650. (delete-region (org-element-property :begin drawer)
  12651. (progn (goto-char (org-element-property :end drawer))
  12652. (skip-chars-backward " \r\t\n")
  12653. (forward-line)
  12654. (point))))))))
  12655. (defvar org-ts-type nil)
  12656. (defun org-sparse-tree (&optional arg type)
  12657. "Create a sparse tree, prompt for the details.
  12658. This command can create sparse trees. You first need to select the type
  12659. of match used to create the tree:
  12660. t Show all TODO entries.
  12661. T Show entries with a specific TODO keyword.
  12662. m Show entries selected by a tags/property match.
  12663. p Enter a property name and its value (both with completion on existing
  12664. names/values) and show entries with that property.
  12665. r Show entries matching a regular expression (`/' can be used as well).
  12666. b Show deadlines and scheduled items before a date.
  12667. a Show deadlines and scheduled items after a date.
  12668. d Show deadlines due within `org-deadline-warning-days'.
  12669. D Show deadlines and scheduled items between a date range."
  12670. (interactive "P")
  12671. (setq type (or type org-sparse-tree-default-date-type))
  12672. (setq org-ts-type type)
  12673. (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12674. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12675. \[c]ycle through date types: %s"
  12676. (cl-case type
  12677. (all "all timestamps")
  12678. (scheduled "only scheduled")
  12679. (deadline "only deadline")
  12680. (active "only active timestamps")
  12681. (inactive "only inactive timestamps")
  12682. (closed "with a closed time-stamp")
  12683. (otherwise "scheduled/deadline")))
  12684. (let ((answer (read-char-exclusive)))
  12685. (cl-case answer
  12686. (?c
  12687. (org-sparse-tree
  12688. arg
  12689. (cadr
  12690. (memq type '(nil all scheduled deadline active inactive closed)))))
  12691. (?d (call-interactively 'org-check-deadlines))
  12692. (?b (call-interactively 'org-check-before-date))
  12693. (?a (call-interactively 'org-check-after-date))
  12694. (?D (call-interactively 'org-check-dates-range))
  12695. (?t (call-interactively 'org-show-todo-tree))
  12696. (?T (org-show-todo-tree '(4)))
  12697. (?m (call-interactively 'org-match-sparse-tree))
  12698. ((?p ?P)
  12699. (let* ((kwd (completing-read
  12700. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12701. (value (completing-read
  12702. "Value: " (mapcar #'list (org-property-values kwd)))))
  12703. (unless (string-match "\\`{.*}\\'" value)
  12704. (setq value (concat "\"" value "\"")))
  12705. (org-match-sparse-tree arg (concat kwd "=" value))))
  12706. ((?r ?R ?/) (call-interactively 'org-occur))
  12707. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12708. (defvar-local org-occur-highlights nil
  12709. "List of overlays used for occur matches.")
  12710. (defvar-local org-occur-parameters nil
  12711. "Parameters of the active org-occur calls.
  12712. This is a list, each call to org-occur pushes as cons cell,
  12713. containing the regular expression and the callback, onto the list.
  12714. The list can contain several entries if `org-occur' has been called
  12715. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12716. will only contain one set of parameters. When the highlights are
  12717. removed (for example with `C-c C-c', or with the next edit (depending
  12718. on `org-remove-highlights-with-change'), this variable is emptied
  12719. as well.")
  12720. (defun org-occur (regexp &optional keep-previous callback)
  12721. "Make a compact tree which shows all matches of REGEXP.
  12722. The tree will show the lines where the regexp matches, and any other context
  12723. defined in `org-show-context-detail', which see.
  12724. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12725. done by a previous call to `org-occur' will be kept, to allow stacking of
  12726. calls to this command.
  12727. Optional argument CALLBACK can be a function of no argument. In this case,
  12728. it is called with point at the end of the match, match data being set
  12729. accordingly. Current match is shown only if the return value is non-nil.
  12730. The function must neither move point nor alter narrowing."
  12731. (interactive "sRegexp: \nP")
  12732. (when (equal regexp "")
  12733. (user-error "Regexp cannot be empty"))
  12734. (unless keep-previous
  12735. (org-remove-occur-highlights nil nil t))
  12736. (push (cons regexp callback) org-occur-parameters)
  12737. (let ((cnt 0))
  12738. (save-excursion
  12739. (goto-char (point-min))
  12740. (when (or (not keep-previous) ; do not want to keep
  12741. (not org-occur-highlights)) ; no previous matches
  12742. ;; hide everything
  12743. (org-overview))
  12744. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12745. (isearch-no-upper-case-p regexp t)
  12746. org-occur-case-fold-search)))
  12747. (while (re-search-forward regexp nil t)
  12748. (when (or (not callback)
  12749. (save-match-data (funcall callback)))
  12750. (setq cnt (1+ cnt))
  12751. (when org-highlight-sparse-tree-matches
  12752. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12753. (org-show-context 'occur-tree)))))
  12754. (when org-remove-highlights-with-change
  12755. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12756. nil 'local))
  12757. (unless org-sparse-tree-open-archived-trees
  12758. (org-hide-archived-subtrees (point-min) (point-max)))
  12759. (run-hooks 'org-occur-hook)
  12760. (when (called-interactively-p 'interactive)
  12761. (message "%d match(es) for regexp %s" cnt regexp))
  12762. cnt))
  12763. (defun org-occur-next-match (&optional n _reset)
  12764. "Function for `next-error-function' to find sparse tree matches.
  12765. N is the number of matches to move, when negative move backwards.
  12766. This function always goes back to the starting point when no
  12767. match is found."
  12768. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12769. (search-func (if (< n 0)
  12770. 'previous-single-char-property-change
  12771. 'next-single-char-property-change))
  12772. (n (abs n))
  12773. (pos (point))
  12774. p1)
  12775. (catch 'exit
  12776. (while (setq p1 (funcall search-func (point) 'org-type))
  12777. (when (equal p1 limit)
  12778. (goto-char pos)
  12779. (user-error "No more matches"))
  12780. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12781. (setq n (1- n))
  12782. (when (= n 0)
  12783. (goto-char p1)
  12784. (throw 'exit (point))))
  12785. (goto-char p1))
  12786. (goto-char p1)
  12787. (user-error "No more matches"))))
  12788. (defun org-show-context (&optional key)
  12789. "Make sure point and context are visible.
  12790. Optional argument KEY, when non-nil, is a symbol. See
  12791. `org-show-context-detail' for allowed values and how much is to
  12792. be shown."
  12793. (org-show-set-visibility
  12794. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12795. ((cdr (assq key org-show-context-detail)))
  12796. (t (cdr (assq 'default org-show-context-detail))))))
  12797. (defun org-show-set-visibility (detail)
  12798. "Set visibility around point according to DETAIL.
  12799. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12800. `tree', `canonical' or t. See `org-show-context-detail' for more
  12801. information."
  12802. ;; Show current heading and possibly its entry, following headline
  12803. ;; or all children.
  12804. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12805. (org-flag-heading nil)
  12806. (org-show-entry)
  12807. ;; If point is hidden within a drawer or a block, make sure to
  12808. ;; expose it.
  12809. (dolist (o (overlays-at (point)))
  12810. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12811. (delete-overlay o)))
  12812. (unless (org-before-first-heading-p)
  12813. (org-with-limited-levels
  12814. (cl-case detail
  12815. ((tree canonical t) (org-show-children))
  12816. ((nil minimal ancestors))
  12817. (t (save-excursion
  12818. (outline-next-heading)
  12819. (org-flag-heading nil)))))))
  12820. ;; Show all siblings.
  12821. (when (eq detail 'lineage) (org-show-siblings))
  12822. ;; Show ancestors, possibly with their children.
  12823. (when (memq detail '(ancestors lineage tree canonical t))
  12824. (save-excursion
  12825. (while (org-up-heading-safe)
  12826. (org-flag-heading nil)
  12827. (when (memq detail '(canonical t)) (org-show-entry))
  12828. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12829. (defvar org-reveal-start-hook nil
  12830. "Hook run before revealing a location.")
  12831. (defun org-reveal (&optional siblings)
  12832. "Show current entry, hierarchy above it, and the following headline.
  12833. This can be used to show a consistent set of context around
  12834. locations exposed with `org-show-context'.
  12835. With optional argument SIBLINGS, on each level of the hierarchy all
  12836. siblings are shown. This repairs the tree structure to what it would
  12837. look like when opened with hierarchical calls to `org-cycle'.
  12838. With double optional argument \\[universal-argument] \\[universal-argument], \
  12839. go to the parent and show the
  12840. entire tree."
  12841. (interactive "P")
  12842. (run-hooks 'org-reveal-start-hook)
  12843. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12844. ((equal siblings '(16))
  12845. (save-excursion
  12846. (when (org-up-heading-safe)
  12847. (org-show-subtree)
  12848. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12849. (t (org-show-set-visibility 'lineage))))
  12850. (defun org-highlight-new-match (beg end)
  12851. "Highlight from BEG to END and mark the highlight is an occur headline."
  12852. (let ((ov (make-overlay beg end)))
  12853. (overlay-put ov 'face 'secondary-selection)
  12854. (overlay-put ov 'org-type 'org-occur)
  12855. (push ov org-occur-highlights)))
  12856. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12857. "Remove the occur highlights from the buffer.
  12858. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12859. from the `before-change-functions' in the current buffer."
  12860. (interactive)
  12861. (unless org-inhibit-highlight-removal
  12862. (mapc #'delete-overlay org-occur-highlights)
  12863. (setq org-occur-highlights nil)
  12864. (setq org-occur-parameters nil)
  12865. (unless noremove
  12866. (remove-hook 'before-change-functions
  12867. 'org-remove-occur-highlights 'local))))
  12868. ;;;; Priorities
  12869. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12870. "Regular expression matching the priority indicator.")
  12871. (defvar org-remove-priority-next-time nil)
  12872. (defun org-priority-up ()
  12873. "Increase the priority of the current item."
  12874. (interactive)
  12875. (org-priority 'up))
  12876. (defun org-priority-down ()
  12877. "Decrease the priority of the current item."
  12878. (interactive)
  12879. (org-priority 'down))
  12880. (defun org-priority (&optional action _show)
  12881. "Change the priority of an item.
  12882. ACTION can be `set', `up', `down', or a character."
  12883. (interactive "P")
  12884. (if (equal action '(4))
  12885. (org-show-priority)
  12886. (unless org-enable-priority-commands
  12887. (user-error "Priority commands are disabled"))
  12888. (setq action (or action 'set))
  12889. (let (current new news have remove)
  12890. (save-excursion
  12891. (org-back-to-heading t)
  12892. (when (looking-at org-priority-regexp)
  12893. (setq current (string-to-char (match-string 2))
  12894. have t))
  12895. (cond
  12896. ((eq action 'remove)
  12897. (setq remove t new ?\ ))
  12898. ((or (eq action 'set)
  12899. (integerp action))
  12900. (if (not (eq action 'set))
  12901. (setq new action)
  12902. (message "Priority %c-%c, SPC to remove: "
  12903. org-highest-priority org-lowest-priority)
  12904. (save-match-data
  12905. (setq new (read-char-exclusive))))
  12906. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12907. (= (upcase org-lowest-priority) org-lowest-priority))
  12908. (setq new (upcase new)))
  12909. (cond ((equal new ?\ ) (setq remove t))
  12910. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12911. (user-error "Priority must be between `%c' and `%c'"
  12912. org-highest-priority org-lowest-priority))))
  12913. ((eq action 'up)
  12914. (setq new (if have
  12915. (1- current) ; normal cycling
  12916. ;; last priority was empty
  12917. (if (eq last-command this-command)
  12918. org-lowest-priority ; wrap around empty to lowest
  12919. ;; default
  12920. (if org-priority-start-cycle-with-default
  12921. org-default-priority
  12922. (1- org-default-priority))))))
  12923. ((eq action 'down)
  12924. (setq new (if have
  12925. (1+ current) ; normal cycling
  12926. ;; last priority was empty
  12927. (if (eq last-command this-command)
  12928. org-highest-priority ; wrap around empty to highest
  12929. ;; default
  12930. (if org-priority-start-cycle-with-default
  12931. org-default-priority
  12932. (1+ org-default-priority))))))
  12933. (t (user-error "Invalid action")))
  12934. (when (or (< (upcase new) org-highest-priority)
  12935. (> (upcase new) org-lowest-priority))
  12936. (if (and (memq action '(up down))
  12937. (not have) (not (eq last-command this-command)))
  12938. ;; `new' is from default priority
  12939. (error
  12940. "The default can not be set, see `org-default-priority' why")
  12941. ;; normal cycling: `new' is beyond highest/lowest priority
  12942. ;; and is wrapped around to the empty priority
  12943. (setq remove t)))
  12944. (setq news (format "%c" new))
  12945. (if have
  12946. (if remove
  12947. (replace-match "" t t nil 1)
  12948. (replace-match news t t nil 2))
  12949. (if remove
  12950. (user-error "No priority cookie found in line")
  12951. (let ((case-fold-search nil))
  12952. (looking-at org-todo-line-regexp))
  12953. (if (match-end 2)
  12954. (progn
  12955. (goto-char (match-end 2))
  12956. (insert " [#" news "]"))
  12957. (goto-char (match-beginning 3))
  12958. (insert "[#" news "] "))))
  12959. (org-set-tags nil 'align))
  12960. (if remove
  12961. (message "Priority removed")
  12962. (message "Priority of current item set to %s" news)))))
  12963. (defun org-show-priority ()
  12964. "Show the priority of the current item.
  12965. This priority is composed of the main priority given with the [#A] cookies,
  12966. and by additional input from the age of a schedules or deadline entry."
  12967. (interactive)
  12968. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12969. (org-get-at-bol 'priority)
  12970. (save-excursion
  12971. (save-match-data
  12972. (beginning-of-line)
  12973. (and (looking-at org-heading-regexp)
  12974. (org-get-priority (match-string 0))))))))
  12975. (message "Priority is %d" (if pri pri -1000))))
  12976. (defun org-get-priority (s)
  12977. "Find priority cookie and return priority."
  12978. (save-match-data
  12979. (if (functionp org-get-priority-function)
  12980. (funcall org-get-priority-function)
  12981. (if (not (string-match org-priority-regexp s))
  12982. (* 1000 (- org-lowest-priority org-default-priority))
  12983. (* 1000 (- org-lowest-priority
  12984. (string-to-char (match-string 2 s))))))))
  12985. ;;;; Tags
  12986. (defvar org-agenda-archives-mode)
  12987. (defvar org-map-continue-from nil
  12988. "Position from where mapping should continue.
  12989. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12990. (defvar org-scanner-tags nil
  12991. "The current tag list while the tags scanner is running.")
  12992. (defvar org-trust-scanner-tags nil
  12993. "Should `org-get-tags-at' use the tags for the scanner.
  12994. This is for internal dynamical scoping only.
  12995. When this is non-nil, the function `org-get-tags-at' will return the value
  12996. of `org-scanner-tags' instead of building the list by itself. This
  12997. can lead to large speed-ups when the tags scanner is used in a file with
  12998. many entries, and when the list of tags is retrieved, for example to
  12999. obtain a list of properties. Building the tags list for each entry in such
  13000. a file becomes an N^2 operation - but with this variable set, it scales
  13001. as N.")
  13002. (defvar org--matcher-tags-todo-only nil)
  13003. (defun org-scan-tags (action matcher todo-only &optional start-level)
  13004. "Scan headline tags with inheritance and produce output ACTION.
  13005. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  13006. or `agenda' to produce an entry list for an agenda view. It can also be
  13007. a Lisp form or a function that should be called at each matched headline, in
  13008. this case the return value is a list of all return values from these calls.
  13009. MATCHER is a function accepting three arguments, returning
  13010. a non-nil value whenever a given set of tags qualifies a headline
  13011. for inclusion. See `org-make-tags-matcher' for more information.
  13012. As a special case, it can also be set to t (respectively nil) in
  13013. order to match all (respectively none) headline.
  13014. When TODO-ONLY is non-nil, only lines with a not-done TODO
  13015. keyword are included in the output.
  13016. START-LEVEL can be a string with asterisks, reducing the scope to
  13017. headlines matching this string."
  13018. (require 'org-agenda)
  13019. (let* ((re (concat "^"
  13020. (if start-level
  13021. ;; Get the correct level to match
  13022. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  13023. org-outline-regexp)
  13024. " *\\(\\<\\("
  13025. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  13026. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  13027. (props (list 'face 'default
  13028. 'done-face 'org-agenda-done
  13029. 'undone-face 'default
  13030. 'mouse-face 'highlight
  13031. 'org-not-done-regexp org-not-done-regexp
  13032. 'org-todo-regexp org-todo-regexp
  13033. 'org-complex-heading-regexp org-complex-heading-regexp
  13034. 'help-echo
  13035. (format "mouse-2 or RET jump to org file %s"
  13036. (abbreviate-file-name
  13037. (or (buffer-file-name (buffer-base-buffer))
  13038. (buffer-name (buffer-base-buffer)))))))
  13039. (org-map-continue-from nil)
  13040. lspos tags tags-list
  13041. (tags-alist (list (cons 0 org-file-tags)))
  13042. (llast 0) rtn rtn1 level category i txt
  13043. todo marker entry priority
  13044. ts-date ts-date-type ts-date-pair)
  13045. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  13046. (setq action (list 'lambda nil action)))
  13047. (save-excursion
  13048. (goto-char (point-min))
  13049. (when (eq action 'sparse-tree)
  13050. (org-overview)
  13051. (org-remove-occur-highlights))
  13052. (while (let (case-fold-search)
  13053. (re-search-forward re nil t))
  13054. (setq org-map-continue-from nil)
  13055. (catch :skip
  13056. (setq todo
  13057. ;; TODO: is the 1-2 difference a bug?
  13058. (when (match-end 1) (match-string-no-properties 2))
  13059. tags (when (match-end 4) (match-string-no-properties 4)))
  13060. (goto-char (setq lspos (match-beginning 0)))
  13061. (setq level (org-reduced-level (org-outline-level))
  13062. category (org-get-category))
  13063. (when (eq action 'agenda)
  13064. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13065. ts-date (car ts-date-pair)
  13066. ts-date-type (cdr ts-date-pair)))
  13067. (setq i llast llast level)
  13068. ;; remove tag lists from same and sublevels
  13069. (while (>= i level)
  13070. (when (setq entry (assoc i tags-alist))
  13071. (setq tags-alist (delete entry tags-alist)))
  13072. (setq i (1- i)))
  13073. ;; add the next tags
  13074. (when tags
  13075. (setq tags (org-split-string tags ":")
  13076. tags-alist
  13077. (cons (cons level tags) tags-alist)))
  13078. ;; compile tags for current headline
  13079. (setq tags-list
  13080. (if org-use-tag-inheritance
  13081. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13082. tags)
  13083. org-scanner-tags tags-list)
  13084. (when org-use-tag-inheritance
  13085. (setcdr (car tags-alist)
  13086. (mapcar (lambda (x)
  13087. (setq x (copy-sequence x))
  13088. (org-add-prop-inherited x))
  13089. (cdar tags-alist))))
  13090. (when (and tags org-use-tag-inheritance
  13091. (or (not (eq t org-use-tag-inheritance))
  13092. org-tags-exclude-from-inheritance))
  13093. ;; Selective inheritance, remove uninherited ones.
  13094. (setcdr (car tags-alist)
  13095. (org-remove-uninherited-tags (cdar tags-alist))))
  13096. (when (and
  13097. ;; eval matcher only when the todo condition is OK
  13098. (and (or (not todo-only) (member todo org-not-done-keywords))
  13099. (if (functionp matcher)
  13100. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13101. (funcall matcher todo tags-list level))
  13102. matcher))
  13103. ;; Call the skipper, but return t if it does not
  13104. ;; skip, so that the `and' form continues evaluating.
  13105. (progn
  13106. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13107. t)
  13108. ;; Check if timestamps are deselecting this entry
  13109. (or (not todo-only)
  13110. (and (member todo org-not-done-keywords)
  13111. (or (not org-agenda-tags-todo-honor-ignore-options)
  13112. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13113. ;; select this headline
  13114. (cond
  13115. ((eq action 'sparse-tree)
  13116. (and org-highlight-sparse-tree-matches
  13117. (org-get-heading) (match-end 0)
  13118. (org-highlight-new-match
  13119. (match-beginning 1) (match-end 1)))
  13120. (org-show-context 'tags-tree))
  13121. ((eq action 'agenda)
  13122. (setq txt (org-agenda-format-item
  13123. ""
  13124. (concat
  13125. (if (eq org-tags-match-list-sublevels 'indented)
  13126. (make-string (1- level) ?.) "")
  13127. (org-get-heading))
  13128. (make-string level ?\s)
  13129. category
  13130. tags-list)
  13131. priority (org-get-priority txt))
  13132. (goto-char lspos)
  13133. (setq marker (org-agenda-new-marker))
  13134. (org-add-props txt props
  13135. 'org-marker marker 'org-hd-marker marker 'org-category category
  13136. 'todo-state todo
  13137. 'ts-date ts-date
  13138. 'priority priority
  13139. 'type (concat "tagsmatch" ts-date-type))
  13140. (push txt rtn))
  13141. ((functionp action)
  13142. (setq org-map-continue-from nil)
  13143. (save-excursion
  13144. (setq rtn1 (funcall action))
  13145. (push rtn1 rtn)))
  13146. (t (user-error "Invalid action")))
  13147. ;; if we are to skip sublevels, jump to end of subtree
  13148. (unless org-tags-match-list-sublevels
  13149. (org-end-of-subtree t)
  13150. (backward-char 1))))
  13151. ;; Get the correct position from where to continue
  13152. (if org-map-continue-from
  13153. (goto-char org-map-continue-from)
  13154. (and (= (point) lspos) (end-of-line 1)))))
  13155. (when (and (eq action 'sparse-tree)
  13156. (not org-sparse-tree-open-archived-trees))
  13157. (org-hide-archived-subtrees (point-min) (point-max)))
  13158. (nreverse rtn)))
  13159. (defun org-remove-uninherited-tags (tags)
  13160. "Remove all tags that are not inherited from the list TAGS."
  13161. (cond
  13162. ((eq org-use-tag-inheritance t)
  13163. (if org-tags-exclude-from-inheritance
  13164. (org-delete-all org-tags-exclude-from-inheritance tags)
  13165. tags))
  13166. ((not org-use-tag-inheritance) nil)
  13167. ((stringp org-use-tag-inheritance)
  13168. (delq nil (mapcar
  13169. (lambda (x)
  13170. (if (and (string-match org-use-tag-inheritance x)
  13171. (not (member x org-tags-exclude-from-inheritance)))
  13172. x nil))
  13173. tags)))
  13174. ((listp org-use-tag-inheritance)
  13175. (delq nil (mapcar
  13176. (lambda (x)
  13177. (if (member x org-use-tag-inheritance) x nil))
  13178. tags)))))
  13179. (defun org-match-sparse-tree (&optional todo-only match)
  13180. "Create a sparse tree according to tags string MATCH.
  13181. MATCH can contain positive and negative selection of tags, like
  13182. \"+WORK+URGENT-WITHBOSS\".
  13183. If optional argument TODO-ONLY is non-nil, only select lines that are
  13184. also TODO lines."
  13185. (interactive "P")
  13186. (org-agenda-prepare-buffers (list (current-buffer)))
  13187. (let ((org--matcher-tags-todo-only todo-only))
  13188. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13189. org--matcher-tags-todo-only)))
  13190. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13191. (defvar org-cached-props nil)
  13192. (defun org-cached-entry-get (pom property)
  13193. (if (or (eq t org-use-property-inheritance)
  13194. (and (stringp org-use-property-inheritance)
  13195. (let ((case-fold-search t))
  13196. (string-match-p org-use-property-inheritance property)))
  13197. (and (listp org-use-property-inheritance)
  13198. (member-ignore-case property org-use-property-inheritance)))
  13199. ;; Caching is not possible, check it directly.
  13200. (org-entry-get pom property 'inherit)
  13201. ;; Get all properties, so we can do complicated checks easily.
  13202. (cdr (assoc-string property
  13203. (or org-cached-props
  13204. (setq org-cached-props (org-entry-properties pom)))
  13205. t))))
  13206. (defun org-global-tags-completion-table (&optional files)
  13207. "Return the list of all tags in all agenda buffer/files.
  13208. Optional FILES argument is a list of files which can be used
  13209. instead of the agenda files."
  13210. (save-excursion
  13211. (org-uniquify
  13212. (delq nil
  13213. (apply #'append
  13214. (mapcar
  13215. (lambda (file)
  13216. (set-buffer (find-file-noselect file))
  13217. (mapcar (lambda (x)
  13218. (and (stringp (car-safe x))
  13219. (list (car-safe x))))
  13220. (or org-current-tag-alist (org-get-buffer-tags))))
  13221. (if (car-safe files) files
  13222. (org-agenda-files))))))))
  13223. (defun org-make-tags-matcher (match)
  13224. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13225. Returns a cons of the selection string MATCH and a function
  13226. implementing the matcher.
  13227. The matcher is to be called at an Org entry, with point on the
  13228. headline, and returns non-nil if the entry matches the selection
  13229. string MATCH. It must be called with three arguments: the TODO
  13230. keyword at the entry (or nil if none), the list of all tags at
  13231. the entry including inherited ones and the reduced level of the
  13232. headline. Additionally, the category of the entry, if any, must
  13233. be specified as the text property `org-category' on the headline.
  13234. This function sets the variable `org--matcher-tags-todo-only' to
  13235. a non-nil value if the matcher restricts matching to TODO
  13236. entries, otherwise it is not touched.
  13237. See also `org-scan-tags'."
  13238. (unless match
  13239. ;; Get a new match request, with completion against the global
  13240. ;; tags table and the local tags in current buffer.
  13241. (let ((org-last-tags-completion-table
  13242. (org-uniquify
  13243. (delq nil (append (org-get-buffer-tags)
  13244. (org-global-tags-completion-table))))))
  13245. (setq match
  13246. (completing-read
  13247. "Match: "
  13248. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13249. (let ((match0 match)
  13250. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13251. (start 0)
  13252. tagsmatch todomatch tagsmatcher todomatcher)
  13253. ;; Expand group tags.
  13254. (setq match (org-tags-expand match))
  13255. ;; Check if there is a TODO part of this match, which would be the
  13256. ;; part after a "/". To make sure that this slash is not part of
  13257. ;; a property value to be matched against, we also check that
  13258. ;; there is no / after that slash. First, find the last slash.
  13259. (let ((s 0))
  13260. (while (string-match "/+" match s)
  13261. (setq start (match-beginning 0))
  13262. (setq s (match-end 0))))
  13263. (if (and (string-match "/+" match start)
  13264. (not (string-match-p "\"" match start)))
  13265. ;; Match contains also a TODO-matching request.
  13266. (progn
  13267. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13268. (setq todomatch (substring match (match-end 0)))
  13269. (when (string-match "\\`!" todomatch)
  13270. (setq org--matcher-tags-todo-only t)
  13271. (setq todomatch (substring todomatch 1)))
  13272. (when (string-match "\\`\\s-*\\'" todomatch)
  13273. (setq todomatch nil)))
  13274. ;; Only matching tags.
  13275. (setq tagsmatch match)
  13276. (setq todomatch nil))
  13277. ;; Make the tags matcher.
  13278. (when (org-string-nw-p tagsmatch)
  13279. (let ((orlist nil)
  13280. (orterms (org-split-string tagsmatch "|"))
  13281. term)
  13282. (while (setq term (pop orterms))
  13283. (while (and (equal (substring term -1) "\\") orterms)
  13284. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13285. (while (string-match re term)
  13286. (let* ((rest (substring term (match-end 0)))
  13287. (minus (and (match-end 1)
  13288. (equal (match-string 1 term) "-")))
  13289. (tag (save-match-data
  13290. (replace-regexp-in-string
  13291. "\\\\-" "-" (match-string 2 term))))
  13292. (regexp (eq (string-to-char tag) ?{))
  13293. (levelp (match-end 4))
  13294. (propp (match-end 5))
  13295. (mm
  13296. (cond
  13297. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13298. (levelp
  13299. `(,(org-op-to-function (match-string 3 term))
  13300. level
  13301. ,(string-to-number (match-string 4 term))))
  13302. (propp
  13303. (let* ((gv (pcase (upcase (match-string 5 term))
  13304. ("CATEGORY"
  13305. '(get-text-property (point) 'org-category))
  13306. ("TODO" 'todo)
  13307. (p `(org-cached-entry-get nil ,p))))
  13308. (pv (match-string 7 term))
  13309. (regexp (eq (string-to-char pv) ?{))
  13310. (strp (eq (string-to-char pv) ?\"))
  13311. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13312. (po (org-op-to-function (match-string 6 term)
  13313. (if timep 'time strp))))
  13314. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13315. (when timep (setq pv (org-matcher-time pv)))
  13316. (cond ((and regexp (eq po 'org<>))
  13317. `(not (string-match ,pv (or ,gv ""))))
  13318. (regexp `(string-match ,pv (or ,gv "")))
  13319. (strp `(,po (or ,gv "") ,pv))
  13320. (t
  13321. `(,po
  13322. (string-to-number (or ,gv ""))
  13323. ,(string-to-number pv))))))
  13324. (t `(member ,tag tags-list)))))
  13325. (push (if minus `(not ,mm) mm) tagsmatcher)
  13326. (setq term rest)))
  13327. (push `(and ,@tagsmatcher) orlist)
  13328. (setq tagsmatcher nil))
  13329. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13330. ;; Make the TODO matcher.
  13331. (when (org-string-nw-p todomatch)
  13332. (let ((orlist nil))
  13333. (dolist (term (org-split-string todomatch "|"))
  13334. (while (string-match re term)
  13335. (let* ((minus (and (match-end 1)
  13336. (equal (match-string 1 term) "-")))
  13337. (kwd (match-string 2 term))
  13338. (regexp (eq (string-to-char kwd) ?{))
  13339. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13340. `(equal todo ,kwd))))
  13341. (push (if minus `(not ,mm) mm) todomatcher))
  13342. (setq term (substring term (match-end 0))))
  13343. (push (if (> (length todomatcher) 1)
  13344. (cons 'and todomatcher)
  13345. (car todomatcher))
  13346. orlist)
  13347. (setq todomatcher nil))
  13348. (setq todomatcher (cons 'or orlist))))
  13349. ;; Return the string and function of the matcher. If no
  13350. ;; tags-specific or todo-specific matcher exists, match
  13351. ;; everything.
  13352. (let ((matcher (if (and tagsmatcher todomatcher)
  13353. `(and ,tagsmatcher ,todomatcher)
  13354. (or tagsmatcher todomatcher t))))
  13355. (when org--matcher-tags-todo-only
  13356. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13357. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13358. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13359. "Expand group tags in MATCH.
  13360. This replaces every group tag in MATCH with a regexp tag search.
  13361. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13362. will be replaced like this:
  13363. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13364. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13365. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13366. Replacing by a regexp preserves the structure of the match.
  13367. E.g., this expansion
  13368. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13369. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13370. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13371. A group tag in MATCH can contain regular expressions of its own.
  13372. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13373. will be replaced like this:
  13374. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13375. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13376. assumed to be a single group tag, and the function will return
  13377. the list of tags in this group.
  13378. When DOWNCASE is non-nil, expand downcased TAGS."
  13379. (if org-group-tags
  13380. (let* ((case-fold-search t)
  13381. (stable org-mode-syntax-table)
  13382. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13383. (taggroups (if downcased
  13384. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13385. taggroups)
  13386. taggroups))
  13387. (taggroups-keys (mapcar #'car taggroups))
  13388. (return-match (if downcased (downcase match) match))
  13389. (count 0)
  13390. (work-already-expanded tags-already-expanded)
  13391. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13392. ;; @ and _ are allowed as word-components in tags.
  13393. (modify-syntax-entry ?@ "w" stable)
  13394. (modify-syntax-entry ?_ "w" stable)
  13395. ;; Temporarily replace regexp-expressions in the match-expression.
  13396. (while (string-match "{.+?}" return-match)
  13397. (cl-incf count)
  13398. (push (match-string 0 return-match) regexps-in-match)
  13399. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13400. (while (and taggroups-keys
  13401. (with-syntax-table stable
  13402. (string-match
  13403. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13404. (regexp-opt taggroups-keys) "\\>\\)")
  13405. return-match)))
  13406. (let* ((dir (match-string 1 return-match))
  13407. (tag (match-string 2 return-match))
  13408. (tag (if downcased (downcase tag) tag)))
  13409. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13410. (member tag work-already-expanded))
  13411. (setq tags-in-group (assoc tag taggroups))
  13412. (push tag work-already-expanded)
  13413. ;; Recursively expand each tag in the group, if the tag hasn't
  13414. ;; already been expanded. Restore the match-data after all recursive calls.
  13415. (save-match-data
  13416. (let (tags-expanded)
  13417. (dolist (x (cdr tags-in-group))
  13418. (if (and (member x taggroups-keys)
  13419. (not (member x work-already-expanded)))
  13420. (setq tags-expanded
  13421. (delete-dups
  13422. (append
  13423. (org-tags-expand x t downcased
  13424. work-already-expanded)
  13425. tags-expanded)))
  13426. (setq tags-expanded
  13427. (append (list x) tags-expanded)))
  13428. (setq work-already-expanded
  13429. (delete-dups
  13430. (append tags-expanded
  13431. work-already-expanded))))
  13432. (setq tags-in-group
  13433. (delete-dups (cons (car tags-in-group)
  13434. tags-expanded)))))
  13435. ;; Filter tag-regexps from tags.
  13436. (setq regexp-in-group-escaped
  13437. (delq nil (mapcar (lambda (x)
  13438. (if (stringp x)
  13439. (and (equal "{" (substring x 0 1))
  13440. (equal "}" (substring x -1))
  13441. x)
  13442. x))
  13443. tags-in-group))
  13444. regexp-in-group
  13445. (mapcar (lambda (x)
  13446. (substring x 1 -1))
  13447. regexp-in-group-escaped)
  13448. tags-in-group
  13449. (delq nil (mapcar (lambda (x)
  13450. (if (stringp x)
  13451. (and (not (equal "{" (substring x 0 1)))
  13452. (not (equal "}" (substring x -1)))
  13453. x)
  13454. x))
  13455. tags-in-group)))
  13456. ;; If single-as-list, do no more in the while-loop.
  13457. (if (not single-as-list)
  13458. (progn
  13459. (when regexp-in-group
  13460. (setq regexp-in-group
  13461. (concat "\\|"
  13462. (mapconcat 'identity regexp-in-group
  13463. "\\|"))))
  13464. (setq tags-in-group
  13465. (concat dir
  13466. "{\\<"
  13467. (regexp-opt tags-in-group)
  13468. "\\>"
  13469. regexp-in-group
  13470. "}"))
  13471. (when (stringp tags-in-group)
  13472. (org-add-props tags-in-group '(grouptag t)))
  13473. (setq return-match
  13474. (replace-match tags-in-group t t return-match)))
  13475. (setq tags-in-group
  13476. (append regexp-in-group-escaped tags-in-group))))
  13477. (setq taggroups-keys (delete tag taggroups-keys))))
  13478. ;; Add the regular expressions back into the match-expression again.
  13479. (while regexps-in-match
  13480. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13481. (pop regexps-in-match)
  13482. return-match t t))
  13483. (cl-decf count))
  13484. (if single-as-list
  13485. (if tags-in-group tags-in-group (list return-match))
  13486. return-match))
  13487. (if single-as-list
  13488. (list (if downcased (downcase match) match))
  13489. match)))
  13490. (defun org-op-to-function (op &optional stringp)
  13491. "Turn an operator into the appropriate function."
  13492. (setq op
  13493. (cond
  13494. ((equal op "<" ) '(< string< org-time<))
  13495. ((equal op ">" ) '(> org-string> org-time>))
  13496. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13497. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13498. ((member op '("=" "==")) '(= string= org-time=))
  13499. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13500. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13501. (defun org<> (a b) (not (= a b)))
  13502. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13503. (defun org-string>= (a b) (not (string< a b)))
  13504. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13505. (defun org-string<> (a b) (not (string= a b)))
  13506. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13507. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13508. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13509. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13510. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13511. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13512. (defun org-2ft (s)
  13513. "Convert S to a floating point time.
  13514. If S is already a number, just return it. If it is a string, parse
  13515. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13516. (cond
  13517. ((numberp s) s)
  13518. ((stringp s)
  13519. (condition-case nil
  13520. (float-time (apply 'encode-time (org-parse-time-string s)))
  13521. (error 0.)))
  13522. (t 0.)))
  13523. (defun org-time-today ()
  13524. "Time in seconds today at 0:00.
  13525. Returns the float number of seconds since the beginning of the
  13526. epoch to the beginning of today (00:00)."
  13527. (float-time (apply 'encode-time
  13528. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13529. (defun org-matcher-time (s)
  13530. "Interpret a time comparison value."
  13531. (save-match-data
  13532. (cond
  13533. ((string= s "<now>") (float-time))
  13534. ((string= s "<today>") (org-time-today))
  13535. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13536. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13537. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13538. (+ (org-time-today)
  13539. (* (string-to-number (match-string 1 s))
  13540. (cdr (assoc (match-string 2 s)
  13541. '(("d" . 86400.0) ("w" . 604800.0)
  13542. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13543. (t (org-2ft s)))))
  13544. (defun org-match-any-p (re list)
  13545. "Does re match any element of list?"
  13546. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13547. (delq nil list))
  13548. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13549. (defvar org-tags-overlay (make-overlay 1 1))
  13550. (delete-overlay org-tags-overlay)
  13551. (defun org-get-local-tags-at (&optional pos)
  13552. "Get a list of tags defined in the current headline."
  13553. (org-get-tags-at pos 'local))
  13554. (defun org-get-local-tags ()
  13555. "Get a list of tags defined in the current headline."
  13556. (org-get-tags-at nil 'local))
  13557. (defun org-get-tags-at (&optional pos local)
  13558. "Get a list of all headline tags applicable at POS.
  13559. POS defaults to point. If tags are inherited, the list contains
  13560. the targets in the same sequence as the headlines appear, i.e.
  13561. the tags of the current headline come last.
  13562. When LOCAL is non-nil, only return tags from the current headline,
  13563. ignore inherited ones."
  13564. (interactive)
  13565. (if (and org-trust-scanner-tags
  13566. (or (not pos) (equal pos (point)))
  13567. (not local))
  13568. org-scanner-tags
  13569. (let (tags ltags lastpos parent)
  13570. (save-excursion
  13571. (save-restriction
  13572. (widen)
  13573. (goto-char (or pos (point)))
  13574. (save-match-data
  13575. (catch 'done
  13576. (condition-case nil
  13577. (progn
  13578. (org-back-to-heading t)
  13579. (while (not (equal lastpos (point)))
  13580. (setq lastpos (point))
  13581. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13582. (setq ltags (org-split-string
  13583. (match-string-no-properties 1) ":"))
  13584. (when parent
  13585. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13586. (setq tags (append
  13587. (if parent
  13588. (org-remove-uninherited-tags ltags)
  13589. ltags)
  13590. tags)))
  13591. (or org-use-tag-inheritance (throw 'done t))
  13592. (when local (throw 'done t))
  13593. (or (org-up-heading-safe) (error nil))
  13594. (setq parent t)))
  13595. (error nil)))))
  13596. (if local
  13597. tags
  13598. (reverse (delete-dups
  13599. (reverse (append
  13600. (org-remove-uninherited-tags
  13601. org-file-tags)
  13602. tags)))))))))
  13603. (defun org-add-prop-inherited (s)
  13604. (add-text-properties 0 (length s) '(inherited t) s)
  13605. s)
  13606. (defun org-toggle-tag (tag &optional onoff)
  13607. "Toggle the tag TAG for the current line.
  13608. If ONOFF is `on' or `off', don't toggle but set to this state."
  13609. (let (res current)
  13610. (save-excursion
  13611. (org-back-to-heading t)
  13612. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13613. (point-at-eol) t)
  13614. (progn
  13615. (setq current (match-string 1))
  13616. (replace-match ""))
  13617. (setq current ""))
  13618. (setq current (nreverse (org-split-string current ":")))
  13619. (cond
  13620. ((eq onoff 'on)
  13621. (setq res t)
  13622. (or (member tag current) (push tag current)))
  13623. ((eq onoff 'off)
  13624. (or (not (member tag current)) (setq current (delete tag current))))
  13625. (t (if (member tag current)
  13626. (setq current (delete tag current))
  13627. (setq res t)
  13628. (push tag current))))
  13629. (end-of-line 1)
  13630. (if current
  13631. (progn
  13632. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13633. (org-set-tags nil t))
  13634. (delete-horizontal-space))
  13635. (run-hooks 'org-after-tags-change-hook))
  13636. res))
  13637. (defun org-align-tags-here (to-col)
  13638. ;; Assumes that this is a headline
  13639. "Align tags on the current headline to TO-COL."
  13640. (let ((pos (point)) (col (current-column)) ncol tags-l p)
  13641. (beginning-of-line 1)
  13642. (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13643. (< pos (match-beginning 2)))
  13644. (progn
  13645. (setq tags-l (string-width (match-string 2)))
  13646. (goto-char (match-beginning 1))
  13647. (insert " ")
  13648. (delete-region (point) (1+ (match-beginning 2)))
  13649. (setq ncol (max (current-column)
  13650. (1+ col)
  13651. (if (> to-col 0)
  13652. to-col
  13653. (- (abs to-col) tags-l))))
  13654. (setq p (point))
  13655. (insert (make-string (- ncol (current-column)) ?\ ))
  13656. (setq ncol (current-column))
  13657. (when indent-tabs-mode (tabify p (point-at-eol)))
  13658. (org-move-to-column (min ncol col)))
  13659. (goto-char pos))))
  13660. (defun org-set-tags-command (&optional arg just-align)
  13661. "Call the set-tags command for the current entry."
  13662. (interactive "P")
  13663. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13664. (org-set-tags arg just-align)
  13665. (save-excursion
  13666. (unless (and (org-region-active-p)
  13667. org-loop-over-headlines-in-active-region)
  13668. (org-back-to-heading t))
  13669. (org-set-tags arg just-align))))
  13670. (defun org-set-tags-to (data)
  13671. "Set the tags of the current entry to DATA, replacing the current tags.
  13672. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13673. If DATA is nil or the empty string, any tags will be removed."
  13674. (interactive "sTags: ")
  13675. (setq data
  13676. (cond
  13677. ((eq data nil) "")
  13678. ((equal data "") "")
  13679. ((stringp data)
  13680. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13681. ":"))
  13682. ((listp data)
  13683. (concat ":" (mapconcat 'identity data ":") ":"))))
  13684. (when data
  13685. (save-excursion
  13686. (org-back-to-heading t)
  13687. (when (looking-at org-complex-heading-regexp)
  13688. (if (match-end 5)
  13689. (progn
  13690. (goto-char (match-beginning 5))
  13691. (insert data)
  13692. (delete-region (point) (point-at-eol))
  13693. (org-set-tags nil 'align))
  13694. (goto-char (point-at-eol))
  13695. (insert " " data)
  13696. (org-set-tags nil 'align)))
  13697. (beginning-of-line 1)
  13698. (when (looking-at ".*?\\([ \t]+\\)$")
  13699. (delete-region (match-beginning 1) (match-end 1))))))
  13700. (defun org-align-all-tags ()
  13701. "Align the tags in all headings."
  13702. (interactive)
  13703. (save-excursion
  13704. (or (ignore-errors (org-back-to-heading t))
  13705. (outline-next-heading))
  13706. (if (org-at-heading-p)
  13707. (org-set-tags t)
  13708. (message "No headings"))))
  13709. (defvar org-indent-indentation-per-level)
  13710. (defun org-set-tags (&optional arg just-align)
  13711. "Set the tags for the current headline.
  13712. With prefix ARG, realign all tags in headings in the current buffer.
  13713. When JUST-ALIGN is non-nil, only align tags."
  13714. (interactive "P")
  13715. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13716. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13717. 'region-start-level
  13718. 'region))
  13719. org-loop-over-headlines-in-active-region)
  13720. (org-map-entries
  13721. ;; We don't use ARG and JUST-ALIGN here because these args
  13722. ;; are not useful when looping over headlines.
  13723. #'org-set-tags
  13724. org-loop-over-headlines-in-active-region
  13725. cl
  13726. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13727. (let ((org-setting-tags t))
  13728. (if arg
  13729. (save-excursion
  13730. (goto-char (point-min))
  13731. (while (re-search-forward org-outline-regexp-bol nil t)
  13732. (org-set-tags nil t)
  13733. (end-of-line))
  13734. (message "All tags realigned to column %d" org-tags-column))
  13735. (let* ((current (org-get-tags-string))
  13736. (col (current-column))
  13737. (tags
  13738. (if just-align current
  13739. ;; Get a new set of tags from the user.
  13740. (save-excursion
  13741. (let* ((seen)
  13742. (table
  13743. (setq
  13744. org-last-tags-completion-table
  13745. ;; Uniquify tags in alists, yet preserve
  13746. ;; structure (i.e., keywords).
  13747. (delq nil
  13748. (mapcar
  13749. (lambda (pair)
  13750. (let ((head (car pair)))
  13751. (cond ((symbolp head) pair)
  13752. ((member head seen) nil)
  13753. (t (push head seen)
  13754. pair))))
  13755. (append
  13756. (or org-current-tag-alist
  13757. (org-get-buffer-tags))
  13758. (and
  13759. org-complete-tags-always-offer-all-agenda-tags
  13760. (org-global-tags-completion-table
  13761. (org-agenda-files))))))))
  13762. (current-tags (org-split-string current ":"))
  13763. (inherited-tags
  13764. (nreverse (nthcdr (length current-tags)
  13765. (nreverse (org-get-tags-at))))))
  13766. (replace-regexp-in-string
  13767. "\\([-+&]+\\|,\\)"
  13768. ":"
  13769. (if (or (eq t org-use-fast-tag-selection)
  13770. (and org-use-fast-tag-selection
  13771. (delq nil (mapcar #'cdr table))))
  13772. (org-fast-tag-selection
  13773. current-tags inherited-tags table
  13774. (and org-fast-tag-selection-include-todo
  13775. org-todo-key-alist))
  13776. (let ((org-add-colon-after-tag-completion
  13777. (< 1 (length table))))
  13778. (org-trim
  13779. (completing-read
  13780. "Tags: "
  13781. #'org-tags-completion-function
  13782. nil nil current 'org-tags-history))))))))))
  13783. (when org-tags-sort-function
  13784. (setq tags
  13785. (mapconcat
  13786. #'identity
  13787. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13788. org-tags-sort-function)
  13789. ":")))
  13790. (if (not (org-string-nw-p tags)) (setq tags "")
  13791. (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
  13792. (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
  13793. ;; Insert new tags at the correct column
  13794. (beginning-of-line)
  13795. (let ((level (if (looking-at org-outline-regexp)
  13796. (- (match-end 0) (point) 1)
  13797. 1)))
  13798. (cond
  13799. ((and (equal current "") (equal tags "")))
  13800. ((re-search-forward
  13801. (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
  13802. (line-end-position)
  13803. t)
  13804. (if (equal tags "") (replace-match "" t t)
  13805. (goto-char (match-beginning 0))
  13806. (let* ((c0 (current-column))
  13807. ;; Compute offset for the case of org-indent-mode
  13808. ;; active.
  13809. (di (if (bound-and-true-p org-indent-mode)
  13810. (* (1- org-indent-indentation-per-level)
  13811. (1- level))
  13812. 0))
  13813. (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
  13814. (tc (+ org-tags-column
  13815. (if (> org-tags-column 0) (- di) di)))
  13816. (c1 (max (1+ c0)
  13817. (if (> tc 0) tc
  13818. (- (- tc) (string-width tags)))))
  13819. (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
  13820. (replace-match rpl t t)
  13821. (when indent-tabs-mode (tabify p0 (point))))))
  13822. (t (error "Tags alignment failed"))))
  13823. (org-move-to-column col))
  13824. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13825. (defun org-change-tag-in-region (beg end tag off)
  13826. "Add or remove TAG for each entry in the region.
  13827. This works in the agenda, and also in an Org buffer."
  13828. (interactive
  13829. (list (region-beginning) (region-end)
  13830. (let ((org-last-tags-completion-table
  13831. (if (derived-mode-p 'org-mode)
  13832. (org-uniquify
  13833. (delq nil (append (org-get-buffer-tags)
  13834. (org-global-tags-completion-table))))
  13835. (org-global-tags-completion-table))))
  13836. (completing-read
  13837. "Tag: " 'org-tags-completion-function nil nil nil
  13838. 'org-tags-history))
  13839. (progn
  13840. (message "[s]et or [r]emove? ")
  13841. (equal (read-char-exclusive) ?r))))
  13842. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13843. (let ((agendap (equal major-mode 'org-agenda-mode))
  13844. l1 l2 m buf pos newhead (cnt 0))
  13845. (goto-char end)
  13846. (setq l2 (1- (org-current-line)))
  13847. (goto-char beg)
  13848. (setq l1 (org-current-line))
  13849. (cl-loop for l from l1 to l2 do
  13850. (org-goto-line l)
  13851. (setq m (get-text-property (point) 'org-hd-marker))
  13852. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13853. (and agendap m))
  13854. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13855. pos (if agendap m (point)))
  13856. (with-current-buffer buf
  13857. (save-excursion
  13858. (save-restriction
  13859. (goto-char pos)
  13860. (setq cnt (1+ cnt))
  13861. (org-toggle-tag tag (if off 'off 'on))
  13862. (setq newhead (org-get-heading)))))
  13863. (and agendap (org-agenda-change-all-lines newhead m))))
  13864. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13865. (defun org-tags-completion-function (string _predicate &optional flag)
  13866. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13867. (confirm (lambda (x) (stringp (car x)))))
  13868. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13869. (setq s1 (match-string 1 string)
  13870. s2 (match-string 2 string))
  13871. (setq s1 "" s2 string))
  13872. (cond
  13873. ((eq flag nil)
  13874. ;; try completion
  13875. (setq rtn (try-completion s2 ctable confirm))
  13876. (when (stringp rtn)
  13877. (setq rtn
  13878. (concat s1 s2 (substring rtn (length s2))
  13879. (if (and org-add-colon-after-tag-completion
  13880. (assoc rtn ctable))
  13881. ":" ""))))
  13882. rtn)
  13883. ((eq flag t)
  13884. ;; all-completions
  13885. (all-completions s2 ctable confirm))
  13886. ((eq flag 'lambda)
  13887. ;; exact match?
  13888. (assoc s2 ctable)))))
  13889. (defun org-fast-tag-insert (kwd tags face &optional end)
  13890. "Insert KDW, and the TAGS, the latter with face FACE.
  13891. Also insert END."
  13892. (insert (format "%-12s" (concat kwd ":"))
  13893. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13894. (or end "")))
  13895. (defun org-fast-tag-show-exit (flag)
  13896. (save-excursion
  13897. (org-goto-line 3)
  13898. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13899. (replace-match ""))
  13900. (when flag
  13901. (end-of-line 1)
  13902. (org-move-to-column (- (window-width) 19) t)
  13903. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13904. (defun org-set-current-tags-overlay (current prefix)
  13905. "Add an overlay to CURRENT tag with PREFIX."
  13906. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13907. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13908. (org-overlay-display org-tags-overlay (concat prefix s))))
  13909. (defvar org-last-tag-selection-key nil)
  13910. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13911. "Fast tag selection with single keys.
  13912. CURRENT is the current list of tags in the headline, INHERITED is the
  13913. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13914. possibly with grouping information. TODO-TABLE is a similar table with
  13915. TODO keywords, should these have keys assigned to them.
  13916. If the keys are nil, a-z are automatically assigned.
  13917. Returns the new tags string, or nil to not change the current settings."
  13918. (let* ((fulltable (append table todo-table))
  13919. (maxlen (apply 'max (mapcar
  13920. (lambda (x)
  13921. (if (stringp (car x)) (string-width (car x)) 0))
  13922. fulltable)))
  13923. (buf (current-buffer))
  13924. (expert (eq org-fast-tag-selection-single-key 'expert))
  13925. (buffer-tags nil)
  13926. (fwidth (+ maxlen 3 1 3))
  13927. (ncol (/ (- (window-width) 4) fwidth))
  13928. (i-face 'org-done)
  13929. (c-face 'org-todo)
  13930. tg cnt e c char c1 c2 ntable tbl rtn
  13931. ov-start ov-end ov-prefix
  13932. (exit-after-next org-fast-tag-selection-single-key)
  13933. (done-keywords org-done-keywords)
  13934. groups ingroup intaggroup)
  13935. (save-excursion
  13936. (beginning-of-line 1)
  13937. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13938. (setq ov-start (match-beginning 1)
  13939. ov-end (match-end 1)
  13940. ov-prefix "")
  13941. (setq ov-start (1- (point-at-eol))
  13942. ov-end (1+ ov-start))
  13943. (skip-chars-forward "^\n\r")
  13944. (setq ov-prefix
  13945. (concat
  13946. (buffer-substring (1- (point)) (point))
  13947. (if (> (current-column) org-tags-column)
  13948. " "
  13949. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13950. (move-overlay org-tags-overlay ov-start ov-end)
  13951. (save-window-excursion
  13952. (if expert
  13953. (set-buffer (get-buffer-create " *Org tags*"))
  13954. (delete-other-windows)
  13955. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13956. (org-switch-to-buffer-other-window " *Org tags*"))
  13957. (erase-buffer)
  13958. (setq-local org-done-keywords done-keywords)
  13959. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13960. (org-fast-tag-insert "Current" current c-face "\n\n")
  13961. (org-fast-tag-show-exit exit-after-next)
  13962. (org-set-current-tags-overlay current ov-prefix)
  13963. (setq tbl fulltable char ?a cnt 0)
  13964. (while (setq e (pop tbl))
  13965. (cond
  13966. ((eq (car e) :startgroup)
  13967. (push '() groups) (setq ingroup t)
  13968. (unless (zerop cnt)
  13969. (setq cnt 0)
  13970. (insert "\n"))
  13971. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13972. ((eq (car e) :endgroup)
  13973. (setq ingroup nil cnt 0)
  13974. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13975. ((eq (car e) :startgrouptag)
  13976. (setq intaggroup t)
  13977. (unless (zerop cnt)
  13978. (setq cnt 0)
  13979. (insert "\n"))
  13980. (insert "[ "))
  13981. ((eq (car e) :endgrouptag)
  13982. (setq intaggroup nil cnt 0)
  13983. (insert "]\n"))
  13984. ((equal e '(:newline))
  13985. (unless (zerop cnt)
  13986. (setq cnt 0)
  13987. (insert "\n")
  13988. (setq e (car tbl))
  13989. (while (equal (car tbl) '(:newline))
  13990. (insert "\n")
  13991. (setq tbl (cdr tbl)))))
  13992. ((equal e '(:grouptags)) (insert " : "))
  13993. (t
  13994. (setq tg (copy-sequence (car e)) c2 nil)
  13995. (if (cdr e)
  13996. (setq c (cdr e))
  13997. ;; automatically assign a character.
  13998. (setq c1 (string-to-char
  13999. (downcase (substring
  14000. tg (if (= (string-to-char tg) ?@) 1 0)))))
  14001. (if (or (rassoc c1 ntable) (rassoc c1 table))
  14002. (while (or (rassoc char ntable) (rassoc char table))
  14003. (setq char (1+ char)))
  14004. (setq c2 c1))
  14005. (setq c (or c2 char)))
  14006. (when ingroup (push tg (car groups)))
  14007. (setq tg (org-add-props tg nil 'face
  14008. (cond
  14009. ((not (assoc tg table))
  14010. (org-get-todo-face tg))
  14011. ((member tg current) c-face)
  14012. ((member tg inherited) i-face))))
  14013. (when (equal (caar tbl) :grouptags)
  14014. (org-add-props tg nil 'face 'org-tag-group))
  14015. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  14016. (insert "[" c "] " tg (make-string
  14017. (- fwidth 4 (length tg)) ?\ ))
  14018. (push (cons tg c) ntable)
  14019. (when (= (cl-incf cnt) ncol)
  14020. (insert "\n")
  14021. (when (or ingroup intaggroup) (insert " "))
  14022. (setq cnt 0)))))
  14023. (setq ntable (nreverse ntable))
  14024. (insert "\n")
  14025. (goto-char (point-min))
  14026. (unless expert (org-fit-window-to-buffer))
  14027. (setq rtn
  14028. (catch 'exit
  14029. (while t
  14030. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  14031. (if (not groups) "no " "")
  14032. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  14033. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  14034. (setq org-last-tag-selection-key c)
  14035. (cond
  14036. ((= c ?\r) (throw 'exit t))
  14037. ((= c ?!)
  14038. (setq groups (not groups))
  14039. (goto-char (point-min))
  14040. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  14041. ((= c ?\C-c)
  14042. (if (not expert)
  14043. (org-fast-tag-show-exit
  14044. (setq exit-after-next (not exit-after-next)))
  14045. (setq expert nil)
  14046. (delete-other-windows)
  14047. (set-window-buffer (split-window-vertically) " *Org tags*")
  14048. (org-switch-to-buffer-other-window " *Org tags*")
  14049. (org-fit-window-to-buffer)))
  14050. ((or (= c ?\C-g)
  14051. (and (= c ?q) (not (rassoc c ntable))))
  14052. (delete-overlay org-tags-overlay)
  14053. (setq quit-flag t))
  14054. ((= c ?\ )
  14055. (setq current nil)
  14056. (when exit-after-next (setq exit-after-next 'now)))
  14057. ((= c ?\t)
  14058. (condition-case nil
  14059. (setq tg (completing-read
  14060. "Tag: "
  14061. (or buffer-tags
  14062. (with-current-buffer buf
  14063. (setq buffer-tags
  14064. (org-get-buffer-tags))))))
  14065. (quit (setq tg "")))
  14066. (when (string-match "\\S-" tg)
  14067. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14068. (if (member tg current)
  14069. (setq current (delete tg current))
  14070. (push tg current)))
  14071. (when exit-after-next (setq exit-after-next 'now)))
  14072. ((setq e (rassoc c todo-table) tg (car e))
  14073. (with-current-buffer buf
  14074. (save-excursion (org-todo tg)))
  14075. (when exit-after-next (setq exit-after-next 'now)))
  14076. ((setq e (rassoc c ntable) tg (car e))
  14077. (if (member tg current)
  14078. (setq current (delete tg current))
  14079. (cl-loop for g in groups do
  14080. (when (member tg g)
  14081. (dolist (x g) (setq current (delete x current)))))
  14082. (push tg current))
  14083. (when exit-after-next (setq exit-after-next 'now))))
  14084. ;; Create a sorted list
  14085. (setq current
  14086. (sort current
  14087. (lambda (a b)
  14088. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14089. (when (eq exit-after-next 'now) (throw 'exit t))
  14090. (goto-char (point-min))
  14091. (beginning-of-line 2)
  14092. (delete-region (point) (point-at-eol))
  14093. (org-fast-tag-insert "Current" current c-face)
  14094. (org-set-current-tags-overlay current ov-prefix)
  14095. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14096. (setq tg (match-string 1))
  14097. (add-text-properties
  14098. (match-beginning 1) (match-end 1)
  14099. (list 'face
  14100. (cond
  14101. ((member tg current) c-face)
  14102. ((member tg inherited) i-face)
  14103. (t (get-text-property (match-beginning 1) 'face))))))
  14104. (goto-char (point-min)))))
  14105. (delete-overlay org-tags-overlay)
  14106. (if rtn
  14107. (mapconcat 'identity current ":")
  14108. nil))))
  14109. (defun org-get-tags-string ()
  14110. "Get the TAGS string in the current headline."
  14111. (unless (org-at-heading-p t)
  14112. (user-error "Not on a heading"))
  14113. (save-excursion
  14114. (beginning-of-line 1)
  14115. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14116. (match-string-no-properties 1)
  14117. "")))
  14118. (defun org-get-tags ()
  14119. "Get the list of tags specified in the current headline."
  14120. (org-split-string (org-get-tags-string) ":"))
  14121. (defun org-get-buffer-tags ()
  14122. "Get a table of all tags used in the buffer, for completion."
  14123. (org-with-wide-buffer
  14124. (goto-char (point-min))
  14125. (let ((tag-re (concat org-outline-regexp-bol
  14126. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14127. tags)
  14128. (while (re-search-forward tag-re nil t)
  14129. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14130. (push tag tags)))
  14131. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14132. ;;;; The mapping API
  14133. (defvar org-agenda-skip-comment-trees)
  14134. (defvar org-agenda-skip-function)
  14135. (defun org-map-entries (func &optional match scope &rest skip)
  14136. "Call FUNC at each headline selected by MATCH in SCOPE.
  14137. FUNC is a function or a lisp form. The function will be called without
  14138. arguments, with the cursor positioned at the beginning of the headline.
  14139. The return values of all calls to the function will be collected and
  14140. returned as a list.
  14141. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14142. does not need to preserve point. After evaluation, the cursor will be
  14143. moved to the end of the line (presumably of the headline of the
  14144. processed entry) and search continues from there. Under some
  14145. circumstances, this may not produce the wanted results. For example,
  14146. if you have removed (e.g. archived) the current (sub)tree it could
  14147. mean that the next entry will be skipped entirely. In such cases, you
  14148. can specify the position from where search should continue by making
  14149. FUNC set the variable `org-map-continue-from' to the desired buffer
  14150. position.
  14151. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14152. Only headlines that are matched by this query will be considered during
  14153. the iteration. When MATCH is nil or t, all headlines will be
  14154. visited by the iteration.
  14155. SCOPE determines the scope of this command. It can be any of:
  14156. nil The current buffer, respecting the restriction if any
  14157. tree The subtree started with the entry at point
  14158. region The entries within the active region, if any
  14159. region-start-level
  14160. The entries within the active region, but only those at
  14161. the same level than the first one.
  14162. file The current buffer, without restriction
  14163. file-with-archives
  14164. The current buffer, and any archives associated with it
  14165. agenda All agenda files
  14166. agenda-with-archives
  14167. All agenda files with any archive files associated with them
  14168. \(file1 file2 ...)
  14169. If this is a list, all files in the list will be scanned
  14170. The remaining args are treated as settings for the skipping facilities of
  14171. the scanner. The following items can be given here:
  14172. archive skip trees with the archive tag
  14173. comment skip trees with the COMMENT keyword
  14174. function or Emacs Lisp form:
  14175. will be used as value for `org-agenda-skip-function', so
  14176. whenever the function returns a position, FUNC will not be
  14177. called for that entry and search will continue from the
  14178. position returned
  14179. If your function needs to retrieve the tags including inherited tags
  14180. at the *current* entry, you can use the value of the variable
  14181. `org-scanner-tags' which will be much faster than getting the value
  14182. with `org-get-tags-at'. If your function gets properties with
  14183. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14184. to t around the call to `org-entry-properties' to get the same speedup.
  14185. Note that if your function moves around to retrieve tags and properties at
  14186. a *different* entry, you cannot use these techniques."
  14187. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14188. (not (org-region-active-p)))
  14189. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14190. (org-agenda-skip-archived-trees (memq 'archive skip))
  14191. (org-agenda-skip-comment-trees (memq 'comment skip))
  14192. (org-agenda-skip-function
  14193. (car (org-delete-all '(comment archive) skip)))
  14194. (org-tags-match-list-sublevels t)
  14195. (start-level (eq scope 'region-start-level))
  14196. matcher res
  14197. org-todo-keywords-for-agenda
  14198. org-done-keywords-for-agenda
  14199. org-todo-keyword-alist-for-agenda
  14200. org-tag-alist-for-agenda
  14201. org--matcher-tags-todo-only)
  14202. (cond
  14203. ((eq match t) (setq matcher t))
  14204. ((eq match nil) (setq matcher t))
  14205. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14206. (save-excursion
  14207. (save-restriction
  14208. (cond ((eq scope 'tree)
  14209. (org-back-to-heading t)
  14210. (org-narrow-to-subtree)
  14211. (setq scope nil))
  14212. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14213. (org-region-active-p))
  14214. ;; If needed, set start-level to a string like "2"
  14215. (when start-level
  14216. (save-excursion
  14217. (goto-char (region-beginning))
  14218. (unless (org-at-heading-p) (outline-next-heading))
  14219. (setq start-level (org-current-level))))
  14220. (narrow-to-region (region-beginning)
  14221. (save-excursion
  14222. (goto-char (region-end))
  14223. (unless (and (bolp) (org-at-heading-p))
  14224. (outline-next-heading))
  14225. (point)))
  14226. (setq scope nil)))
  14227. (if (not scope)
  14228. (progn
  14229. (org-agenda-prepare-buffers
  14230. (and buffer-file-name (list buffer-file-name)))
  14231. (setq res
  14232. (org-scan-tags
  14233. func matcher org--matcher-tags-todo-only start-level)))
  14234. ;; Get the right scope
  14235. (cond
  14236. ((and scope (listp scope) (symbolp (car scope)))
  14237. (setq scope (eval scope)))
  14238. ((eq scope 'agenda)
  14239. (setq scope (org-agenda-files t)))
  14240. ((eq scope 'agenda-with-archives)
  14241. (setq scope (org-agenda-files t))
  14242. (setq scope (org-add-archive-files scope)))
  14243. ((eq scope 'file)
  14244. (setq scope (and buffer-file-name (list buffer-file-name))))
  14245. ((eq scope 'file-with-archives)
  14246. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14247. (org-agenda-prepare-buffers scope)
  14248. (dolist (file scope)
  14249. (with-current-buffer (org-find-base-buffer-visiting file)
  14250. (save-excursion
  14251. (save-restriction
  14252. (widen)
  14253. (goto-char (point-min))
  14254. (setq res
  14255. (append
  14256. res
  14257. (org-scan-tags
  14258. func matcher org--matcher-tags-todo-only))))))))))
  14259. res)))
  14260. ;;; Properties API
  14261. (defconst org-special-properties
  14262. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14263. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14264. "The special properties valid in Org mode.
  14265. These are properties that are not defined in the property drawer,
  14266. but in some other way.")
  14267. (defconst org-default-properties
  14268. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14269. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14270. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14271. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14272. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14273. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14274. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14275. "Some properties that are used by Org mode for various purposes.
  14276. Being in this list makes sure that they are offered for completion.")
  14277. (defun org--valid-property-p (property)
  14278. "Non nil when string PROPERTY is a valid property name."
  14279. (not
  14280. (or (equal property "")
  14281. (string-match-p "\\s-" property))))
  14282. (defun org--update-property-plist (key val props)
  14283. "Associate KEY to VAL in alist PROPS.
  14284. Modifications are made by side-effect. Return new alist."
  14285. (let* ((appending (string= (substring key -1) "+"))
  14286. (key (if appending (substring key 0 -1) key))
  14287. (old (assoc-string key props t)))
  14288. (if (not old) (cons (cons key val) props)
  14289. (setcdr old (if appending (concat (cdr old) " " val) val))
  14290. props)))
  14291. (defun org-get-property-block (&optional beg force)
  14292. "Return the (beg . end) range of the body of the property drawer.
  14293. BEG is the beginning of the current subtree, or of the part
  14294. before the first headline. If it is not given, it will be found.
  14295. If the drawer does not exist, create it if FORCE is non-nil, or
  14296. return nil."
  14297. (org-with-wide-buffer
  14298. (when beg (goto-char beg))
  14299. (unless (org-before-first-heading-p)
  14300. (let ((beg (cond (beg)
  14301. ((or (not (featurep 'org-inlinetask))
  14302. (org-inlinetask-in-task-p))
  14303. (org-back-to-heading t))
  14304. (t (org-with-limited-levels (org-back-to-heading t))))))
  14305. (forward-line)
  14306. (when (looking-at-p org-planning-line-re) (forward-line))
  14307. (cond ((looking-at org-property-drawer-re)
  14308. (forward-line)
  14309. (cons (point) (progn (goto-char (match-end 0))
  14310. (line-beginning-position))))
  14311. (force
  14312. (goto-char beg)
  14313. (org-insert-property-drawer)
  14314. (let ((pos (save-excursion (search-forward ":END:")
  14315. (line-beginning-position))))
  14316. (cons pos pos))))))))
  14317. (defun org-at-property-p ()
  14318. "Non-nil when point is inside a property drawer.
  14319. See `org-property-re' for match data, if applicable."
  14320. (save-excursion
  14321. (beginning-of-line)
  14322. (and (looking-at org-property-re)
  14323. (let ((property-drawer (save-match-data (org-get-property-block))))
  14324. (and property-drawer
  14325. (>= (point) (car property-drawer))
  14326. (< (point) (cdr property-drawer)))))))
  14327. (defun org-property-action ()
  14328. "Do an action on properties."
  14329. (interactive)
  14330. (unless (org-at-property-p) (user-error "Not at a property"))
  14331. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14332. (let ((c (read-char-exclusive)))
  14333. (cl-case c
  14334. (?s (call-interactively #'org-set-property))
  14335. (?d (call-interactively #'org-delete-property))
  14336. (?D (call-interactively #'org-delete-property-globally))
  14337. (?c (call-interactively #'org-compute-property-at-point))
  14338. (otherwise (user-error "No such property action %c" c)))))
  14339. (defun org-inc-effort ()
  14340. "Increment the value of the effort property in the current entry."
  14341. (interactive)
  14342. (org-set-effort nil t))
  14343. (defvar org-clock-effort) ; Defined in org-clock.el.
  14344. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14345. (defun org-set-effort (&optional value increment)
  14346. "Set the effort property of the current entry.
  14347. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14348. 10th allowed value.
  14349. When INCREMENT is non-nil, set the property to the next allowed value."
  14350. (interactive "P")
  14351. (when (equal value 0) (setq value 10))
  14352. (let* ((completion-ignore-case t)
  14353. (prop org-effort-property)
  14354. (cur (org-entry-get nil prop))
  14355. (allowed (org-property-get-allowed-values nil prop 'table))
  14356. (existing (mapcar 'list (org-property-values prop)))
  14357. (heading (nth 4 (org-heading-components)))
  14358. rpl
  14359. (val (cond
  14360. ((stringp value) value)
  14361. ((and allowed (integerp value))
  14362. (or (car (nth (1- value) allowed))
  14363. (car (org-last allowed))))
  14364. ((and allowed increment)
  14365. (or (cl-caadr (member (list cur) allowed))
  14366. (user-error "Allowed effort values are not set")))
  14367. (allowed
  14368. (message "Select 1-9,0, [RET%s]: %s"
  14369. (if cur (concat "=" cur) "")
  14370. (mapconcat 'car allowed " "))
  14371. (setq rpl (read-char-exclusive))
  14372. (if (equal rpl ?\r)
  14373. cur
  14374. (setq rpl (- rpl ?0))
  14375. (when (equal rpl 0) (setq rpl 10))
  14376. (if (and (> rpl 0) (<= rpl (length allowed)))
  14377. (car (nth (1- rpl) allowed))
  14378. (org-completing-read "Effort: " allowed nil))))
  14379. (t
  14380. (org-completing-read
  14381. (concat "Effort" (and cur (string-match "\\S-" cur)
  14382. (concat " [" cur "]"))
  14383. ": ")
  14384. existing nil nil "" nil cur)))))
  14385. (unless (equal (org-entry-get nil prop) val)
  14386. (org-entry-put nil prop val))
  14387. (org-refresh-property
  14388. '((effort . identity)
  14389. (effort-minutes . org-duration-string-to-minutes))
  14390. val)
  14391. (when (equal heading (bound-and-true-p org-clock-current-task))
  14392. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14393. (org-clock-update-mode-line))
  14394. (message "%s is now %s" prop val)))
  14395. (defun org-entry-properties (&optional pom which)
  14396. "Get all properties of the current entry.
  14397. When POM is a buffer position, get all properties from the entry
  14398. there instead.
  14399. This includes the TODO keyword, the tags, time strings for
  14400. deadline, scheduled, and clocking, and any additional properties
  14401. defined in the entry.
  14402. If WHICH is nil or `all', get all properties. If WHICH is
  14403. `special' or `standard', only get that subclass. If WHICH is
  14404. a string, only get that property.
  14405. Return value is an alist. Keys are properties, as upcased
  14406. strings."
  14407. (org-with-point-at pom
  14408. (when (and (derived-mode-p 'org-mode)
  14409. (ignore-errors (org-back-to-heading t)))
  14410. (catch 'exit
  14411. (let* ((beg (point))
  14412. (specific (and (stringp which) (upcase which)))
  14413. (which (cond ((not specific) which)
  14414. ((member specific org-special-properties) 'special)
  14415. (t 'standard)))
  14416. props)
  14417. ;; Get the special properties, like TODO and TAGS.
  14418. (when (memq which '(nil all special))
  14419. (when (or (not specific) (string= specific "CLOCKSUM"))
  14420. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14421. (when clocksum
  14422. (push (cons "CLOCKSUM"
  14423. (org-minutes-to-clocksum-string clocksum))
  14424. props)))
  14425. (when specific (throw 'exit props)))
  14426. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14427. (let ((clocksumt (get-text-property (point)
  14428. :org-clock-minutes-today)))
  14429. (when clocksumt
  14430. (push (cons "CLOCKSUM_T"
  14431. (org-minutes-to-clocksum-string clocksumt))
  14432. props)))
  14433. (when specific (throw 'exit props)))
  14434. (when (or (not specific) (string= specific "ITEM"))
  14435. (when (looking-at org-complex-heading-regexp)
  14436. (push (cons "ITEM"
  14437. (let ((title (match-string-no-properties 4)))
  14438. (if (org-string-nw-p title)
  14439. (org-remove-tabs title)
  14440. "")))
  14441. props))
  14442. (when specific (throw 'exit props)))
  14443. (when (or (not specific) (string= specific "TODO"))
  14444. (let ((case-fold-search nil))
  14445. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14446. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14447. (when specific (throw 'exit props)))
  14448. (when (or (not specific) (string= specific "PRIORITY"))
  14449. (push (cons "PRIORITY"
  14450. (if (looking-at org-priority-regexp)
  14451. (match-string-no-properties 2)
  14452. (char-to-string org-default-priority)))
  14453. props)
  14454. (when specific (throw 'exit props)))
  14455. (when (or (not specific) (string= specific "FILE"))
  14456. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14457. props)
  14458. (when specific (throw 'exit props)))
  14459. (when (or (not specific) (string= specific "TAGS"))
  14460. (let ((value (org-string-nw-p (org-get-tags-string))))
  14461. (when value (push (cons "TAGS" value) props)))
  14462. (when specific (throw 'exit props)))
  14463. (when (or (not specific) (string= specific "ALLTAGS"))
  14464. (let ((value (org-get-tags-at)))
  14465. (when value
  14466. (push (cons "ALLTAGS"
  14467. (format ":%s:" (mapconcat #'identity value ":")))
  14468. props)))
  14469. (when specific (throw 'exit props)))
  14470. (when (or (not specific) (string= specific "BLOCKED"))
  14471. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14472. (when specific (throw 'exit props)))
  14473. (when (or (not specific)
  14474. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14475. (forward-line)
  14476. (when (looking-at-p org-planning-line-re)
  14477. (end-of-line)
  14478. (let ((bol (line-beginning-position))
  14479. ;; Backward compatibility: time keywords used to
  14480. ;; be configurable (before 8.3). Make sure we
  14481. ;; get the correct keyword.
  14482. (key-assoc `(("CLOSED" . ,org-closed-string)
  14483. ("DEADLINE" . ,org-deadline-string)
  14484. ("SCHEDULED" . ,org-scheduled-string))))
  14485. (dolist (pair (if specific (list (assoc specific key-assoc))
  14486. key-assoc))
  14487. (save-excursion
  14488. (when (search-backward (cdr pair) bol t)
  14489. (goto-char (match-end 0))
  14490. (skip-chars-forward " \t")
  14491. (and (looking-at org-ts-regexp-both)
  14492. (push (cons (car pair)
  14493. (match-string-no-properties 0))
  14494. props)))))))
  14495. (when specific (throw 'exit props)))
  14496. (when (or (not specific)
  14497. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14498. (let ((find-ts
  14499. (lambda (end ts)
  14500. ;; Fix next time-stamp before END. TS is the
  14501. ;; list of time-stamps found so far.
  14502. (let ((ts ts)
  14503. (regexp (cond
  14504. ((string= specific "TIMESTAMP")
  14505. org-ts-regexp)
  14506. ((string= specific "TIMESTAMP_IA")
  14507. org-ts-regexp-inactive)
  14508. ((assoc "TIMESTAMP_IA" ts)
  14509. org-ts-regexp)
  14510. ((assoc "TIMESTAMP" ts)
  14511. org-ts-regexp-inactive)
  14512. (t org-ts-regexp-both))))
  14513. (catch 'next
  14514. (while (re-search-forward regexp end t)
  14515. (backward-char)
  14516. (let ((object (org-element-context)))
  14517. ;; Accept to match timestamps in node
  14518. ;; properties, too.
  14519. (when (memq (org-element-type object)
  14520. '(node-property timestamp))
  14521. (let ((type
  14522. (org-element-property :type object)))
  14523. (cond
  14524. ((and (memq type '(active active-range))
  14525. (not (equal specific "TIMESTAMP_IA")))
  14526. (unless (assoc "TIMESTAMP" ts)
  14527. (push (cons "TIMESTAMP"
  14528. (org-element-property
  14529. :raw-value object))
  14530. ts)
  14531. (when specific (throw 'exit ts))))
  14532. ((and (memq type '(inactive inactive-range))
  14533. (not (string= specific "TIMESTAMP")))
  14534. (unless (assoc "TIMESTAMP_IA" ts)
  14535. (push (cons "TIMESTAMP_IA"
  14536. (org-element-property
  14537. :raw-value object))
  14538. ts)
  14539. (when specific (throw 'exit ts))))))
  14540. ;; Both timestamp types are found,
  14541. ;; move to next part.
  14542. (when (= (length ts) 2) (throw 'next ts)))))
  14543. ts)))))
  14544. (goto-char beg)
  14545. ;; First look for timestamps within headline.
  14546. (let ((ts (funcall find-ts (line-end-position) nil)))
  14547. (if (= (length ts) 2) (setq props (nconc ts props))
  14548. (forward-line)
  14549. ;; Then find timestamps in the section, skipping
  14550. ;; planning line.
  14551. (when (looking-at-p org-planning-line-re)
  14552. (forward-line))
  14553. (let ((end (save-excursion (outline-next-heading))))
  14554. (setq props (nconc (funcall find-ts end ts) props))))))))
  14555. ;; Get the standard properties, like :PROP:.
  14556. (when (memq which '(nil all standard))
  14557. ;; If we are looking after a specific property, delegate
  14558. ;; to `org-entry-get', which is faster. However, make an
  14559. ;; exception for "CATEGORY", since it can be also set
  14560. ;; through keywords (i.e. #+CATEGORY).
  14561. (if (and specific (not (equal specific "CATEGORY")))
  14562. (let ((value (org-entry-get beg specific nil t)))
  14563. (throw 'exit (and value (list (cons specific value)))))
  14564. (let ((range (org-get-property-block beg)))
  14565. (when range
  14566. (let ((end (cdr range)) seen-base)
  14567. (goto-char (car range))
  14568. ;; Unlike to `org--update-property-plist', we
  14569. ;; handle the case where base values is found
  14570. ;; after its extension. We also forbid standard
  14571. ;; properties to be named as special properties.
  14572. (while (re-search-forward org-property-re end t)
  14573. (let* ((key (upcase (match-string-no-properties 2)))
  14574. (extendp (string-match-p "\\+\\'" key))
  14575. (key-base (if extendp (substring key 0 -1) key))
  14576. (value (match-string-no-properties 3)))
  14577. (cond
  14578. ((member-ignore-case key-base org-special-properties))
  14579. (extendp
  14580. (setq props
  14581. (org--update-property-plist key value props)))
  14582. ((member key seen-base))
  14583. (t (push key seen-base)
  14584. (let ((p (assoc-string key props t)))
  14585. (if p (setcdr p (concat value " " (cdr p)))
  14586. (push (cons key value) props))))))))))))
  14587. (unless (assoc "CATEGORY" props)
  14588. (push (cons "CATEGORY" (org-get-category beg)) props)
  14589. (when (string= specific "CATEGORY") (throw 'exit props)))
  14590. ;; Return value.
  14591. props)))))
  14592. (defun org-property--local-values (property literal-nil)
  14593. "Return value for PROPERTY in current entry.
  14594. Value is a list whose car is the base value for PROPERTY and cdr
  14595. a list of accumulated values. Return nil if neither is found in
  14596. the entry. Also return nil when PROPERTY is set to \"nil\",
  14597. unless LITERAL-NIL is non-nil."
  14598. (let ((range (org-get-property-block)))
  14599. (when range
  14600. (goto-char (car range))
  14601. (let* ((case-fold-search t)
  14602. (end (cdr range))
  14603. (value
  14604. ;; Base value.
  14605. (save-excursion
  14606. (let ((v (and (re-search-forward
  14607. (org-re-property property nil t) end t)
  14608. (match-string-no-properties 3))))
  14609. (list (if literal-nil v (org-not-nil v)))))))
  14610. ;; Find additional values.
  14611. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14612. (while (re-search-forward property+ end t)
  14613. (push (match-string-no-properties 3) value)))
  14614. ;; Return final values.
  14615. (and (not (equal value '(nil))) (nreverse value))))))
  14616. (defun org-entry-get (pom property &optional inherit literal-nil)
  14617. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14618. If INHERIT is non-nil and the entry does not have the property,
  14619. then also check higher levels of the hierarchy. If INHERIT is
  14620. the symbol `selective', use inheritance only if the setting in
  14621. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14622. If the property is present but empty, the return value is the
  14623. empty string. If the property is not present at all, nil is
  14624. returned. In any other case, return the value as a string.
  14625. Search is case-insensitive.
  14626. If LITERAL-NIL is set, return the string value \"nil\" as
  14627. a string, do not interpret it as the list atom nil. This is used
  14628. for inheritance when a \"nil\" value can supersede a non-nil
  14629. value higher up the hierarchy."
  14630. (org-with-point-at pom
  14631. (cond
  14632. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14633. ;; We need a special property. Use `org-entry-properties' to
  14634. ;; retrieve it, but specify the wanted property.
  14635. (cdr (assoc-string property (org-entry-properties nil property))))
  14636. ((and inherit
  14637. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14638. (org-entry-get-with-inheritance property literal-nil))
  14639. (t
  14640. (let* ((local (org-property--local-values property literal-nil))
  14641. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14642. (if literal-nil value (org-not-nil value)))))))
  14643. (defun org-property-or-variable-value (var &optional inherit)
  14644. "Check if there is a property fixing the value of VAR.
  14645. If yes, return this value. If not, return the current value of the variable."
  14646. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14647. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14648. (read prop)
  14649. (symbol-value var))))
  14650. (defun org-entry-delete (pom property)
  14651. "Delete PROPERTY from entry at point-or-marker POM.
  14652. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14653. non-nil when a property was removed."
  14654. (unless (member property org-special-properties)
  14655. (org-with-point-at pom
  14656. (let ((range (org-get-property-block)))
  14657. (when range
  14658. (let* ((begin (car range))
  14659. (origin (cdr range))
  14660. (end (copy-marker origin))
  14661. (re (org-re-property
  14662. (concat (regexp-quote property) "\\+?") t t)))
  14663. (goto-char begin)
  14664. (while (re-search-forward re end t)
  14665. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14666. ;; If drawer is empty, remove it altogether.
  14667. (when (= begin end)
  14668. (delete-region (line-beginning-position 0)
  14669. (line-beginning-position 2)))
  14670. ;; Return non-nil if some property was removed.
  14671. (prog1 (/= end origin) (set-marker end nil))))))))
  14672. ;; Multi-values properties are properties that contain multiple values
  14673. ;; These values are assumed to be single words, separated by whitespace.
  14674. (defun org-entry-add-to-multivalued-property (pom property value)
  14675. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14676. (let* ((old (org-entry-get pom property))
  14677. (values (and old (org-split-string old "[ \t]"))))
  14678. (setq value (org-entry-protect-space value))
  14679. (unless (member value values)
  14680. (setq values (append values (list value)))
  14681. (org-entry-put pom property
  14682. (mapconcat 'identity values " ")))))
  14683. (defun org-entry-remove-from-multivalued-property (pom property value)
  14684. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14685. (let* ((old (org-entry-get pom property))
  14686. (values (and old (org-split-string old "[ \t]"))))
  14687. (setq value (org-entry-protect-space value))
  14688. (when (member value values)
  14689. (setq values (delete value values))
  14690. (org-entry-put pom property
  14691. (mapconcat 'identity values " ")))))
  14692. (defun org-entry-member-in-multivalued-property (pom property value)
  14693. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14694. (let* ((old (org-entry-get pom property))
  14695. (values (and old (org-split-string old "[ \t]"))))
  14696. (setq value (org-entry-protect-space value))
  14697. (member value values)))
  14698. (defun org-entry-get-multivalued-property (pom property)
  14699. "Return a list of values in a multivalued property."
  14700. (let* ((value (org-entry-get pom property))
  14701. (values (and value (org-split-string value "[ \t]"))))
  14702. (mapcar 'org-entry-restore-space values)))
  14703. (defun org-entry-put-multivalued-property (pom property &rest values)
  14704. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14705. VALUES should be a list of strings. Spaces will be protected."
  14706. (org-entry-put pom property
  14707. (mapconcat 'org-entry-protect-space values " "))
  14708. (let* ((value (org-entry-get pom property))
  14709. (values (and value (org-split-string value "[ \t]"))))
  14710. (mapcar 'org-entry-restore-space values)))
  14711. (defun org-entry-protect-space (s)
  14712. "Protect spaces and newline in string S."
  14713. (while (string-match " " s)
  14714. (setq s (replace-match "%20" t t s)))
  14715. (while (string-match "\n" s)
  14716. (setq s (replace-match "%0A" t t s)))
  14717. s)
  14718. (defun org-entry-restore-space (s)
  14719. "Restore spaces and newline in string S."
  14720. (while (string-match "%20" s)
  14721. (setq s (replace-match " " t t s)))
  14722. (while (string-match "%0A" s)
  14723. (setq s (replace-match "\n" t t s)))
  14724. s)
  14725. (defvar org-entry-property-inherited-from (make-marker)
  14726. "Marker pointing to the entry from where a property was inherited.
  14727. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14728. location of the entry where the inheritance search matched. If there was
  14729. no match, the marker will point nowhere.
  14730. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14731. is set.")
  14732. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14733. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14734. The search will stop at the first ancestor which has the property defined.
  14735. If the value found is \"nil\", return nil to show that the property
  14736. should be considered as undefined (this is the meaning of nil here).
  14737. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14738. (move-marker org-entry-property-inherited-from nil)
  14739. (org-with-wide-buffer
  14740. (let (value)
  14741. (catch 'exit
  14742. (while t
  14743. (let ((v (org-property--local-values property literal-nil)))
  14744. (when v
  14745. (setq value
  14746. (concat (mapconcat #'identity (delq nil v) " ")
  14747. (and value " ")
  14748. value)))
  14749. (cond
  14750. ((car v)
  14751. (org-back-to-heading t)
  14752. (move-marker org-entry-property-inherited-from (point))
  14753. (throw 'exit nil))
  14754. ((org-up-heading-safe))
  14755. (t
  14756. (let ((global
  14757. (cdr (or (assoc-string property org-file-properties t)
  14758. (assoc-string property org-global-properties t)
  14759. (assoc-string property org-global-properties-fixed t)))))
  14760. (cond ((not global))
  14761. (value (setq value (concat global " " value)))
  14762. (t (setq value global))))
  14763. (throw 'exit nil))))))
  14764. (if literal-nil value (org-not-nil value)))))
  14765. (defvar org-property-changed-functions nil
  14766. "Hook called when the value of a property has changed.
  14767. Each hook function should accept two arguments, the name of the property
  14768. and the new value.")
  14769. (defun org-entry-put (pom property value)
  14770. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14771. If the value is nil, it is converted to the empty string. If it
  14772. is not a string, an error is raised. Also raise an error on
  14773. invalid property names.
  14774. PROPERTY can be any regular property (see
  14775. `org-special-properties'). It can also be \"TODO\",
  14776. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14777. For the last two properties, VALUE may have any of the special
  14778. values \"earlier\" and \"later\". The function then increases or
  14779. decreases scheduled or deadline date by one day."
  14780. (cond ((null value) (setq value ""))
  14781. ((not (stringp value)) (error "Properties values should be strings"))
  14782. ((not (org--valid-property-p property))
  14783. (user-error "Invalid property name: \"%s\"" property)))
  14784. (org-with-point-at pom
  14785. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14786. (org-back-to-heading t)
  14787. (org-with-limited-levels (org-back-to-heading t)))
  14788. (let ((beg (point)))
  14789. (cond
  14790. ((equal property "TODO")
  14791. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14792. ((not (member value org-todo-keywords-1))
  14793. (user-error "\"%s\" is not a valid TODO state" value)))
  14794. (org-todo value)
  14795. (org-set-tags nil 'align))
  14796. ((equal property "PRIORITY")
  14797. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14798. (org-set-tags nil 'align))
  14799. ((equal property "SCHEDULED")
  14800. (forward-line)
  14801. (if (and (looking-at-p org-planning-line-re)
  14802. (re-search-forward
  14803. org-scheduled-time-regexp (line-end-position) t))
  14804. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14805. ((string= value "later") (org-timestamp-change 1 'day))
  14806. ((string= value "") (org-schedule '(4)))
  14807. (t (org-schedule nil value)))
  14808. (if (member value '("earlier" "later" ""))
  14809. (call-interactively #'org-schedule)
  14810. (org-schedule nil value))))
  14811. ((equal property "DEADLINE")
  14812. (forward-line)
  14813. (if (and (looking-at-p org-planning-line-re)
  14814. (re-search-forward
  14815. org-deadline-time-regexp (line-end-position) t))
  14816. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14817. ((string= value "later") (org-timestamp-change 1 'day))
  14818. ((string= value "") (org-deadline '(4)))
  14819. (t (org-deadline nil value)))
  14820. (if (member value '("earlier" "later" ""))
  14821. (call-interactively #'org-deadline)
  14822. (org-deadline nil value))))
  14823. ((member property org-special-properties)
  14824. (error "The %s property cannot be set with `org-entry-put'" property))
  14825. (t
  14826. (let* ((range (org-get-property-block beg 'force))
  14827. (end (cdr range))
  14828. (case-fold-search t))
  14829. (goto-char (car range))
  14830. (if (re-search-forward (org-re-property property nil t) end t)
  14831. (progn (delete-region (match-beginning 0) (match-end 0))
  14832. (goto-char (match-beginning 0)))
  14833. (goto-char end)
  14834. (insert "\n")
  14835. (backward-char))
  14836. (insert ":" property ":")
  14837. (when value (insert " " value))
  14838. (org-indent-line)))))
  14839. (run-hook-with-args 'org-property-changed-functions property value)))
  14840. (defun org-buffer-property-keys
  14841. (&optional specials defaults columns ignore-malformed)
  14842. "Get all property keys in the current buffer.
  14843. When SPECIALS is non-nil, also list the special properties that
  14844. reflect things like tags and TODO state.
  14845. When DEFAULTS is non-nil, also include properties that has
  14846. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14847. DESCRIPTION, LOCATION, and LOGGING and others.
  14848. When COLUMNS in non-nil, also include property names given in
  14849. COLUMN formats in the current buffer.
  14850. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14851. automatically performed, such drawers will be silently ignored."
  14852. (let ((case-fold-search t)
  14853. (props (append
  14854. (and specials org-special-properties)
  14855. (and defaults (cons org-effort-property org-default-properties))
  14856. nil)))
  14857. (org-with-wide-buffer
  14858. (goto-char (point-min))
  14859. (while (re-search-forward org-property-start-re nil t)
  14860. (let ((range (org-get-property-block)))
  14861. (catch 'skip
  14862. (unless range
  14863. (when (and (not ignore-malformed)
  14864. (not (org-before-first-heading-p))
  14865. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14866. (line-beginning-position))))
  14867. (org-get-property-block nil t))
  14868. (throw 'skip nil))
  14869. (goto-char (car range))
  14870. (let ((begin (car range))
  14871. (end (cdr range)))
  14872. ;; Make sure that found property block is not located
  14873. ;; before current point, as it would generate an infloop.
  14874. ;; It can happen, for example, in the following
  14875. ;; situation:
  14876. ;;
  14877. ;; * Headline
  14878. ;; :PROPERTIES:
  14879. ;; ...
  14880. ;; :END:
  14881. ;; *************** Inlinetask
  14882. ;; #+BEGIN_EXAMPLE
  14883. ;; :PROPERTIES:
  14884. ;; #+END_EXAMPLE
  14885. ;;
  14886. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14887. (while (< (point) end)
  14888. (let ((p (progn (looking-at org-property-re)
  14889. (match-string-no-properties 2))))
  14890. ;; Only add true property name, not extension symbol.
  14891. (push (if (not (string-match-p "\\+\\'" p)) p
  14892. (substring p 0 -1))
  14893. props))
  14894. (forward-line))))
  14895. (outline-next-heading)))
  14896. (when columns
  14897. (goto-char (point-min))
  14898. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14899. (let ((element (org-element-at-point)))
  14900. (when (memq (org-element-type element) '(keyword node-property))
  14901. (let ((value (org-element-property :value element))
  14902. (start 0))
  14903. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14904. (setq start (match-end 0))
  14905. (let ((p (match-string-no-properties 1 value)))
  14906. (unless (member-ignore-case p org-special-properties)
  14907. (push p props))))))))))
  14908. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14909. (defun org-property-values (key)
  14910. "List all non-nil values of property KEY in current buffer."
  14911. (org-with-wide-buffer
  14912. (goto-char (point-min))
  14913. (let ((case-fold-search t)
  14914. (re (org-re-property key))
  14915. values)
  14916. (while (re-search-forward re nil t)
  14917. (push (org-entry-get (point) key) values))
  14918. (delete-dups values))))
  14919. (defun org-insert-property-drawer ()
  14920. "Insert a property drawer into the current entry."
  14921. (org-with-wide-buffer
  14922. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14923. (org-back-to-heading t)
  14924. (org-with-limited-levels (org-back-to-heading t)))
  14925. (forward-line)
  14926. (when (looking-at-p org-planning-line-re) (forward-line))
  14927. (unless (looking-at-p org-property-drawer-re)
  14928. ;; Make sure we start editing a line from current entry, not from
  14929. ;; next one. It prevents extending text properties or overlays
  14930. ;; belonging to the latter.
  14931. (when (bolp) (backward-char))
  14932. (let ((begin (1+ (point)))
  14933. (inhibit-read-only t))
  14934. (insert "\n:PROPERTIES:\n:END:")
  14935. (when (eobp) (insert "\n"))
  14936. (org-indent-region begin (point))))))
  14937. (defun org-insert-drawer (&optional arg drawer)
  14938. "Insert a drawer at point.
  14939. When optional argument ARG is non-nil, insert a property drawer.
  14940. Optional argument DRAWER, when non-nil, is a string representing
  14941. drawer's name. Otherwise, the user is prompted for a name.
  14942. If a region is active, insert the drawer around that region
  14943. instead.
  14944. Point is left between drawer's boundaries."
  14945. (interactive "P")
  14946. (let* ((drawer (if arg "PROPERTIES"
  14947. (or drawer (read-from-minibuffer "Drawer: ")))))
  14948. (cond
  14949. ;; With C-u, fall back on `org-insert-property-drawer'
  14950. (arg (org-insert-property-drawer))
  14951. ;; Check validity of suggested drawer's name.
  14952. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14953. (user-error "Invalid drawer name"))
  14954. ;; With an active region, insert a drawer at point.
  14955. ((not (org-region-active-p))
  14956. (progn
  14957. (unless (bolp) (insert "\n"))
  14958. (insert (format ":%s:\n\n:END:\n" drawer))
  14959. (forward-line -2)))
  14960. ;; Otherwise, insert the drawer at point
  14961. (t
  14962. (let ((rbeg (region-beginning))
  14963. (rend (copy-marker (region-end))))
  14964. (unwind-protect
  14965. (progn
  14966. (goto-char rbeg)
  14967. (beginning-of-line)
  14968. (when (save-excursion
  14969. (re-search-forward org-outline-regexp-bol rend t))
  14970. (user-error "Drawers cannot contain headlines"))
  14971. ;; Position point at the beginning of the first
  14972. ;; non-blank line in region. Insert drawer's opening
  14973. ;; there, then indent it.
  14974. (org-skip-whitespace)
  14975. (beginning-of-line)
  14976. (insert ":" drawer ":\n")
  14977. (forward-line -1)
  14978. (indent-for-tab-command)
  14979. ;; Move point to the beginning of the first blank line
  14980. ;; after the last non-blank line in region. Insert
  14981. ;; drawer's closing, then indent it.
  14982. (goto-char rend)
  14983. (skip-chars-backward " \r\t\n")
  14984. (insert "\n:END:")
  14985. (deactivate-mark t)
  14986. (indent-for-tab-command)
  14987. (unless (eolp) (insert "\n")))
  14988. ;; Clear marker, whatever the outcome of insertion is.
  14989. (set-marker rend nil)))))))
  14990. (defvar org-property-set-functions-alist nil
  14991. "Property set function alist.
  14992. Each entry should have the following format:
  14993. (PROPERTY . READ-FUNCTION)
  14994. The read function will be called with the same argument as
  14995. `org-completing-read'.")
  14996. (defun org-set-property-function (property)
  14997. "Get the function that should be used to set PROPERTY.
  14998. This is computed according to `org-property-set-functions-alist'."
  14999. (or (cdr (assoc property org-property-set-functions-alist))
  15000. 'org-completing-read))
  15001. (defun org-read-property-value (property)
  15002. "Read PROPERTY value from user."
  15003. (let* ((completion-ignore-case t)
  15004. (allowed (org-property-get-allowed-values nil property 'table))
  15005. (cur (org-entry-get nil property))
  15006. (prompt (concat property " value"
  15007. (if (and cur (string-match "\\S-" cur))
  15008. (concat " [" cur "]") "") ": "))
  15009. (set-function (org-set-property-function property))
  15010. (val (if allowed
  15011. (funcall set-function prompt allowed nil
  15012. (not (get-text-property 0 'org-unrestricted
  15013. (caar allowed))))
  15014. (funcall set-function prompt
  15015. (mapcar 'list (org-property-values property))
  15016. nil nil "" nil cur))))
  15017. (org-trim val)))
  15018. (defvar org-last-set-property nil)
  15019. (defvar org-last-set-property-value nil)
  15020. (defun org-read-property-name ()
  15021. "Read a property name."
  15022. (let ((completion-ignore-case t)
  15023. (default-prop (or (and (org-at-property-p)
  15024. (match-string-no-properties 2))
  15025. org-last-set-property)))
  15026. (org-completing-read
  15027. (concat "Property"
  15028. (if default-prop (concat " [" default-prop "]") "")
  15029. ": ")
  15030. (mapcar #'list (org-buffer-property-keys nil t t))
  15031. nil nil nil nil default-prop)))
  15032. (defun org-set-property-and-value (use-last)
  15033. "Allow to set [PROPERTY]: [value] direction from prompt.
  15034. When use-default, don't even ask, just use the last
  15035. \"[PROPERTY]: [value]\" string from the history."
  15036. (interactive "P")
  15037. (let* ((completion-ignore-case t)
  15038. (pv (or (and use-last org-last-set-property-value)
  15039. (org-completing-read
  15040. "Enter a \"[Property]: [value]\" pair: "
  15041. nil nil nil nil nil
  15042. org-last-set-property-value)))
  15043. prop val)
  15044. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  15045. (setq prop (match-string 1 pv)
  15046. val (match-string 2 pv))
  15047. (org-set-property prop val))))
  15048. (defun org-set-property (property value)
  15049. "In the current entry, set PROPERTY to VALUE.
  15050. When called interactively, this will prompt for a property name, offering
  15051. completion on existing and default properties. And then it will prompt
  15052. for a value, offering completion either on allowed values (via an inherited
  15053. xxx_ALL property) or on existing values in other instances of this property
  15054. in the current file.
  15055. Throw an error when trying to set a property with an invalid name."
  15056. (interactive (list nil nil))
  15057. (let ((property (or property (org-read-property-name))))
  15058. ;; `org-entry-put' also makes the following check, but this one
  15059. ;; avoids polluting `org-last-set-property' and
  15060. ;; `org-last-set-property-value' needlessly.
  15061. (unless (org--valid-property-p property)
  15062. (user-error "Invalid property name: \"%s\"" property))
  15063. (let ((value (or value (org-read-property-value property)))
  15064. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15065. (setq org-last-set-property property)
  15066. (setq org-last-set-property-value (concat property ": " value))
  15067. ;; Possibly postprocess the inserted value:
  15068. (when fn (setq value (funcall fn value)))
  15069. (unless (equal (org-entry-get nil property) value)
  15070. (org-entry-put nil property value)))))
  15071. (defun org-find-property (property &optional value)
  15072. "Find first entry in buffer that sets PROPERTY.
  15073. When optional argument VALUE is non-nil, only consider an entry
  15074. if it contains PROPERTY set to this value. If PROPERTY should be
  15075. explicitly set to nil, use string \"nil\" for VALUE.
  15076. Return position where the entry begins, or nil if there is no
  15077. such entry. If narrowing is in effect, only search the visible
  15078. part of the buffer."
  15079. (save-excursion
  15080. (goto-char (point-min))
  15081. (let ((case-fold-search t)
  15082. (re (org-re-property property nil (not value) value)))
  15083. (catch 'exit
  15084. (while (re-search-forward re nil t)
  15085. (when (if value (org-at-property-p)
  15086. (org-entry-get (point) property nil t))
  15087. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15088. (defun org-delete-property (property)
  15089. "In the current entry, delete PROPERTY."
  15090. (interactive
  15091. (let* ((completion-ignore-case t)
  15092. (cat (org-entry-get (point) "CATEGORY"))
  15093. (props0 (org-entry-properties nil 'standard))
  15094. (props (if cat props0
  15095. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15096. (prop (if (< 1 (length props))
  15097. (completing-read "Property: " props nil t)
  15098. (caar props))))
  15099. (list prop)))
  15100. (if (not property)
  15101. (message "No property to delete in this entry")
  15102. (org-entry-delete nil property)
  15103. (message "Property \"%s\" deleted" property)))
  15104. (defun org-delete-property-globally (property)
  15105. "Remove PROPERTY globally, from all entries.
  15106. This function ignores narrowing, if any."
  15107. (interactive
  15108. (let* ((completion-ignore-case t)
  15109. (prop (completing-read
  15110. "Globally remove property: "
  15111. (mapcar #'list (org-buffer-property-keys)))))
  15112. (list prop)))
  15113. (org-with-wide-buffer
  15114. (goto-char (point-min))
  15115. (let ((count 0)
  15116. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15117. (while (re-search-forward re nil t)
  15118. (when (org-entry-delete (point) property) (cl-incf count)))
  15119. (message "Property \"%s\" removed from %d entries" property count))))
  15120. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15121. (defun org-compute-property-at-point ()
  15122. "Compute the property at point.
  15123. This looks for an enclosing column format, extracts the operator and
  15124. then applies it to the property in the column format's scope."
  15125. (interactive)
  15126. (unless (org-at-property-p)
  15127. (user-error "Not at a property"))
  15128. (let ((prop (match-string-no-properties 2)))
  15129. (org-columns-get-format-and-top-level)
  15130. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15131. (user-error "No operator defined for property %s" prop))
  15132. (org-columns-compute prop)))
  15133. (defvar org-property-allowed-value-functions nil
  15134. "Hook for functions supplying allowed values for a specific property.
  15135. The functions must take a single argument, the name of the property, and
  15136. return a flat list of allowed values. If \":ETC\" is one of
  15137. the values, this means that these values are intended as defaults for
  15138. completion, but that other values should be allowed too.
  15139. The functions must return nil if they are not responsible for this
  15140. property.")
  15141. (defun org-property-get-allowed-values (pom property &optional table)
  15142. "Get allowed values for the property PROPERTY.
  15143. When TABLE is non-nil, return an alist that can directly be used for
  15144. completion."
  15145. (let (vals)
  15146. (cond
  15147. ((equal property "TODO")
  15148. (setq vals (org-with-point-at pom
  15149. (append org-todo-keywords-1 '("")))))
  15150. ((equal property "PRIORITY")
  15151. (let ((n org-lowest-priority))
  15152. (while (>= n org-highest-priority)
  15153. (push (char-to-string n) vals)
  15154. (setq n (1- n)))))
  15155. ((equal property "CATEGORY"))
  15156. ((member property org-special-properties))
  15157. ((setq vals (run-hook-with-args-until-success
  15158. 'org-property-allowed-value-functions property)))
  15159. (t
  15160. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15161. (when (and vals (string-match "\\S-" vals))
  15162. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15163. (setq vals (mapcar (lambda (x)
  15164. (cond ((stringp x) x)
  15165. ((numberp x) (number-to-string x))
  15166. ((symbolp x) (symbol-name x))
  15167. (t "???")))
  15168. vals)))))
  15169. (when (member ":ETC" vals)
  15170. (setq vals (remove ":ETC" vals))
  15171. (org-add-props (car vals) '(org-unrestricted t)))
  15172. (if table (mapcar 'list vals) vals)))
  15173. (defun org-property-previous-allowed-value (&optional _previous)
  15174. "Switch to the next allowed value for this property."
  15175. (interactive)
  15176. (org-property-next-allowed-value t))
  15177. (defun org-property-next-allowed-value (&optional previous)
  15178. "Switch to the next allowed value for this property."
  15179. (interactive)
  15180. (unless (org-at-property-p)
  15181. (user-error "Not at a property"))
  15182. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15183. (key (match-string 2))
  15184. (value (match-string 3))
  15185. (allowed (or (org-property-get-allowed-values (point) key)
  15186. (and (member value '("[ ]" "[-]" "[X]"))
  15187. '("[ ]" "[X]"))))
  15188. (heading (save-match-data (nth 4 (org-heading-components))))
  15189. nval)
  15190. (unless allowed
  15191. (user-error "Allowed values for this property have not been defined"))
  15192. (when previous (setq allowed (reverse allowed)))
  15193. (when (member value allowed)
  15194. (setq nval (car (cdr (member value allowed)))))
  15195. (setq nval (or nval (car allowed)))
  15196. (when (equal nval value)
  15197. (user-error "Only one allowed value for this property"))
  15198. (org-at-property-p)
  15199. (replace-match (concat " :" key ": " nval) t t)
  15200. (org-indent-line)
  15201. (beginning-of-line 1)
  15202. (skip-chars-forward " \t")
  15203. (when (equal prop org-effort-property)
  15204. (org-refresh-property
  15205. '((effort . identity)
  15206. (effort-minutes . org-duration-string-to-minutes))
  15207. nval)
  15208. (when (string= org-clock-current-task heading)
  15209. (setq org-clock-effort nval)
  15210. (org-clock-update-mode-line)))
  15211. (run-hook-with-args 'org-property-changed-functions key nval)))
  15212. (defun org-find-olp (path &optional this-buffer)
  15213. "Return a marker pointing to the entry at outline path OLP.
  15214. If anything goes wrong, throw an error.
  15215. You can wrap this call to catch the error like this:
  15216. \(condition-case msg
  15217. \(org-mobile-locate-entry (match-string 4))
  15218. \(error (nth 1 msg)))
  15219. The return value will then be either a string with the error message,
  15220. or a marker if everything is OK.
  15221. If THIS-BUFFER is set, the outline path does not contain a file,
  15222. only headings."
  15223. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15224. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15225. (level 1)
  15226. (lmin 1)
  15227. (lmax 1)
  15228. end found flevel)
  15229. (unless buffer (error "File not found :%s" file))
  15230. (with-current-buffer buffer
  15231. (org-with-wide-buffer
  15232. (goto-char (point-min))
  15233. (dolist (heading path)
  15234. (let ((re (format org-complex-heading-regexp-format
  15235. (regexp-quote heading)))
  15236. (cnt 0))
  15237. (while (re-search-forward re end t)
  15238. (setq level (- (match-end 1) (match-beginning 1)))
  15239. (when (and (>= level lmin) (<= level lmax))
  15240. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15241. (when (= cnt 0)
  15242. (error "Heading not found on level %d: %s" lmax heading))
  15243. (when (> cnt 1)
  15244. (error "Heading not unique on level %d: %s" lmax heading))
  15245. (goto-char found)
  15246. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15247. (setq end (save-excursion (org-end-of-subtree t t)))))
  15248. (when (org-at-heading-p)
  15249. (point-marker))))))
  15250. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15251. "Find node HEADING in BUFFER.
  15252. Return a marker to the heading if it was found, or nil if not.
  15253. If POS-ONLY is set, return just the position instead of a marker.
  15254. The heading text must match exact, but it may have a TODO keyword,
  15255. a priority cookie and tags in the standard locations."
  15256. (with-current-buffer (or buffer (current-buffer))
  15257. (save-excursion
  15258. (save-restriction
  15259. (widen)
  15260. (goto-char (point-min))
  15261. (let (case-fold-search)
  15262. (when (re-search-forward
  15263. (format org-complex-heading-regexp-format
  15264. (regexp-quote heading)) nil t)
  15265. (if pos-only
  15266. (match-beginning 0)
  15267. (move-marker (make-marker) (match-beginning 0)))))))))
  15268. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15269. "Find Org node headline HEADING in all .org files in directory DIR.
  15270. When the target headline is found, return a marker to this location."
  15271. (let ((files (directory-files (or dir default-directory)
  15272. t "\\`[^.#].*\\.org\\'"))
  15273. visiting m buffer)
  15274. (catch 'found
  15275. (dolist (file files)
  15276. (message "trying %s" file)
  15277. (setq visiting (org-find-base-buffer-visiting file))
  15278. (setq buffer (or visiting (find-file-noselect file)))
  15279. (setq m (org-find-exact-headline-in-buffer
  15280. heading buffer))
  15281. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15282. (and m (throw 'found m))))))
  15283. (defun org-find-entry-with-id (ident)
  15284. "Locate the entry that contains the ID property with exact value IDENT.
  15285. IDENT can be a string, a symbol or a number, this function will search for
  15286. the string representation of it.
  15287. Return the position where this entry starts, or nil if there is no such entry."
  15288. (interactive "sID: ")
  15289. (let ((id (cond
  15290. ((stringp ident) ident)
  15291. ((symbolp ident) (symbol-name ident))
  15292. ((numberp ident) (number-to-string ident))
  15293. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15294. (org-with-wide-buffer (org-find-property "ID" id))))
  15295. ;;;; Timestamps
  15296. (defvar org-last-changed-timestamp nil)
  15297. (defvar org-last-inserted-timestamp nil
  15298. "The last time stamp inserted with `org-insert-time-stamp'.")
  15299. (defvar org-ts-what) ; dynamically scoped parameter
  15300. (defun org-time-stamp (arg &optional inactive)
  15301. "Prompt for a date/time and insert a time stamp.
  15302. If the user specifies a time like HH:MM or if this command is
  15303. called with at least one prefix argument, the time stamp contains
  15304. the date and the time. Otherwise, only the date is included.
  15305. All parts of a date not specified by the user are filled in from
  15306. the timestamp at point, if any, or the current date/time
  15307. otherwise.
  15308. If there is already a timestamp at the cursor, it is replaced.
  15309. With two universal prefix arguments, insert an active timestamp
  15310. with the current time without prompting the user.
  15311. When called from lisp, the timestamp is inactive if INACTIVE is
  15312. non-nil."
  15313. (interactive "P")
  15314. (let* ((ts (cond
  15315. ((org-at-date-range-p t)
  15316. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15317. ((org-at-timestamp-p t) (match-string 0))))
  15318. ;; Default time is either the timestamp at point or today.
  15319. ;; When entering a range, only the range start is considered.
  15320. (default-time (if (not ts) (current-time)
  15321. (apply #'encode-time (org-parse-time-string ts))))
  15322. (default-input (and ts (org-get-compact-tod ts)))
  15323. (repeater (and ts
  15324. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15325. (match-string 0 ts)))
  15326. org-time-was-given
  15327. org-end-time-was-given
  15328. (time
  15329. (and (if (equal arg '(16)) (current-time)
  15330. ;; Preserve `this-command' and `last-command'.
  15331. (let ((this-command this-command)
  15332. (last-command last-command))
  15333. (org-read-date
  15334. arg 'totime nil nil default-time default-input
  15335. inactive))))))
  15336. (cond
  15337. ((and ts
  15338. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15339. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15340. (insert "--")
  15341. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15342. (ts
  15343. ;; Make sure we're on a timestamp. When in the middle of a date
  15344. ;; range, move arbitrarily to range end.
  15345. (unless (org-at-timestamp-p t)
  15346. (skip-chars-forward "-")
  15347. (org-at-timestamp-p t))
  15348. (replace-match "")
  15349. (setq org-last-changed-timestamp
  15350. (org-insert-time-stamp
  15351. time (or org-time-was-given arg)
  15352. inactive nil nil (list org-end-time-was-given)))
  15353. (when repeater
  15354. (backward-char)
  15355. (insert " " repeater)
  15356. (setq org-last-changed-timestamp
  15357. (concat (substring org-last-inserted-timestamp 0 -1)
  15358. " " repeater ">")))
  15359. (message "Timestamp updated"))
  15360. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15361. (t (org-insert-time-stamp
  15362. time (or org-time-was-given arg) inactive nil nil
  15363. (list org-end-time-was-given))))))
  15364. ;; FIXME: can we use this for something else, like computing time differences?
  15365. (defun org-get-compact-tod (s)
  15366. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15367. (let* ((t1 (match-string 1 s))
  15368. (h1 (string-to-number (match-string 2 s)))
  15369. (m1 (string-to-number (match-string 3 s)))
  15370. (t2 (and (match-end 4) (match-string 5 s)))
  15371. (h2 (and t2 (string-to-number (match-string 6 s))))
  15372. (m2 (and t2 (string-to-number (match-string 7 s))))
  15373. dh dm)
  15374. (if (not t2)
  15375. t1
  15376. (setq dh (- h2 h1) dm (- m2 m1))
  15377. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15378. (concat t1 "+" (number-to-string dh)
  15379. (and (/= 0 dm) (format ":%02d" dm)))))))
  15380. (defun org-time-stamp-inactive (&optional arg)
  15381. "Insert an inactive time stamp.
  15382. An inactive time stamp is enclosed in square brackets instead of angle
  15383. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15384. does not link to the calendar and cannot be changed with the S-cursor keys.
  15385. So these are more for recording a certain time/date."
  15386. (interactive "P")
  15387. (org-time-stamp arg 'inactive))
  15388. (defvar org-date-ovl (make-overlay 1 1))
  15389. (overlay-put org-date-ovl 'face 'org-date-selected)
  15390. (delete-overlay org-date-ovl)
  15391. (defvar org-ans1) ; dynamically scoped parameter
  15392. (defvar org-ans2) ; dynamically scoped parameter
  15393. (defvar org-plain-time-of-day-regexp) ; defined below
  15394. (defvar org-overriding-default-time nil) ; dynamically scoped
  15395. (defvar org-read-date-overlay nil)
  15396. (defvar org-dcst nil) ; dynamically scoped
  15397. (defvar org-read-date-history nil)
  15398. (defvar org-read-date-final-answer nil)
  15399. (defvar org-read-date-analyze-futurep nil)
  15400. (defvar org-read-date-analyze-forced-year nil)
  15401. (defvar org-read-date-inactive)
  15402. (defvar org-read-date-minibuffer-local-map
  15403. (let* ((map (make-sparse-keymap)))
  15404. (set-keymap-parent map minibuffer-local-map)
  15405. (org-defkey map (kbd ".")
  15406. (lambda () (interactive)
  15407. ;; Are we at the beginning of the prompt?
  15408. (if (looking-back "^[^:]+: "
  15409. (let ((inhibit-field-text-motion t))
  15410. (line-beginning-position)))
  15411. (org-eval-in-calendar '(calendar-goto-today))
  15412. (insert "."))))
  15413. (org-defkey map (kbd "C-.")
  15414. (lambda () (interactive)
  15415. (org-eval-in-calendar '(calendar-goto-today))))
  15416. (org-defkey map [(meta shift left)]
  15417. (lambda () (interactive)
  15418. (org-eval-in-calendar '(calendar-backward-month 1))))
  15419. (org-defkey map [(meta shift right)]
  15420. (lambda () (interactive)
  15421. (org-eval-in-calendar '(calendar-forward-month 1))))
  15422. (org-defkey map [(meta shift up)]
  15423. (lambda () (interactive)
  15424. (org-eval-in-calendar '(calendar-backward-year 1))))
  15425. (org-defkey map [(meta shift down)]
  15426. (lambda () (interactive)
  15427. (org-eval-in-calendar '(calendar-forward-year 1))))
  15428. (org-defkey map [?\e (shift left)]
  15429. (lambda () (interactive)
  15430. (org-eval-in-calendar '(calendar-backward-month 1))))
  15431. (org-defkey map [?\e (shift right)]
  15432. (lambda () (interactive)
  15433. (org-eval-in-calendar '(calendar-forward-month 1))))
  15434. (org-defkey map [?\e (shift up)]
  15435. (lambda () (interactive)
  15436. (org-eval-in-calendar '(calendar-backward-year 1))))
  15437. (org-defkey map [?\e (shift down)]
  15438. (lambda () (interactive)
  15439. (org-eval-in-calendar '(calendar-forward-year 1))))
  15440. (org-defkey map [(shift up)]
  15441. (lambda () (interactive)
  15442. (org-eval-in-calendar '(calendar-backward-week 1))))
  15443. (org-defkey map [(shift down)]
  15444. (lambda () (interactive)
  15445. (org-eval-in-calendar '(calendar-forward-week 1))))
  15446. (org-defkey map [(shift left)]
  15447. (lambda () (interactive)
  15448. (org-eval-in-calendar '(calendar-backward-day 1))))
  15449. (org-defkey map [(shift right)]
  15450. (lambda () (interactive)
  15451. (org-eval-in-calendar '(calendar-forward-day 1))))
  15452. (org-defkey map "!"
  15453. (lambda () (interactive)
  15454. (org-eval-in-calendar '(diary-view-entries))
  15455. (message "")))
  15456. (org-defkey map ">"
  15457. (lambda () (interactive)
  15458. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15459. (org-defkey map "<"
  15460. (lambda () (interactive)
  15461. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15462. (org-defkey map "\C-v"
  15463. (lambda () (interactive)
  15464. (org-eval-in-calendar
  15465. '(calendar-scroll-left-three-months 1))))
  15466. (org-defkey map "\M-v"
  15467. (lambda () (interactive)
  15468. (org-eval-in-calendar
  15469. '(calendar-scroll-right-three-months 1))))
  15470. map)
  15471. "Keymap for minibuffer commands when using `org-read-date'.")
  15472. (defvar org-def)
  15473. (defvar org-defdecode)
  15474. (defvar org-with-time)
  15475. (defvar calendar-setup) ; Dynamically scoped.
  15476. (defun org-read-date (&optional with-time to-time from-string prompt
  15477. default-time default-input inactive)
  15478. "Read a date, possibly a time, and make things smooth for the user.
  15479. The prompt will suggest to enter an ISO date, but you can also enter anything
  15480. which will at least partially be understood by `parse-time-string'.
  15481. Unrecognized parts of the date will default to the current day, month, year,
  15482. hour and minute. If this command is called to replace a timestamp at point,
  15483. or to enter the second timestamp of a range, the default time is taken
  15484. from the existing stamp. Furthermore, the command prefers the future,
  15485. so if you are giving a date where the year is not given, and the day-month
  15486. combination is already past in the current year, it will assume you
  15487. mean next year. For details, see the manual. A few examples:
  15488. 3-2-5 --> 2003-02-05
  15489. feb 15 --> currentyear-02-15
  15490. 2/15 --> currentyear-02-15
  15491. sep 12 9 --> 2009-09-12
  15492. 12:45 --> today 12:45
  15493. 22 sept 0:34 --> currentyear-09-22 0:34
  15494. 12 --> currentyear-currentmonth-12
  15495. Fri --> nearest Friday after today
  15496. -Tue --> last Tuesday
  15497. etc.
  15498. Furthermore you can specify a relative date by giving, as the *first* thing
  15499. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15500. change in days weeks, months, years.
  15501. With a single plus or minus, the date is relative to today. With a double
  15502. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15503. +4d --> four days from today
  15504. +4 --> same as above
  15505. +2w --> two weeks from today
  15506. ++5 --> five days from default date
  15507. The function understands only English month and weekday abbreviations.
  15508. While prompting, a calendar is popped up - you can also select the
  15509. date with the mouse (button 1). The calendar shows a period of three
  15510. months. To scroll it to other months, use the keys `>' and `<'.
  15511. If you don't like the calendar, turn it off with
  15512. (setq org-read-date-popup-calendar nil)
  15513. With optional argument TO-TIME, the date will immediately be converted
  15514. to an internal time.
  15515. With an optional argument WITH-TIME, the prompt will suggest to
  15516. also insert a time. Note that when WITH-TIME is not set, you can
  15517. still enter a time, and this function will inform the calling routine
  15518. about this change. The calling routine may then choose to change the
  15519. format used to insert the time stamp into the buffer to include the time.
  15520. With optional argument FROM-STRING, read from this string instead from
  15521. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15522. the time/date that is used for everything that is not specified by the
  15523. user."
  15524. (require 'parse-time)
  15525. (let* ((org-with-time with-time)
  15526. (org-time-stamp-rounding-minutes
  15527. (if (equal org-with-time '(16))
  15528. '(0 0)
  15529. org-time-stamp-rounding-minutes))
  15530. (org-dcst org-display-custom-times)
  15531. (ct (org-current-time))
  15532. (org-def (or org-overriding-default-time default-time ct))
  15533. (org-defdecode (decode-time org-def))
  15534. (cur-frame (selected-frame))
  15535. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15536. (calendar-setup
  15537. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15538. (calendar-move-hook nil)
  15539. (calendar-view-diary-initially-flag nil)
  15540. (calendar-view-holidays-initially-flag nil)
  15541. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15542. ;; Rationalize `org-def' and `org-defdecode', if required.
  15543. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15544. (setf (nth 2 org-defdecode) -1)
  15545. (setf (nth 1 org-defdecode) 59)
  15546. (setq org-def (apply #'encode-time org-defdecode))
  15547. (setq org-defdecode (decode-time org-def)))
  15548. (let* ((timestr (format-time-string
  15549. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15550. org-def))
  15551. (prompt (concat (if prompt (concat prompt " ") "")
  15552. (format "Date+time [%s]: " timestr))))
  15553. (cond
  15554. (from-string (setq ans from-string))
  15555. (org-read-date-popup-calendar
  15556. (save-excursion
  15557. (save-window-excursion
  15558. (calendar)
  15559. (when (eq calendar-setup 'calendar-only)
  15560. (setq cal-frame
  15561. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15562. (select-frame cal-frame))
  15563. (org-eval-in-calendar '(setq cursor-type nil) t)
  15564. (unwind-protect
  15565. (progn
  15566. (calendar-forward-day (- (time-to-days org-def)
  15567. (calendar-absolute-from-gregorian
  15568. (calendar-current-date))))
  15569. (org-eval-in-calendar nil t)
  15570. (let* ((old-map (current-local-map))
  15571. (map (copy-keymap calendar-mode-map))
  15572. (minibuffer-local-map
  15573. (copy-keymap org-read-date-minibuffer-local-map)))
  15574. (org-defkey map (kbd "RET") 'org-calendar-select)
  15575. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15576. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15577. (unwind-protect
  15578. (progn
  15579. (use-local-map map)
  15580. (setq org-read-date-inactive inactive)
  15581. (add-hook 'post-command-hook 'org-read-date-display)
  15582. (setq org-ans0
  15583. (read-string prompt
  15584. default-input
  15585. 'org-read-date-history
  15586. nil))
  15587. ;; org-ans0: from prompt
  15588. ;; org-ans1: from mouse click
  15589. ;; org-ans2: from calendar motion
  15590. (setq ans
  15591. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15592. (remove-hook 'post-command-hook 'org-read-date-display)
  15593. (use-local-map old-map)
  15594. (when org-read-date-overlay
  15595. (delete-overlay org-read-date-overlay)
  15596. (setq org-read-date-overlay nil)))))
  15597. (bury-buffer "*Calendar*")
  15598. (when cal-frame
  15599. (delete-frame cal-frame)
  15600. (select-frame-set-input-focus cur-frame))))))
  15601. (t ; Naked prompt only
  15602. (unwind-protect
  15603. (setq ans (read-string prompt default-input
  15604. 'org-read-date-history timestr))
  15605. (when org-read-date-overlay
  15606. (delete-overlay org-read-date-overlay)
  15607. (setq org-read-date-overlay nil))))))
  15608. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15609. (when org-read-date-analyze-forced-year
  15610. (message "Year was forced into %s"
  15611. (if org-read-date-force-compatible-dates
  15612. "compatible range (1970-2037)"
  15613. "range representable on this machine"))
  15614. (ding))
  15615. ;; One round trip to get rid of 34th of August and stuff like that....
  15616. (setq final (decode-time (apply 'encode-time final)))
  15617. (setq org-read-date-final-answer ans)
  15618. (if to-time
  15619. (apply 'encode-time final)
  15620. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15621. (format "%04d-%02d-%02d %02d:%02d"
  15622. (nth 5 final) (nth 4 final) (nth 3 final)
  15623. (nth 2 final) (nth 1 final))
  15624. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15625. (defun org-read-date-display ()
  15626. "Display the current date prompt interpretation in the minibuffer."
  15627. (when org-read-date-display-live
  15628. (when org-read-date-overlay
  15629. (delete-overlay org-read-date-overlay))
  15630. (when (minibufferp (current-buffer))
  15631. (save-excursion
  15632. (end-of-line 1)
  15633. (while (not (equal (buffer-substring
  15634. (max (point-min) (- (point) 4)) (point))
  15635. " "))
  15636. (insert " ")))
  15637. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15638. " " (or org-ans1 org-ans2)))
  15639. (org-end-time-was-given nil)
  15640. (f (org-read-date-analyze ans org-def org-defdecode))
  15641. (fmts (if org-dcst
  15642. org-time-stamp-custom-formats
  15643. org-time-stamp-formats))
  15644. (fmt (if (or org-with-time
  15645. (and (boundp 'org-time-was-given) org-time-was-given))
  15646. (cdr fmts)
  15647. (car fmts)))
  15648. (txt (format-time-string fmt (apply 'encode-time f)))
  15649. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15650. (txt (concat "=> " txt)))
  15651. (when (and org-end-time-was-given
  15652. (string-match org-plain-time-of-day-regexp txt))
  15653. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15654. org-end-time-was-given
  15655. (substring txt (match-end 0)))))
  15656. (when org-read-date-analyze-futurep
  15657. (setq txt (concat txt " (=>F)")))
  15658. (setq org-read-date-overlay
  15659. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15660. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15661. (defun org-read-date-analyze (ans def defdecode)
  15662. "Analyze the combined answer of the date prompt."
  15663. ;; FIXME: cleanup and comment
  15664. ;; Pass `current-time' result to `decode-time' (instead of calling
  15665. ;; without arguments) so that only `current-time' has to be
  15666. ;; overriden in tests.
  15667. (let ((org-def def)
  15668. (org-defdecode defdecode)
  15669. (nowdecode (decode-time (current-time)))
  15670. delta deltan deltaw deltadef year month day
  15671. hour minute second wday pm h2 m2 tl wday1
  15672. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15673. (setq org-read-date-analyze-futurep nil
  15674. org-read-date-analyze-forced-year nil)
  15675. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15676. (setq ans "+0"))
  15677. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15678. (setq ans (replace-match "" t t ans)
  15679. deltan (car delta)
  15680. deltaw (nth 1 delta)
  15681. deltadef (nth 2 delta)))
  15682. ;; Check if there is an iso week date in there. If yes, store the
  15683. ;; info and postpone interpreting it until the rest of the parsing
  15684. ;; is done.
  15685. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15686. (setq iso-year (when (match-end 1)
  15687. (org-small-year-to-year
  15688. (string-to-number (match-string 1 ans))))
  15689. iso-weekday (when (match-end 3)
  15690. (string-to-number (match-string 3 ans)))
  15691. iso-week (string-to-number (match-string 2 ans)))
  15692. (setq ans (replace-match "" t t ans)))
  15693. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15694. (when (string-match
  15695. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15696. (setq year (if (match-end 2)
  15697. (string-to-number (match-string 2 ans))
  15698. (progn (setq kill-year t)
  15699. (string-to-number (format-time-string "%Y"))))
  15700. month (string-to-number (match-string 3 ans))
  15701. day (string-to-number (match-string 4 ans)))
  15702. (setq year (org-small-year-to-year year))
  15703. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15704. t nil ans)))
  15705. ;; Help matching dotted european dates
  15706. (when (string-match
  15707. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15708. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15709. (setq kill-year t)
  15710. (string-to-number (format-time-string "%Y")))
  15711. day (string-to-number (match-string 1 ans))
  15712. month (string-to-number (match-string 2 ans))
  15713. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15714. t nil ans)))
  15715. ;; Help matching american dates, like 5/30 or 5/30/7
  15716. (when (string-match
  15717. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15718. (setq year (if (match-end 4)
  15719. (string-to-number (match-string 4 ans))
  15720. (progn (setq kill-year t)
  15721. (string-to-number (format-time-string "%Y"))))
  15722. month (string-to-number (match-string 1 ans))
  15723. day (string-to-number (match-string 2 ans)))
  15724. (setq year (org-small-year-to-year year))
  15725. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15726. t nil ans)))
  15727. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15728. ;; If there is a time with am/pm, and *no* time without it, we convert
  15729. ;; so that matching will be successful.
  15730. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15731. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15732. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15733. (setq hour (string-to-number (match-string 1 ans))
  15734. minute (if (match-end 3)
  15735. (string-to-number (match-string 3 ans))
  15736. 0)
  15737. pm (equal ?p
  15738. (string-to-char (downcase (match-string 4 ans)))))
  15739. (if (and (= hour 12) (not pm))
  15740. (setq hour 0)
  15741. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15742. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15743. t t ans))))
  15744. ;; Check if a time range is given as a duration
  15745. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15746. (setq hour (string-to-number (match-string 1 ans))
  15747. h2 (+ hour (string-to-number (match-string 3 ans)))
  15748. minute (string-to-number (match-string 2 ans))
  15749. m2 (+ minute (if (match-end 5) (string-to-number
  15750. (match-string 5 ans))0)))
  15751. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15752. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15753. t t ans)))
  15754. ;; Check if there is a time range
  15755. (when (boundp 'org-end-time-was-given)
  15756. (setq org-time-was-given nil)
  15757. (when (and (string-match org-plain-time-of-day-regexp ans)
  15758. (match-end 8))
  15759. (setq org-end-time-was-given (match-string 8 ans))
  15760. (setq ans (concat (substring ans 0 (match-beginning 7))
  15761. (substring ans (match-end 7))))))
  15762. (setq tl (parse-time-string ans)
  15763. day (or (nth 3 tl) (nth 3 org-defdecode))
  15764. month
  15765. (cond ((nth 4 tl))
  15766. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15767. ;; Day was specified. Make sure DAY+MONTH
  15768. ;; combination happens in the future.
  15769. ((nth 3 tl)
  15770. (setq futurep t)
  15771. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15772. (nth 4 nowdecode)))
  15773. (t (nth 4 org-defdecode)))
  15774. year
  15775. (cond ((and (not kill-year) (nth 5 tl)))
  15776. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15777. ;; Month was guessed in the future and is at least
  15778. ;; equal to NOWDECODE's. Fix year accordingly.
  15779. (futurep
  15780. (if (or (> month (nth 4 nowdecode))
  15781. (>= day (nth 3 nowdecode)))
  15782. (nth 5 nowdecode)
  15783. (1+ (nth 5 nowdecode))))
  15784. ;; Month was specified. Make sure MONTH+YEAR
  15785. ;; combination happens in the future.
  15786. ((nth 4 tl)
  15787. (setq futurep t)
  15788. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15789. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15790. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15791. (t (nth 5 nowdecode))))
  15792. (t (nth 5 org-defdecode)))
  15793. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15794. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15795. second (or (nth 0 tl) 0)
  15796. wday (nth 6 tl))
  15797. (when (and (eq org-read-date-prefer-future 'time)
  15798. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15799. (equal day (nth 3 nowdecode))
  15800. (equal month (nth 4 nowdecode))
  15801. (equal year (nth 5 nowdecode))
  15802. (nth 2 tl)
  15803. (or (< (nth 2 tl) (nth 2 nowdecode))
  15804. (and (= (nth 2 tl) (nth 2 nowdecode))
  15805. (nth 1 tl)
  15806. (< (nth 1 tl) (nth 1 nowdecode)))))
  15807. (setq day (1+ day)
  15808. futurep t))
  15809. ;; Special date definitions below
  15810. (cond
  15811. (iso-week
  15812. ;; There was an iso week
  15813. (require 'cal-iso)
  15814. (setq futurep nil)
  15815. (setq year (or iso-year year)
  15816. day (or iso-weekday wday 1)
  15817. wday nil ; to make sure that the trigger below does not match
  15818. iso-date (calendar-gregorian-from-absolute
  15819. (calendar-iso-to-absolute
  15820. (list iso-week day year))))
  15821. ; FIXME: Should we also push ISO weeks into the future?
  15822. ; (when (and org-read-date-prefer-future
  15823. ; (not iso-year)
  15824. ; (< (calendar-absolute-from-gregorian iso-date)
  15825. ; (time-to-days (current-time))))
  15826. ; (setq year (1+ year)
  15827. ; iso-date (calendar-gregorian-from-absolute
  15828. ; (calendar-iso-to-absolute
  15829. ; (list iso-week day year)))))
  15830. (setq month (car iso-date)
  15831. year (nth 2 iso-date)
  15832. day (nth 1 iso-date)))
  15833. (deltan
  15834. (setq futurep nil)
  15835. (unless deltadef
  15836. ;; Pass `current-time' result to `decode-time' (instead of
  15837. ;; calling without arguments) so that only `current-time' has
  15838. ;; to be overriden in tests.
  15839. (let ((now (decode-time (current-time))))
  15840. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15841. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15842. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15843. ((equal deltaw "m") (setq month (+ month deltan)))
  15844. ((equal deltaw "y") (setq year (+ year deltan)))))
  15845. ((and wday (not (nth 3 tl)))
  15846. ;; Weekday was given, but no day, so pick that day in the week
  15847. ;; on or after the derived date.
  15848. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15849. (unless (equal wday wday1)
  15850. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15851. (when (and (boundp 'org-time-was-given)
  15852. (nth 2 tl))
  15853. (setq org-time-was-given t))
  15854. (when (< year 100) (setq year (+ 2000 year)))
  15855. ;; Check of the date is representable
  15856. (if org-read-date-force-compatible-dates
  15857. (progn
  15858. (when (< year 1970)
  15859. (setq year 1970 org-read-date-analyze-forced-year t))
  15860. (when (> year 2037)
  15861. (setq year 2037 org-read-date-analyze-forced-year t)))
  15862. (condition-case nil
  15863. (ignore (encode-time second minute hour day month year))
  15864. (error
  15865. (setq year (nth 5 org-defdecode))
  15866. (setq org-read-date-analyze-forced-year t))))
  15867. (setq org-read-date-analyze-futurep futurep)
  15868. (list second minute hour day month year)))
  15869. (defvar parse-time-weekdays)
  15870. (defun org-read-date-get-relative (s today default)
  15871. "Check string S for special relative date string.
  15872. TODAY and DEFAULT are internal times, for today and for a default.
  15873. Return shift list (N what def-flag)
  15874. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15875. N is the number of WHATs to shift.
  15876. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15877. the DEFAULT date rather than TODAY."
  15878. (require 'parse-time)
  15879. (when (and
  15880. (string-match
  15881. (concat
  15882. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15883. "\\([0-9]+\\)?"
  15884. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15885. "\\([ \t]\\|$\\)") s)
  15886. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15887. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15888. (string-to-char (substring (match-string 1 s) -1))
  15889. ?+))
  15890. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15891. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15892. (what (if (match-end 3) (match-string 3 s) "d"))
  15893. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15894. (date (if rel default today))
  15895. (wday (nth 6 (decode-time date)))
  15896. delta)
  15897. (if wday1
  15898. (progn
  15899. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15900. (when (= delta 0) (setq delta 7))
  15901. (when (= dir ?-)
  15902. (setq delta (- delta 7))
  15903. (when (= delta 0) (setq delta -7)))
  15904. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15905. (list delta "d" rel))
  15906. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15907. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15908. "Turn a user-specified date into the internal representation.
  15909. The internal representation needed by the calendar is (month day year).
  15910. This is a wrapper to handle the brain-dead convention in calendar that
  15911. user function argument order change dependent on argument order."
  15912. (pcase calendar-date-style
  15913. (`american (list arg1 arg2 arg3))
  15914. (`european (list arg2 arg1 arg3))
  15915. (`iso (list arg2 arg3 arg1))))
  15916. (defun org-eval-in-calendar (form &optional keepdate)
  15917. "Eval FORM in the calendar window and return to current window.
  15918. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15919. (let ((sf (selected-frame))
  15920. (sw (selected-window)))
  15921. (select-window (get-buffer-window "*Calendar*" t))
  15922. (eval form)
  15923. (when (and (not keepdate) (calendar-cursor-to-date))
  15924. (let* ((date (calendar-cursor-to-date))
  15925. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15926. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15927. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15928. (select-window sw)
  15929. (select-frame-set-input-focus sf)))
  15930. (defun org-calendar-select ()
  15931. "Return to `org-read-date' with the date currently selected.
  15932. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15933. (interactive)
  15934. (when (calendar-cursor-to-date)
  15935. (let* ((date (calendar-cursor-to-date))
  15936. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15937. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15938. (when (active-minibuffer-window) (exit-minibuffer))))
  15939. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15940. "Insert a date stamp for the date given by the internal TIME.
  15941. See `format-time-string' for the format of TIME.
  15942. WITH-HM means use the stamp format that includes the time of the day.
  15943. INACTIVE means use square brackets instead of angular ones, so that the
  15944. stamp will not contribute to the agenda.
  15945. PRE and POST are optional strings to be inserted before and after the
  15946. stamp.
  15947. The command returns the inserted time stamp."
  15948. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15949. stamp)
  15950. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15951. (insert-before-markers (or pre ""))
  15952. (when (listp extra)
  15953. (setq extra (car extra))
  15954. (if (and (stringp extra)
  15955. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15956. (setq extra (format "-%02d:%02d"
  15957. (string-to-number (match-string 1 extra))
  15958. (string-to-number (match-string 2 extra))))
  15959. (setq extra nil)))
  15960. (when extra
  15961. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15962. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15963. (insert-before-markers (or post ""))
  15964. (setq org-last-inserted-timestamp stamp)))
  15965. (defun org-toggle-time-stamp-overlays ()
  15966. "Toggle the use of custom time stamp formats."
  15967. (interactive)
  15968. (setq org-display-custom-times (not org-display-custom-times))
  15969. (unless org-display-custom-times
  15970. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15971. (while (setq p (next-single-property-change p 'display))
  15972. (when (and (get-text-property p 'display)
  15973. (eq (get-text-property p 'face) 'org-date))
  15974. (remove-text-properties
  15975. p (setq p (next-single-property-change p 'display))
  15976. '(display t))))
  15977. (set-buffer-modified-p bmp)))
  15978. (org-restart-font-lock)
  15979. (setq org-table-may-need-update t)
  15980. (if org-display-custom-times
  15981. (message "Time stamps are overlaid with custom format")
  15982. (message "Time stamp overlays removed")))
  15983. (defun org-display-custom-time (beg end)
  15984. "Overlay modified time stamp format over timestamp between BEG and END."
  15985. (let* ((ts (buffer-substring beg end))
  15986. t1 w1 with-hm tf time str w2 (off 0))
  15987. (save-match-data
  15988. (setq t1 (org-parse-time-string ts t))
  15989. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15990. (setq off (- (match-end 0) (match-beginning 0)))))
  15991. (setq end (- end off))
  15992. (setq w1 (- end beg)
  15993. with-hm (and (nth 1 t1) (nth 2 t1))
  15994. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15995. time (org-fix-decoded-time t1)
  15996. str (org-add-props
  15997. (format-time-string
  15998. (substring tf 1 -1) (apply 'encode-time time))
  15999. nil 'mouse-face 'highlight)
  16000. w2 (length str))
  16001. (unless (= w2 w1)
  16002. (add-text-properties (1+ beg) (+ 2 beg)
  16003. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  16004. (put-text-property beg end 'display str)))
  16005. (defun org-fix-decoded-time (time)
  16006. "Set 0 instead of nil for the first 6 elements of time.
  16007. Don't touch the rest."
  16008. (let ((n 0))
  16009. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  16010. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  16011. "Difference between TIMESTAMP-STRING and now in days.
  16012. If SECONDS is non-nil, return the difference in seconds."
  16013. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  16014. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  16015. (funcall fdiff (current-time)))))
  16016. (defun org-deadline-close-p (timestamp-string &optional ndays)
  16017. "Is the time in TIMESTAMP-STRING close to the current date?"
  16018. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  16019. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  16020. (not (org-entry-is-done-p))))
  16021. (defun org-get-wdays (ts &optional delay zero-delay)
  16022. "Get the deadline lead time appropriate for timestring TS.
  16023. When DELAY is non-nil, get the delay time for scheduled items
  16024. instead of the deadline lead time. When ZERO-DELAY is non-nil
  16025. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  16026. don't try to find the delay cookie in the scheduled timestamp."
  16027. (let ((tv (if delay org-scheduled-delay-days
  16028. org-deadline-warning-days)))
  16029. (cond
  16030. ((or (and delay (< tv 0))
  16031. (and delay zero-delay (<= tv 0))
  16032. (and (not delay) (<= tv 0)))
  16033. ;; Enforce this value no matter what
  16034. (- tv))
  16035. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  16036. ;; lead time is specified.
  16037. (floor (* (string-to-number (match-string 1 ts))
  16038. (cdr (assoc (match-string 2 ts)
  16039. '(("d" . 1) ("w" . 7)
  16040. ("m" . 30.4) ("y" . 365.25)
  16041. ("h" . 0.041667)))))))
  16042. ;; go for the default.
  16043. (t tv))))
  16044. (defun org-calendar-select-mouse (ev)
  16045. "Return to `org-read-date' with the date currently selected.
  16046. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  16047. (interactive "e")
  16048. (mouse-set-point ev)
  16049. (when (calendar-cursor-to-date)
  16050. (let* ((date (calendar-cursor-to-date))
  16051. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  16052. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  16053. (when (active-minibuffer-window) (exit-minibuffer))))
  16054. (defun org-check-deadlines (ndays)
  16055. "Check if there are any deadlines due or past due.
  16056. A deadline is considered due if it happens within `org-deadline-warning-days'
  16057. days from today's date. If the deadline appears in an entry marked DONE,
  16058. it is not shown. The prefix arg NDAYS can be used to test that many
  16059. days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
  16060. (interactive "P")
  16061. (let* ((org-warn-days
  16062. (cond
  16063. ((equal ndays '(4)) 100000)
  16064. (ndays (prefix-numeric-value ndays))
  16065. (t (abs org-deadline-warning-days))))
  16066. (case-fold-search nil)
  16067. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16068. (callback
  16069. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16070. (message "%d deadlines past-due or due within %d days"
  16071. (org-occur regexp nil callback)
  16072. org-warn-days)))
  16073. (defsubst org-re-timestamp (type)
  16074. "Return a regexp for timestamp TYPE.
  16075. Allowed values for TYPE are:
  16076. all: all timestamps
  16077. active: only active timestamps (<...>)
  16078. inactive: only inactive timestamps ([...])
  16079. scheduled: only scheduled timestamps
  16080. deadline: only deadline timestamps
  16081. closed: only closed time-stamps
  16082. When TYPE is nil, fall back on returning a regexp that matches
  16083. both scheduled and deadline timestamps."
  16084. (cl-case type
  16085. (all org-ts-regexp-both)
  16086. (active org-ts-regexp)
  16087. (inactive org-ts-regexp-inactive)
  16088. (scheduled org-scheduled-time-regexp)
  16089. (deadline org-deadline-time-regexp)
  16090. (closed org-closed-time-regexp)
  16091. (otherwise
  16092. (concat "\\<"
  16093. (regexp-opt (list org-deadline-string org-scheduled-string))
  16094. " *<\\([^>]+\\)>"))))
  16095. (defun org-check-before-date (d)
  16096. "Check if there are deadlines or scheduled entries before date D."
  16097. (interactive (list (org-read-date)))
  16098. (let* ((case-fold-search nil)
  16099. (regexp (org-re-timestamp org-ts-type))
  16100. (ts-type org-ts-type)
  16101. (callback
  16102. (lambda ()
  16103. (let ((match (match-string 1)))
  16104. (and (if (memq ts-type '(active inactive all))
  16105. (eq (org-element-type (save-excursion
  16106. (backward-char)
  16107. (org-element-context)))
  16108. 'timestamp)
  16109. (org-at-planning-p))
  16110. (time-less-p
  16111. (org-time-string-to-time match)
  16112. (org-time-string-to-time d)))))))
  16113. (message "%d entries before %s"
  16114. (org-occur regexp nil callback)
  16115. d)))
  16116. (defun org-check-after-date (d)
  16117. "Check if there are deadlines or scheduled entries after date D."
  16118. (interactive (list (org-read-date)))
  16119. (let* ((case-fold-search nil)
  16120. (regexp (org-re-timestamp org-ts-type))
  16121. (ts-type org-ts-type)
  16122. (callback
  16123. (lambda ()
  16124. (let ((match (match-string 1)))
  16125. (and (if (memq ts-type '(active inactive all))
  16126. (eq (org-element-type (save-excursion
  16127. (backward-char)
  16128. (org-element-context)))
  16129. 'timestamp)
  16130. (org-at-planning-p))
  16131. (not (time-less-p
  16132. (org-time-string-to-time match)
  16133. (org-time-string-to-time d))))))))
  16134. (message "%d entries after %s"
  16135. (org-occur regexp nil callback)
  16136. d)))
  16137. (defun org-check-dates-range (start-date end-date)
  16138. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16139. (interactive (list (org-read-date nil nil nil "Range starts")
  16140. (org-read-date nil nil nil "Range end")))
  16141. (let ((case-fold-search nil)
  16142. (regexp (org-re-timestamp org-ts-type))
  16143. (callback
  16144. (let ((type org-ts-type))
  16145. (lambda ()
  16146. (let ((match (match-string 1)))
  16147. (and
  16148. (if (memq type '(active inactive all))
  16149. (eq (org-element-type (save-excursion
  16150. (backward-char)
  16151. (org-element-context)))
  16152. 'timestamp)
  16153. (org-at-planning-p))
  16154. (not (time-less-p
  16155. (org-time-string-to-time match)
  16156. (org-time-string-to-time start-date)))
  16157. (time-less-p
  16158. (org-time-string-to-time match)
  16159. (org-time-string-to-time end-date))))))))
  16160. (message "%d entries between %s and %s"
  16161. (org-occur regexp nil callback) start-date end-date)))
  16162. (defun org-evaluate-time-range (&optional to-buffer)
  16163. "Evaluate a time range by computing the difference between start and end.
  16164. Normally the result is just printed in the echo area, but with prefix arg
  16165. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16166. If the time range is actually in a table, the result is inserted into the
  16167. next column.
  16168. For time difference computation, a year is assumed to be exactly 365
  16169. days in order to avoid rounding problems."
  16170. (interactive "P")
  16171. (or
  16172. (org-clock-update-time-maybe)
  16173. (save-excursion
  16174. (unless (org-at-date-range-p t)
  16175. (goto-char (point-at-bol))
  16176. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16177. (unless (org-at-date-range-p t)
  16178. (user-error "Not at a time-stamp range, and none found in current line")))
  16179. (let* ((ts1 (match-string 1))
  16180. (ts2 (match-string 2))
  16181. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16182. (match-end (match-end 0))
  16183. (time1 (org-time-string-to-time ts1))
  16184. (time2 (org-time-string-to-time ts2))
  16185. (t1 (float-time time1))
  16186. (t2 (float-time time2))
  16187. (diff (abs (- t2 t1)))
  16188. (negative (< (- t2 t1) 0))
  16189. ;; (ys (floor (* 365 24 60 60)))
  16190. (ds (* 24 60 60))
  16191. (hs (* 60 60))
  16192. (fy "%dy %dd %02d:%02d")
  16193. (fy1 "%dy %dd")
  16194. (fd "%dd %02d:%02d")
  16195. (fd1 "%dd")
  16196. (fh "%02d:%02d")
  16197. y d h m align)
  16198. (if havetime
  16199. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16200. y 0
  16201. d (floor (/ diff ds)) diff (mod diff ds)
  16202. h (floor (/ diff hs)) diff (mod diff hs)
  16203. m (floor (/ diff 60)))
  16204. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16205. y 0
  16206. d (floor (+ (/ diff ds) 0.5))
  16207. h 0 m 0))
  16208. (if (not to-buffer)
  16209. (message "%s" (org-make-tdiff-string y d h m))
  16210. (if (org-at-table-p)
  16211. (progn
  16212. (goto-char match-end)
  16213. (setq align t)
  16214. (and (looking-at " *|") (goto-char (match-end 0))))
  16215. (goto-char match-end))
  16216. (when (looking-at
  16217. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16218. (replace-match ""))
  16219. (when negative (insert " -"))
  16220. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16221. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16222. (insert " " (format fh h m))))
  16223. (when align (org-table-align))
  16224. (message "Time difference inserted")))))
  16225. (defun org-make-tdiff-string (y d h m)
  16226. (let ((fmt "")
  16227. (l nil))
  16228. (when (> y 0)
  16229. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16230. (push y l))
  16231. (when (> d 0)
  16232. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16233. (push d l))
  16234. (when (> h 0)
  16235. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16236. (push h l))
  16237. (when (> m 0)
  16238. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16239. (push m l))
  16240. (apply 'format fmt (nreverse l))))
  16241. (defun org-time-string-to-time (s &optional buffer pos)
  16242. "Convert a timestamp string into internal time."
  16243. (condition-case errdata
  16244. (apply 'encode-time (org-parse-time-string s))
  16245. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16246. s (if (not (and buffer pos))
  16247. ""
  16248. (format-message " at %d in buffer `%s'" pos buffer))
  16249. (cdr errdata)))))
  16250. (defun org-time-string-to-seconds (s)
  16251. "Convert a timestamp string to a number of seconds."
  16252. (float-time (org-time-string-to-time s)))
  16253. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16254. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16255. "Convert time stamp S to an absolute day number.
  16256. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16257. stamp, get the closest date to DAYNR. If PREFER is
  16258. `past' (respectively `future') return a date past (respectively
  16259. after) or equal to DAYNR.
  16260. POS is the location of time stamp S, as a buffer position in
  16261. BUFFER.
  16262. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16263. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16264. signalled."
  16265. (cond
  16266. ((string-match "\\`%%\\((.*)\\)" s)
  16267. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16268. ;; only able to match individual dates. If it fails, raise an
  16269. ;; error.
  16270. (if (and daynr
  16271. (org-diary-sexp-entry
  16272. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16273. daynr
  16274. (signal 'org-diary-sexp-no-match (list s))))
  16275. ((and daynr show-all) (org-closest-date s daynr prefer))
  16276. (t (time-to-days
  16277. (condition-case errdata
  16278. (apply #'encode-time (org-parse-time-string s))
  16279. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16280. s
  16281. (if (not (and buffer pos)) ""
  16282. (format-message " at %d in buffer `%s'" pos buffer))
  16283. (cdr errdata))))))))
  16284. (defun org-days-to-iso-week (days)
  16285. "Return the iso week number."
  16286. (require 'cal-iso)
  16287. (car (calendar-iso-from-absolute days)))
  16288. (defun org-small-year-to-year (year)
  16289. "Convert 2-digit years into 4-digit years.
  16290. YEAR is expanded into one of the 30 next years, if possible, or
  16291. into a past one. Any year larger than 99 is returned unchanged."
  16292. (if (>= year 100) year
  16293. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16294. (century (/ current 100))
  16295. (offset (- year (% current 100))))
  16296. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16297. ((> offset -70) (+ (* century 100) year))
  16298. (t (+ (* (1+ century) 100) year))))))
  16299. (defun org-time-from-absolute (d)
  16300. "Return the time corresponding to date D.
  16301. D may be an absolute day number, or a calendar-type list (month day year)."
  16302. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16303. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16304. (defvar org-agenda-current-date)
  16305. (defun org-calendar-holiday ()
  16306. "List of holidays, for Diary display in Org mode."
  16307. (require 'holidays)
  16308. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16309. (and hl (mapconcat #'identity hl "; "))))
  16310. (defun org-diary-sexp-entry (sexp entry d)
  16311. "Process a SEXP diary ENTRY for date D."
  16312. (require 'diary-lib)
  16313. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16314. ;; dynamically.
  16315. (let* ((sexp `(let ((entry ,entry)
  16316. (date ',d))
  16317. ,(car (read-from-string sexp))))
  16318. (result (if calendar-debug-sexp (eval sexp)
  16319. (condition-case nil
  16320. (eval sexp)
  16321. (error
  16322. (beep)
  16323. (message "Bad sexp at line %d in %s: %s"
  16324. (org-current-line)
  16325. (buffer-file-name) sexp)
  16326. (sleep-for 2))))))
  16327. (cond ((stringp result) (split-string result "; "))
  16328. ((and (consp result)
  16329. (not (consp (cdr result)))
  16330. (stringp (cdr result))) (cdr result))
  16331. ((and (consp result)
  16332. (stringp (car result))) result)
  16333. (result entry))))
  16334. (defun org-diary-to-ical-string (frombuf)
  16335. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16336. This uses the icalendar.el library."
  16337. (let* ((tmpdir temporary-file-directory)
  16338. (tmpfile (make-temp-name
  16339. (expand-file-name "orgics" tmpdir)))
  16340. buf rtn b e)
  16341. (with-current-buffer frombuf
  16342. (icalendar-export-region (point-min) (point-max) tmpfile)
  16343. (setq buf (find-buffer-visiting tmpfile))
  16344. (set-buffer buf)
  16345. (goto-char (point-min))
  16346. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16347. (setq b (match-beginning 0)))
  16348. (goto-char (point-max))
  16349. (when (re-search-backward "^END:VEVENT" nil t)
  16350. (setq e (match-end 0)))
  16351. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16352. (kill-buffer buf)
  16353. (delete-file tmpfile)
  16354. rtn))
  16355. (defun org-closest-date (start current prefer)
  16356. "Return closest date to CURRENT starting from START.
  16357. CURRENT and START are both time stamps.
  16358. When PREFER is `past', return a date that is either CURRENT or
  16359. past. When PREFER is `future', return a date that is either
  16360. CURRENT or future.
  16361. Only time stamps with a repeater are modified. Any other time
  16362. stamp stay unchanged. In any case, return value is an absolute
  16363. day number."
  16364. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16365. ;; No repeater. Do not shift time stamp.
  16366. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16367. (let ((value (string-to-number (match-string 1 start)))
  16368. (type (match-string 2 start)))
  16369. (if (= 0 value)
  16370. ;; Repeater with a 0-value is considered as void.
  16371. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16372. (let* ((base (org-date-to-gregorian start))
  16373. (target (org-date-to-gregorian current))
  16374. (sday (calendar-absolute-from-gregorian base))
  16375. (cday (calendar-absolute-from-gregorian target))
  16376. n1 n2)
  16377. ;; If START is already past CURRENT, just return START.
  16378. (if (<= cday sday) sday
  16379. ;; Compute closest date before (N1) and closest date past
  16380. ;; (N2) CURRENT.
  16381. (pcase type
  16382. ("h"
  16383. (let ((missing-hours
  16384. (mod (+ (- (* 24 (- cday sday))
  16385. (nth 2 (org-parse-time-string start)))
  16386. org-extend-today-until)
  16387. value)))
  16388. (setf n1 (if (= missing-hours 0) cday
  16389. (- cday (1+ (/ missing-hours 24)))))
  16390. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16391. ((or "d" "w")
  16392. (let ((value (if (equal type "w") (* 7 value) value)))
  16393. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16394. (setf n2 (+ n1 value))))
  16395. ("m"
  16396. (let* ((add-months
  16397. (lambda (d n)
  16398. ;; Add N months to gregorian date D, i.e.,
  16399. ;; a list (MONTH DAY YEAR). Return a valid
  16400. ;; gregorian date.
  16401. (let ((m (+ (nth 0 d) n)))
  16402. (list (mod m 12)
  16403. (nth 1 d)
  16404. (+ (/ m 12) (nth 2 d))))))
  16405. (months ; Complete months to TARGET.
  16406. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16407. (- (nth 0 target) (nth 0 base))
  16408. ;; If START's day is greater than
  16409. ;; TARGET's, remove incomplete month.
  16410. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16411. value)
  16412. value))
  16413. (before (funcall add-months base months)))
  16414. (setf n1 (calendar-absolute-from-gregorian before))
  16415. (setf n2
  16416. (calendar-absolute-from-gregorian
  16417. (funcall add-months before value)))))
  16418. (_
  16419. (let* ((d (nth 1 base))
  16420. (m (nth 0 base))
  16421. (y (nth 2 base))
  16422. (years ; Complete years to TARGET.
  16423. (* (/ (- (nth 2 target)
  16424. y
  16425. ;; If START's month and day are
  16426. ;; greater than TARGET's, remove
  16427. ;; incomplete year.
  16428. (if (or (> (nth 0 target) m)
  16429. (and (= (nth 0 target) m)
  16430. (> (nth 1 target) d)))
  16431. 0
  16432. 1))
  16433. value)
  16434. value))
  16435. (before (list m d (+ y years))))
  16436. (setf n1 (calendar-absolute-from-gregorian before))
  16437. (setf n2 (calendar-absolute-from-gregorian
  16438. (list m d (+ (nth 2 before) value)))))))
  16439. ;; Handle PREFER parameter, if any.
  16440. (cond
  16441. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16442. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16443. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16444. (defun org-date-to-gregorian (d)
  16445. "Turn any specification of date D into a Gregorian date for the calendar."
  16446. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16447. ((and (listp d) (= (length d) 3)) d)
  16448. ((stringp d)
  16449. (let ((d (org-parse-time-string d)))
  16450. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16451. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16452. (defun org-parse-time-string (s &optional nodefault)
  16453. "Parse the standard Org time string.
  16454. This should be a lot faster than the normal `parse-time-string'.
  16455. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16456. hour and minute fields will be nil if not given."
  16457. (cond ((string-match org-ts-regexp0 s)
  16458. (list 0
  16459. (when (or (match-beginning 8) (not nodefault))
  16460. (string-to-number (or (match-string 8 s) "0")))
  16461. (when (or (match-beginning 7) (not nodefault))
  16462. (string-to-number (or (match-string 7 s) "0")))
  16463. (string-to-number (match-string 4 s))
  16464. (string-to-number (match-string 3 s))
  16465. (string-to-number (match-string 2 s))
  16466. nil nil nil))
  16467. ((string-match "^<[^>]+>$" s)
  16468. (decode-time (seconds-to-time (org-matcher-time s))))
  16469. (t (error "Not a standard Org time string: %s" s))))
  16470. (defun org-timestamp-up (&optional arg)
  16471. "Increase the date item at the cursor by one.
  16472. If the cursor is on the year, change the year. If it is on the month,
  16473. the day or the time, change that.
  16474. With prefix ARG, change by that many units."
  16475. (interactive "p")
  16476. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16477. (defun org-timestamp-down (&optional arg)
  16478. "Decrease the date item at the cursor by one.
  16479. If the cursor is on the year, change the year. If it is on the month,
  16480. the day or the time, change that.
  16481. With prefix ARG, change by that many units."
  16482. (interactive "p")
  16483. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16484. (defun org-timestamp-up-day (&optional arg)
  16485. "Increase the date in the time stamp by one day.
  16486. With prefix ARG, change that many days."
  16487. (interactive "p")
  16488. (if (and (not (org-at-timestamp-p t))
  16489. (org-at-heading-p))
  16490. (org-todo 'up)
  16491. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16492. (defun org-timestamp-down-day (&optional arg)
  16493. "Decrease the date in the time stamp by one day.
  16494. With prefix ARG, change that many days."
  16495. (interactive "p")
  16496. (if (and (not (org-at-timestamp-p t))
  16497. (org-at-heading-p))
  16498. (org-todo 'down)
  16499. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16500. (defun org-at-timestamp-p (&optional inactive-ok)
  16501. "Non-nil if point is inside a timestamp.
  16502. When optional argument INACTIVE-OK is non-nil, also consider
  16503. inactive timestamps.
  16504. When this function returns a non-nil value, match data is set
  16505. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16506. INACTIVE-OK."
  16507. (interactive)
  16508. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16509. (pos (point))
  16510. (ans (or (looking-at tsr)
  16511. (save-excursion
  16512. (skip-chars-backward "^[<\n\r\t")
  16513. (when (> (point) (point-min)) (backward-char 1))
  16514. (and (looking-at tsr)
  16515. (> (- (match-end 0) pos) -1))))))
  16516. (and ans
  16517. (boundp 'org-ts-what)
  16518. (setq org-ts-what
  16519. (cond
  16520. ((= pos (match-beginning 0)) 'bracket)
  16521. ;; Point is considered to be "on the bracket" whether
  16522. ;; it's really on it or right after it.
  16523. ((= pos (1- (match-end 0))) 'bracket)
  16524. ((= pos (match-end 0)) 'after)
  16525. ((org-pos-in-match-range pos 2) 'year)
  16526. ((org-pos-in-match-range pos 3) 'month)
  16527. ((org-pos-in-match-range pos 7) 'hour)
  16528. ((org-pos-in-match-range pos 8) 'minute)
  16529. ((or (org-pos-in-match-range pos 4)
  16530. (org-pos-in-match-range pos 5)) 'day)
  16531. ((and (> pos (or (match-end 8) (match-end 5)))
  16532. (< pos (match-end 0)))
  16533. (- pos (or (match-end 8) (match-end 5))))
  16534. (t 'day))))
  16535. ans))
  16536. (defun org-toggle-timestamp-type ()
  16537. "Toggle the type (<active> or [inactive]) of a time stamp."
  16538. (interactive)
  16539. (when (org-at-timestamp-p t)
  16540. (let ((beg (match-beginning 0)) (end (match-end 0))
  16541. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16542. (save-excursion
  16543. (goto-char beg)
  16544. (while (re-search-forward "[][<>]" end t)
  16545. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16546. t t)))
  16547. (message "Timestamp is now %sactive"
  16548. (if (equal (char-after beg) ?<) "" "in")))))
  16549. (defun org-at-clock-log-p nil
  16550. "Is the cursor on the clock log line?"
  16551. (save-excursion
  16552. (move-beginning-of-line 1)
  16553. (looking-at org-clock-line-re)))
  16554. (defvar org-clock-history) ; defined in org-clock.el
  16555. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16556. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16557. "Change the date in the time stamp at point.
  16558. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16559. `year', `minute', `second'. If WHAT is not given, the cursor position
  16560. in the timestamp determines what will be changed.
  16561. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16562. (let ((origin (point)) origin-cat
  16563. with-hm inactive
  16564. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16565. org-ts-what
  16566. extra rem
  16567. ts time time0 fixnext clrgx)
  16568. (unless (org-at-timestamp-p t)
  16569. (user-error "Not at a timestamp"))
  16570. (if (and (not what) (eq org-ts-what 'bracket))
  16571. (org-toggle-timestamp-type)
  16572. ;; Point isn't on brackets. Remember the part of the time-stamp
  16573. ;; the point was in. Indeed, size of time-stamps may change,
  16574. ;; but point must be kept in the same category nonetheless.
  16575. (setq origin-cat org-ts-what)
  16576. (when (and (not what) (not (eq org-ts-what 'day))
  16577. org-display-custom-times
  16578. (get-text-property (point) 'display)
  16579. (not (get-text-property (1- (point)) 'display)))
  16580. (setq org-ts-what 'day))
  16581. (setq org-ts-what (or what org-ts-what)
  16582. inactive (= (char-after (match-beginning 0)) ?\[)
  16583. ts (match-string 0))
  16584. (replace-match "")
  16585. (when (string-match
  16586. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16587. ts)
  16588. (setq extra (match-string 1 ts))
  16589. (when suppress-tmp-delay
  16590. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16591. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16592. (setq with-hm t))
  16593. (setq time0 (org-parse-time-string ts))
  16594. (when (and updown
  16595. (eq org-ts-what 'minute)
  16596. (not current-prefix-arg))
  16597. ;; This looks like s-up and s-down. Change by one rounding step.
  16598. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16599. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16600. (setcar (cdr time0) (+ (nth 1 time0)
  16601. (if (> n 0) (- rem) (- dm rem))))))
  16602. (setq time
  16603. (apply #'encode-time
  16604. (or (car time0) 0)
  16605. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16606. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16607. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16608. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16609. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16610. (nthcdr 6 time0)))
  16611. (when (and (member org-ts-what '(hour minute))
  16612. extra
  16613. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16614. (setq extra (org-modify-ts-extra
  16615. extra
  16616. (if (eq org-ts-what 'hour) 2 5)
  16617. n dm)))
  16618. (when (integerp org-ts-what)
  16619. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16620. (when (eq what 'calendar)
  16621. (let ((cal-date (org-get-date-from-calendar)))
  16622. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16623. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16624. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16625. (setcar time0 (or (car time0) 0))
  16626. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16627. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16628. (setq time (apply 'encode-time time0))))
  16629. ;; Insert the new time-stamp, and ensure point stays in the same
  16630. ;; category as before (i.e. not after the last position in that
  16631. ;; category).
  16632. (let ((pos (point)))
  16633. ;; Stay before inserted string. `save-excursion' is of no use.
  16634. (setq org-last-changed-timestamp
  16635. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16636. (goto-char pos))
  16637. (save-match-data
  16638. (looking-at org-ts-regexp3)
  16639. (goto-char (cond
  16640. ;; `day' category ends before `hour' if any, or at
  16641. ;; the end of the day name.
  16642. ((eq origin-cat 'day)
  16643. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16644. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16645. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16646. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16647. ;; `year' and `month' have both fixed size: point
  16648. ;; couldn't have moved into another part.
  16649. (t origin))))
  16650. ;; Update clock if on a CLOCK line.
  16651. (org-clock-update-time-maybe)
  16652. ;; Maybe adjust the closest clock in `org-clock-history'
  16653. (when org-clock-adjust-closest
  16654. (if (not (and (org-at-clock-log-p)
  16655. (< 1 (length (delq nil (mapcar 'marker-position
  16656. org-clock-history))))))
  16657. (message "No clock to adjust")
  16658. (cond ((save-excursion ; fix previous clock?
  16659. (re-search-backward org-ts-regexp0 nil t)
  16660. (looking-back (concat org-clock-string " \\[")
  16661. (line-beginning-position)))
  16662. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16663. ((save-excursion ; fix next clock?
  16664. (re-search-backward org-ts-regexp0 nil t)
  16665. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16666. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16667. (save-window-excursion
  16668. ;; Find closest clock to point, adjust the previous/next one in history
  16669. (let* ((p (save-excursion (org-back-to-heading t)))
  16670. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16671. (clfixnth
  16672. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16673. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16674. (if (not clfixpos)
  16675. (message "No clock to adjust")
  16676. (save-excursion
  16677. (org-goto-marker-or-bmk clfixpos)
  16678. (org-show-subtree)
  16679. (when (re-search-forward clrgx nil t)
  16680. (goto-char (match-beginning 1))
  16681. (let (org-clock-adjust-closest)
  16682. (org-timestamp-change n org-ts-what updown))
  16683. (message "Clock adjusted in %s for heading: %s"
  16684. (file-name-nondirectory (buffer-file-name))
  16685. (org-get-heading t t)))))))))
  16686. ;; Try to recenter the calendar window, if any.
  16687. (when (and org-calendar-follow-timestamp-change
  16688. (get-buffer-window "*Calendar*" t)
  16689. (memq org-ts-what '(day month year)))
  16690. (org-recenter-calendar (time-to-days time))))))
  16691. (defun org-modify-ts-extra (s pos n dm)
  16692. "Change the different parts of the lead-time and repeat fields in timestamp."
  16693. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16694. ng h m new rem)
  16695. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16696. (cond
  16697. ((or (org-pos-in-match-range pos 2)
  16698. (org-pos-in-match-range pos 3))
  16699. (setq m (string-to-number (match-string 3 s))
  16700. h (string-to-number (match-string 2 s)))
  16701. (if (org-pos-in-match-range pos 2)
  16702. (setq h (+ h n))
  16703. (setq n (* dm (with-no-warnings (signum n))))
  16704. (unless (= 0 (setq rem (% m dm)))
  16705. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16706. (setq m (+ m n)))
  16707. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16708. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16709. (setq h (mod h 24))
  16710. (setq ng 1 new (format "-%02d:%02d" h m)))
  16711. ((org-pos-in-match-range pos 6)
  16712. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16713. ((org-pos-in-match-range pos 5)
  16714. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16715. ((org-pos-in-match-range pos 9)
  16716. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16717. ((org-pos-in-match-range pos 8)
  16718. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16719. (when ng
  16720. (setq s (concat
  16721. (substring s 0 (match-beginning ng))
  16722. new
  16723. (substring s (match-end ng))))))
  16724. s))
  16725. (defun org-recenter-calendar (d)
  16726. "If the calendar is visible, recenter it to date D."
  16727. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16728. (when cwin
  16729. (let ((calendar-move-hook nil))
  16730. (with-selected-window cwin
  16731. (calendar-goto-date
  16732. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16733. (defun org-goto-calendar (&optional arg)
  16734. "Go to the Emacs calendar at the current date.
  16735. If there is a time stamp in the current line, go to that date.
  16736. A prefix ARG can be used to force the current date."
  16737. (interactive "P")
  16738. (let ((tsr org-ts-regexp) diff
  16739. (calendar-move-hook nil)
  16740. (calendar-view-holidays-initially-flag nil)
  16741. (calendar-view-diary-initially-flag nil))
  16742. (when (or (org-at-timestamp-p)
  16743. (save-excursion
  16744. (beginning-of-line 1)
  16745. (looking-at (concat ".*" tsr))))
  16746. (let ((d1 (time-to-days (current-time)))
  16747. (d2 (time-to-days
  16748. (org-time-string-to-time (match-string 1)))))
  16749. (setq diff (- d2 d1))))
  16750. (calendar)
  16751. (calendar-goto-today)
  16752. (when (and diff (not arg)) (calendar-forward-day diff))))
  16753. (defun org-get-date-from-calendar ()
  16754. "Return a list (month day year) of date at point in calendar."
  16755. (with-current-buffer "*Calendar*"
  16756. (save-match-data
  16757. (calendar-cursor-to-date))))
  16758. (defun org-date-from-calendar ()
  16759. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16760. If there is already a time stamp at the cursor position, update it."
  16761. (interactive)
  16762. (if (org-at-timestamp-p t)
  16763. (org-timestamp-change 0 'calendar)
  16764. (let ((cal-date (org-get-date-from-calendar)))
  16765. (org-insert-time-stamp
  16766. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16767. (defcustom org-effort-durations
  16768. `(("min" . 1)
  16769. ("h" . 60)
  16770. ("d" . ,(* 60 8))
  16771. ("w" . ,(* 60 8 5))
  16772. ("m" . ,(* 60 8 5 4))
  16773. ("y" . ,(* 60 8 5 40)))
  16774. "Conversion factor to minutes for an effort modifier.
  16775. Each entry has the form (MODIFIER . MINUTES).
  16776. In an effort string, a number followed by MODIFIER is multiplied
  16777. by the specified number of MINUTES to obtain an effort in
  16778. minutes.
  16779. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16780. effort string \"2hours\" is equivalent to 120 minutes."
  16781. :group 'org-agenda
  16782. :version "25.1"
  16783. :package-version '(Org . "8.3")
  16784. :type '(alist :key-type (string :tag "Modifier")
  16785. :value-type (number :tag "Minutes")))
  16786. (defun org-minutes-to-clocksum-string (m)
  16787. "Format number of minutes as a clocksum string.
  16788. The format is determined by `org-time-clocksum-format',
  16789. `org-time-clocksum-use-fractional' and
  16790. `org-time-clocksum-fractional-format' and
  16791. `org-time-clocksum-use-effort-durations'."
  16792. (let ((clocksum "")
  16793. (m (round m)) ; Don't allow fractions of minutes
  16794. h d w mo y fmt n)
  16795. (setq h (if org-time-clocksum-use-effort-durations
  16796. (cdr (assoc "h" org-effort-durations)) 60)
  16797. d (if org-time-clocksum-use-effort-durations
  16798. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16799. w (if org-time-clocksum-use-effort-durations
  16800. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16801. mo (if org-time-clocksum-use-effort-durations
  16802. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16803. y (if org-time-clocksum-use-effort-durations
  16804. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16805. ;; fractional format
  16806. (if org-time-clocksum-use-fractional
  16807. (cond
  16808. ;; single format string
  16809. ((stringp org-time-clocksum-fractional-format)
  16810. (format org-time-clocksum-fractional-format (/ m (float h))))
  16811. ;; choice of fractional formats for different time units
  16812. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16813. (> (/ (truncate m) (* y d h)) 0))
  16814. (format fmt (/ m (* y d (float h)))))
  16815. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16816. (> (/ (truncate m) (* mo d h)) 0))
  16817. (format fmt (/ m (* mo d (float h)))))
  16818. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16819. (> (/ (truncate m) (* w d h)) 0))
  16820. (format fmt (/ m (* w d (float h)))))
  16821. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16822. (> (/ (truncate m) (* d h)) 0))
  16823. (format fmt (/ m (* d (float h)))))
  16824. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16825. (> (/ (truncate m) h) 0))
  16826. (format fmt (/ m (float h))))
  16827. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16828. (format fmt m))
  16829. ;; fall back to smallest time unit with a format
  16830. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16831. (format fmt (/ m (float h))))
  16832. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16833. (format fmt (/ m (* d (float h)))))
  16834. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16835. (format fmt (/ m (* w d (float h)))))
  16836. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16837. (format fmt (/ m (* mo d (float h)))))
  16838. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16839. (format fmt (/ m (* y d (float h))))))
  16840. ;; standard (non-fractional) format, with single format string
  16841. (if (stringp org-time-clocksum-format)
  16842. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16843. ;; separate formats components
  16844. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16845. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16846. (plist-get org-time-clocksum-format :require-years))
  16847. (setq clocksum (concat clocksum (format fmt n))
  16848. m (- m (* n y d h))))
  16849. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16850. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16851. (plist-get org-time-clocksum-format :require-months))
  16852. (setq clocksum (concat clocksum (format fmt n))
  16853. m (- m (* n mo d h))))
  16854. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16855. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16856. (plist-get org-time-clocksum-format :require-weeks))
  16857. (setq clocksum (concat clocksum (format fmt n))
  16858. m (- m (* n w d h))))
  16859. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16860. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16861. (plist-get org-time-clocksum-format :require-days))
  16862. (setq clocksum (concat clocksum (format fmt n))
  16863. m (- m (* n d h))))
  16864. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16865. (or (> (setq n (/ (truncate m) h)) 0)
  16866. (plist-get org-time-clocksum-format :require-hours))
  16867. (setq clocksum (concat clocksum (format fmt n))
  16868. m (- m (* n h))))
  16869. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16870. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16871. (setq clocksum (concat clocksum (format fmt m))))
  16872. ;; return formatted time duration
  16873. clocksum))))
  16874. (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
  16875. (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
  16876. "Org mode version 8.0")
  16877. (defun org-hours-to-clocksum-string (n)
  16878. (org-minutes-to-clocksum-string (* n 60)))
  16879. (defun org-hh:mm-string-to-minutes (s)
  16880. "Convert a string H:MM to a number of minutes.
  16881. If the string is just a number, interpret it as minutes.
  16882. In fact, the first hh:mm or number in the string will be taken,
  16883. there can be extra stuff in the string.
  16884. If no number is found, the return value is 0."
  16885. (cond
  16886. ((integerp s) s)
  16887. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16888. (+ (* (string-to-number (match-string 1 s)) 60)
  16889. (string-to-number (match-string 2 s))))
  16890. ((string-match "\\([0-9]+\\)" s)
  16891. (string-to-number (match-string 1 s)))
  16892. (t 0)))
  16893. (defcustom org-image-actual-width t
  16894. "Should we use the actual width of images when inlining them?
  16895. When set to t, always use the image width.
  16896. When set to a number, use imagemagick (when available) to set
  16897. the image's width to this value.
  16898. When set to a number in a list, try to get the width from any
  16899. #+ATTR.* keyword if it matches a width specification like
  16900. #+ATTR_HTML: :width 300px
  16901. and fall back on that number if none is found.
  16902. When set to nil, try to get the width from an #+ATTR.* keyword
  16903. and fall back on the original width if none is found.
  16904. This requires Emacs >= 24.1, build with imagemagick support."
  16905. :group 'org-appearance
  16906. :version "24.4"
  16907. :package-version '(Org . "8.0")
  16908. :type '(choice
  16909. (const :tag "Use the image width" t)
  16910. (integer :tag "Use a number of pixels")
  16911. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16912. (const :tag "Use #+ATTR* or don't resize" nil)))
  16913. (defcustom org-agenda-inhibit-startup nil
  16914. "Inhibit startup when preparing agenda buffers.
  16915. When this variable is t, the initialization of the Org agenda
  16916. buffers is inhibited: e.g. the visibility state is not set, the
  16917. tables are not re-aligned, etc."
  16918. :type 'boolean
  16919. :version "24.3"
  16920. :group 'org-agenda)
  16921. (defcustom org-agenda-ignore-properties nil
  16922. "Avoid updating text properties when building the agenda.
  16923. Properties are used to prepare buffers for effort estimates,
  16924. appointments, statistics and subtree-local categories.
  16925. If you don't use these in the agenda, you can add them to this
  16926. list and agenda building will be a bit faster.
  16927. The value is a list, with zero or more of the symbols `effort', `appt',
  16928. `stats' or `category'."
  16929. :type '(set :greedy t
  16930. (const effort)
  16931. (const appt)
  16932. (const stats)
  16933. (const category))
  16934. :version "25.1"
  16935. :package-version '(Org . "8.3")
  16936. :group 'org-agenda)
  16937. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16938. "Convert a duration string S to minutes.
  16939. A bare number is interpreted as minutes, modifiers can be set by
  16940. customizing `org-effort-durations' (which see).
  16941. Entries containing a colon are interpreted as H:MM by
  16942. `org-hh:mm-string-to-minutes'."
  16943. (let ((result 0)
  16944. (re (concat "\\([0-9.]+\\) *\\("
  16945. (regexp-opt (mapcar 'car org-effort-durations))
  16946. "\\)")))
  16947. (while (string-match re s)
  16948. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16949. (string-to-number (match-string 1 s))))
  16950. (setq s (replace-match "" nil t s)))
  16951. (setq result (floor result))
  16952. (cl-incf result (org-hh:mm-string-to-minutes s))
  16953. (if output-to-string (number-to-string result) result)))
  16954. ;;;; Files
  16955. (defun org-save-all-org-buffers ()
  16956. "Save all Org buffers without user confirmation."
  16957. (interactive)
  16958. (message "Saving all Org buffers...")
  16959. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16960. (when (featurep 'org-id) (org-id-locations-save))
  16961. (message "Saving all Org buffers... done"))
  16962. (defun org-revert-all-org-buffers ()
  16963. "Revert all Org buffers.
  16964. Prompt for confirmation when there are unsaved changes.
  16965. Be sure you know what you are doing before letting this function
  16966. overwrite your changes.
  16967. This function is useful in a setup where one tracks org files
  16968. with a version control system, to revert on one machine after pulling
  16969. changes from another. I believe the procedure must be like this:
  16970. 1. M-x org-save-all-org-buffers
  16971. 2. Pull changes from the other machine, resolve conflicts
  16972. 3. M-x org-revert-all-org-buffers"
  16973. (interactive)
  16974. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16975. (user-error "Abort"))
  16976. (save-excursion
  16977. (save-window-excursion
  16978. (dolist (b (buffer-list))
  16979. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16980. (with-current-buffer b buffer-file-name))
  16981. (pop-to-buffer-same-window b)
  16982. (revert-buffer t 'no-confirm)))
  16983. (when (and (featurep 'org-id) org-id-track-globally)
  16984. (org-id-locations-load)))))
  16985. ;;;; Agenda files
  16986. ;;;###autoload
  16987. (defun org-switchb (&optional arg)
  16988. "Switch between Org buffers.
  16989. With \\[universal-argument] prefix, restrict available buffers to files.
  16990. With \\[universal-argument] \\[universal-argument] \
  16991. prefix, restrict available buffers to agenda files."
  16992. (interactive "P")
  16993. (let ((blist (org-buffer-list
  16994. (cond ((equal arg '(4)) 'files)
  16995. ((equal arg '(16)) 'agenda)))))
  16996. (pop-to-buffer-same-window
  16997. (completing-read "Org buffer: "
  16998. (mapcar #'list (mapcar #'buffer-name blist))
  16999. nil t))))
  17000. (defun org-buffer-list (&optional predicate exclude-tmp)
  17001. "Return a list of Org buffers.
  17002. PREDICATE can be `export', `files' or `agenda'.
  17003. export restrict the list to Export buffers.
  17004. files restrict the list to buffers visiting Org files.
  17005. agenda restrict the list to buffers visiting agenda files.
  17006. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  17007. (let* ((bfn nil)
  17008. (agenda-files (and (eq predicate 'agenda)
  17009. (mapcar 'file-truename (org-agenda-files t))))
  17010. (filter
  17011. (cond
  17012. ((eq predicate 'files)
  17013. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  17014. ((eq predicate 'export)
  17015. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  17016. ((eq predicate 'agenda)
  17017. (lambda (b)
  17018. (with-current-buffer b
  17019. (and (derived-mode-p 'org-mode)
  17020. (setq bfn (buffer-file-name b))
  17021. (member (file-truename bfn) agenda-files)))))
  17022. (t (lambda (b) (with-current-buffer b
  17023. (or (derived-mode-p 'org-mode)
  17024. (string-match "\\*Org .*Export"
  17025. (buffer-name b)))))))))
  17026. (delq nil
  17027. (mapcar
  17028. (lambda(b)
  17029. (if (and (funcall filter b)
  17030. (or (not exclude-tmp)
  17031. (not (string-match "tmp" (buffer-name b)))))
  17032. b
  17033. nil))
  17034. (buffer-list)))))
  17035. (defun org-agenda-files (&optional unrestricted archives)
  17036. "Get the list of agenda files.
  17037. Optional UNRESTRICTED means return the full list even if a restriction
  17038. is currently in place.
  17039. When ARCHIVES is t, include all archive files that are really being
  17040. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  17041. `org-agenda-archives-mode' is t."
  17042. (let ((files
  17043. (cond
  17044. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  17045. ((stringp org-agenda-files) (org-read-agenda-file-list))
  17046. ((listp org-agenda-files) org-agenda-files)
  17047. (t (error "Invalid value of `org-agenda-files'")))))
  17048. (setq files (apply 'append
  17049. (mapcar (lambda (f)
  17050. (if (file-directory-p f)
  17051. (directory-files
  17052. f t org-agenda-file-regexp)
  17053. (list f)))
  17054. files)))
  17055. (when org-agenda-skip-unavailable-files
  17056. (setq files (delq nil
  17057. (mapcar (function
  17058. (lambda (file)
  17059. (and (file-readable-p file) file)))
  17060. files))))
  17061. (when (or (eq archives t)
  17062. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17063. (setq files (org-add-archive-files files)))
  17064. files))
  17065. (defun org-agenda-file-p (&optional file)
  17066. "Return non-nil, if FILE is an agenda file.
  17067. If FILE is omitted, use the file associated with the current
  17068. buffer."
  17069. (let ((fname (or file (buffer-file-name))))
  17070. (and fname
  17071. (member (file-truename fname)
  17072. (mapcar #'file-truename (org-agenda-files t))))))
  17073. (defun org-edit-agenda-file-list ()
  17074. "Edit the list of agenda files.
  17075. Depending on setup, this either uses customize to edit the variable
  17076. `org-agenda-files', or it visits the file that is holding the list. In the
  17077. latter case, the buffer is set up in a way that saving it automatically kills
  17078. the buffer and restores the previous window configuration."
  17079. (interactive)
  17080. (if (stringp org-agenda-files)
  17081. (let ((cw (current-window-configuration)))
  17082. (find-file org-agenda-files)
  17083. (setq-local org-window-configuration cw)
  17084. (add-hook 'after-save-hook
  17085. (lambda ()
  17086. (set-window-configuration
  17087. (prog1 org-window-configuration
  17088. (kill-buffer (current-buffer))))
  17089. (org-install-agenda-files-menu)
  17090. (message "New agenda file list installed"))
  17091. nil 'local)
  17092. (message "%s" (substitute-command-keys
  17093. "Edit list and finish with \\[save-buffer]")))
  17094. (customize-variable 'org-agenda-files)))
  17095. (defun org-store-new-agenda-file-list (list)
  17096. "Set new value for the agenda file list and save it correctly."
  17097. (if (stringp org-agenda-files)
  17098. (let ((fe (org-read-agenda-file-list t)) b u)
  17099. (while (setq b (find-buffer-visiting org-agenda-files))
  17100. (kill-buffer b))
  17101. (with-temp-file org-agenda-files
  17102. (insert
  17103. (mapconcat
  17104. (lambda (f) ;; Keep un-expanded entries.
  17105. (if (setq u (assoc f fe))
  17106. (cdr u)
  17107. f))
  17108. list "\n")
  17109. "\n")))
  17110. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17111. (org-insert-mode-line-in-empty-file nil))
  17112. (setq org-agenda-files list)
  17113. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17114. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17115. "Read the list of agenda files from a file.
  17116. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17117. filenames, used by `org-store-new-agenda-file-list' to write back
  17118. un-expanded file names."
  17119. (when (file-directory-p org-agenda-files)
  17120. (error "`org-agenda-files' cannot be a single directory"))
  17121. (when (stringp org-agenda-files)
  17122. (with-temp-buffer
  17123. (insert-file-contents org-agenda-files)
  17124. (mapcar
  17125. (lambda (f)
  17126. (let ((e (expand-file-name (substitute-in-file-name f)
  17127. org-directory)))
  17128. (if pair-with-expansion
  17129. (cons e f)
  17130. e)))
  17131. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17132. ;;;###autoload
  17133. (defun org-cycle-agenda-files ()
  17134. "Cycle through the files in `org-agenda-files'.
  17135. If the current buffer visits an agenda file, find the next one in the list.
  17136. If the current buffer does not, find the first agenda file."
  17137. (interactive)
  17138. (let* ((fs (or (org-agenda-files t)
  17139. (user-error "No agenda files")))
  17140. (files (copy-sequence fs))
  17141. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17142. file)
  17143. (when tcf
  17144. (while (and (setq file (pop files))
  17145. (not (equal (file-truename file) tcf)))))
  17146. (find-file (car (or files fs)))
  17147. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17148. (defun org-agenda-file-to-front (&optional to-end)
  17149. "Move/add the current file to the top of the agenda file list.
  17150. If the file is not present in the list, it is added to the front. If it is
  17151. present, it is moved there. With optional argument TO-END, add/move to the
  17152. end of the list."
  17153. (interactive "P")
  17154. (let ((org-agenda-skip-unavailable-files nil)
  17155. (file-alist (mapcar (lambda (x)
  17156. (cons (file-truename x) x))
  17157. (org-agenda-files t)))
  17158. (ctf (file-truename
  17159. (or buffer-file-name
  17160. (user-error "Please save the current buffer to a file"))))
  17161. x had)
  17162. (setq x (assoc ctf file-alist) had x)
  17163. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17164. (if to-end
  17165. (setq file-alist (append (delq x file-alist) (list x)))
  17166. (setq file-alist (cons x (delq x file-alist))))
  17167. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17168. (org-install-agenda-files-menu)
  17169. (message "File %s to %s of agenda file list"
  17170. (if had "moved" "added") (if to-end "end" "front"))))
  17171. (defun org-remove-file (&optional file)
  17172. "Remove current file from the list of files in variable `org-agenda-files'.
  17173. These are the files which are being checked for agenda entries.
  17174. Optional argument FILE means use this file instead of the current."
  17175. (interactive)
  17176. (let* ((org-agenda-skip-unavailable-files nil)
  17177. (file (or file buffer-file-name
  17178. (user-error "Current buffer does not visit a file")))
  17179. (true-file (file-truename file))
  17180. (afile (abbreviate-file-name file))
  17181. (files (delq nil (mapcar
  17182. (lambda (x)
  17183. (unless (equal true-file
  17184. (file-truename x))
  17185. x))
  17186. (org-agenda-files t)))))
  17187. (if (not (= (length files) (length (org-agenda-files t))))
  17188. (progn
  17189. (org-store-new-agenda-file-list files)
  17190. (org-install-agenda-files-menu)
  17191. (message "Removed from Org Agenda list: %s" afile))
  17192. (message "File was not in list: %s (not removed)" afile))))
  17193. (defun org-file-menu-entry (file)
  17194. (vector file (list 'find-file file) t))
  17195. (defun org-check-agenda-file (file)
  17196. "Make sure FILE exists. If not, ask user what to do."
  17197. (unless (file-exists-p file)
  17198. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17199. (abbreviate-file-name file))
  17200. (let ((r (downcase (read-char-exclusive))))
  17201. (cond
  17202. ((equal r ?r)
  17203. (org-remove-file file)
  17204. (throw 'nextfile t))
  17205. (t (user-error "Abort"))))))
  17206. (defun org-get-agenda-file-buffer (file)
  17207. "Get an agenda buffer visiting FILE.
  17208. If the buffer needs to be created, add it to the list of buffers
  17209. which might be released later."
  17210. (let ((buf (org-find-base-buffer-visiting file)))
  17211. (if buf
  17212. buf ; just return it
  17213. ;; Make a new buffer and remember it
  17214. (setq buf (find-file-noselect file))
  17215. (when buf (push buf org-agenda-new-buffers))
  17216. buf)))
  17217. (defun org-release-buffers (blist)
  17218. "Release all buffers in list, asking the user for confirmation when needed.
  17219. When a buffer is unmodified, it is just killed. When modified, it is saved
  17220. \(if the user agrees) and then killed."
  17221. (let (file)
  17222. (dolist (buf blist)
  17223. (setq file (buffer-file-name buf))
  17224. (when (and (buffer-modified-p buf)
  17225. file
  17226. (y-or-n-p (format "Save file %s? " file)))
  17227. (with-current-buffer buf (save-buffer)))
  17228. (kill-buffer buf))))
  17229. (defun org-agenda-prepare-buffers (files)
  17230. "Create buffers for all agenda files, protect archived trees and comments."
  17231. (interactive)
  17232. (let ((pa '(:org-archived t))
  17233. (pc '(:org-comment t))
  17234. (pall '(:org-archived t :org-comment t))
  17235. (inhibit-read-only t)
  17236. (org-inhibit-startup org-agenda-inhibit-startup)
  17237. (rea (concat ":" org-archive-tag ":"))
  17238. re pos)
  17239. (setq org-tag-alist-for-agenda nil
  17240. org-tag-groups-alist-for-agenda nil)
  17241. (save-excursion
  17242. (save-restriction
  17243. (dolist (file files)
  17244. (catch 'nextfile
  17245. (if (bufferp file)
  17246. (set-buffer file)
  17247. (org-check-agenda-file file)
  17248. (set-buffer (org-get-agenda-file-buffer file)))
  17249. (widen)
  17250. (org-set-regexps-and-options 'tags-only)
  17251. (setq pos (point))
  17252. (or (memq 'category org-agenda-ignore-properties)
  17253. (org-refresh-category-properties))
  17254. (or (memq 'stats org-agenda-ignore-properties)
  17255. (org-refresh-stats-properties))
  17256. (or (memq 'effort org-agenda-ignore-properties)
  17257. (org-refresh-effort-properties))
  17258. (or (memq 'appt org-agenda-ignore-properties)
  17259. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17260. (setq org-todo-keywords-for-agenda
  17261. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17262. (setq org-done-keywords-for-agenda
  17263. (append org-done-keywords-for-agenda org-done-keywords))
  17264. (setq org-todo-keyword-alist-for-agenda
  17265. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17266. (setq org-tag-alist-for-agenda
  17267. (org-uniquify
  17268. (append org-tag-alist-for-agenda
  17269. org-current-tag-alist)))
  17270. ;; Merge current file's tag groups into global
  17271. ;; `org-tag-groups-alist-for-agenda'.
  17272. (when org-group-tags
  17273. (dolist (alist org-tag-groups-alist)
  17274. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17275. (if old
  17276. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17277. (push alist org-tag-groups-alist-for-agenda)))))
  17278. (org-with-silent-modifications
  17279. (save-excursion
  17280. (remove-text-properties (point-min) (point-max) pall)
  17281. (when org-agenda-skip-archived-trees
  17282. (goto-char (point-min))
  17283. (while (re-search-forward rea nil t)
  17284. (when (org-at-heading-p t)
  17285. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17286. (goto-char (point-min))
  17287. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17288. (while (re-search-forward re nil t)
  17289. (when (save-match-data (org-in-commented-heading-p t))
  17290. (add-text-properties
  17291. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17292. (goto-char pos)))))
  17293. (setq org-todo-keywords-for-agenda
  17294. (org-uniquify org-todo-keywords-for-agenda))
  17295. (setq org-todo-keyword-alist-for-agenda
  17296. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17297. ;;;; CDLaTeX minor mode
  17298. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17299. "Keymap for the minor `org-cdlatex-mode'.")
  17300. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17301. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17302. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17303. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17304. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17305. (defvar org-cdlatex-texmathp-advice-is-done nil
  17306. "Flag remembering if we have applied the advice to texmathp already.")
  17307. (define-minor-mode org-cdlatex-mode
  17308. "Toggle the minor `org-cdlatex-mode'.
  17309. This mode supports entering LaTeX environment and math in LaTeX fragments
  17310. in Org-mode.
  17311. \\{org-cdlatex-mode-map}"
  17312. nil " OCDL" nil
  17313. (when org-cdlatex-mode
  17314. (require 'cdlatex)
  17315. (run-hooks 'cdlatex-mode-hook)
  17316. (cdlatex-compute-tables))
  17317. (unless org-cdlatex-texmathp-advice-is-done
  17318. (setq org-cdlatex-texmathp-advice-is-done t)
  17319. (defadvice texmathp (around org-math-always-on activate)
  17320. "Always return t in Org buffers.
  17321. This is because we want to insert math symbols without dollars even outside
  17322. the LaTeX math segments. If Orgmode thinks that point is actually inside
  17323. an embedded LaTeX fragment, let texmathp do its job.
  17324. \\[org-cdlatex-mode-map]"
  17325. (interactive)
  17326. (let (p)
  17327. (cond
  17328. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17329. ((eq this-command 'cdlatex-math-symbol)
  17330. (setq ad-return-value t
  17331. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17332. (t
  17333. (let ((p (org-inside-LaTeX-fragment-p)))
  17334. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17335. (setq ad-return-value t
  17336. texmathp-why '("Org-mode embedded math" . 0))
  17337. (when p ad-do-it)))))))))
  17338. (defun turn-on-org-cdlatex ()
  17339. "Unconditionally turn on `org-cdlatex-mode'."
  17340. (org-cdlatex-mode 1))
  17341. (defun org-try-cdlatex-tab ()
  17342. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17343. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17344. - inside a LaTeX fragment, or
  17345. - after the first word in a line, where an abbreviation expansion could
  17346. insert a LaTeX environment."
  17347. (when org-cdlatex-mode
  17348. (cond
  17349. ;; Before any word on the line: No expansion possible.
  17350. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17351. ;; Just after first word on the line: Expand it. Make sure it
  17352. ;; cannot happen on headlines, though.
  17353. ((save-excursion
  17354. (skip-chars-backward "a-zA-Z0-9*")
  17355. (skip-chars-backward " \t")
  17356. (and (bolp) (not (org-at-heading-p))))
  17357. (cdlatex-tab) t)
  17358. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17359. (defun org-cdlatex-underscore-caret (&optional _arg)
  17360. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17361. Revert to the normal definition outside of these fragments."
  17362. (interactive "P")
  17363. (if (org-inside-LaTeX-fragment-p)
  17364. (call-interactively 'cdlatex-sub-superscript)
  17365. (let (org-cdlatex-mode)
  17366. (call-interactively (key-binding (vector last-input-event))))))
  17367. (defun org-cdlatex-math-modify (&optional _arg)
  17368. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17369. Revert to the normal definition outside of these fragments."
  17370. (interactive "P")
  17371. (if (org-inside-LaTeX-fragment-p)
  17372. (call-interactively 'cdlatex-math-modify)
  17373. (let (org-cdlatex-mode)
  17374. (call-interactively (key-binding (vector last-input-event))))))
  17375. (defun org-cdlatex-environment-indent (&optional environment item)
  17376. "Execute `cdlatex-environment' and indent the inserted environment.
  17377. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17378. The inserted environment is indented to current indentation
  17379. unless point is at the beginning of the line, in which the
  17380. environment remains unintended."
  17381. (interactive)
  17382. ;; cdlatex-environment always return nil. Therefore, capture output
  17383. ;; first and determine if an environment was selected.
  17384. (let* ((beg (point-marker))
  17385. (end (copy-marker (point) t))
  17386. (inserted (progn
  17387. (ignore-errors (cdlatex-environment environment item))
  17388. (< beg end)))
  17389. ;; Figure out how many lines to move forward after the
  17390. ;; environment has been inserted.
  17391. (lines (when inserted
  17392. (save-excursion
  17393. (- (cl-loop while (< beg (point))
  17394. with x = 0
  17395. do (forward-line -1)
  17396. (cl-incf x)
  17397. finally return x)
  17398. (if (progn (goto-char beg)
  17399. (and (progn (skip-chars-forward " \t") (eolp))
  17400. (progn (skip-chars-backward " \t") (bolp))))
  17401. 1 0)))))
  17402. (env (org-trim (delete-and-extract-region beg end))))
  17403. (when inserted
  17404. ;; Get indentation of next line unless at column 0.
  17405. (let ((ind (if (bolp) 0
  17406. (save-excursion
  17407. (org-return-indent)
  17408. (prog1 (org-get-indentation)
  17409. (when (progn (skip-chars-forward " \t") (eolp))
  17410. (delete-region beg (point)))))))
  17411. (bol (progn (skip-chars-backward " \t") (bolp))))
  17412. ;; Insert a newline before environment unless at column zero
  17413. ;; to "escape" the current line. Insert a newline if
  17414. ;; something is one the same line as \end{ENVIRONMENT}.
  17415. (insert
  17416. (concat (unless bol "\n") env
  17417. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17418. (unless (zerop ind)
  17419. (save-excursion
  17420. (goto-char beg)
  17421. (while (< (point) end)
  17422. (unless (eolp) (indent-line-to ind))
  17423. (forward-line))))
  17424. (goto-char beg)
  17425. (forward-line lines)
  17426. (indent-line-to ind)))
  17427. (set-marker beg nil)
  17428. (set-marker end nil)))
  17429. ;;;; LaTeX fragments
  17430. (defun org-inside-LaTeX-fragment-p ()
  17431. "Test if point is inside a LaTeX fragment.
  17432. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17433. sequence appearing also before point.
  17434. Even though the matchers for math are configurable, this function assumes
  17435. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17436. delimiters are skipped when they have been removed by customization.
  17437. The return value is nil, or a cons cell with the delimiter and the
  17438. position of this delimiter.
  17439. This function does a reasonably good job, but can locally be fooled by
  17440. for example currency specifications. For example it will assume being in
  17441. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17442. fragments that are properly closed, but during editing, we have to live
  17443. with the uncertainty caused by missing closing delimiters. This function
  17444. looks only before point, not after."
  17445. (catch 'exit
  17446. (let ((pos (point))
  17447. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17448. (lim (progn
  17449. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17450. (point)))
  17451. dd-on str (start 0) m re)
  17452. (goto-char pos)
  17453. (when dodollar
  17454. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17455. re (nth 1 (assoc "$" org-latex-regexps)))
  17456. (while (string-match re str start)
  17457. (cond
  17458. ((= (match-end 0) (length str))
  17459. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17460. ((= (match-end 0) (- (length str) 5))
  17461. (throw 'exit nil))
  17462. (t (setq start (match-end 0))))))
  17463. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17464. (goto-char pos)
  17465. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17466. (and (match-beginning 2) (throw 'exit nil))
  17467. ;; count $$
  17468. (while (re-search-backward "\\$\\$" lim t)
  17469. (setq dd-on (not dd-on)))
  17470. (goto-char pos)
  17471. (when dd-on (cons "$$" m))))))
  17472. (defun org-inside-latex-macro-p ()
  17473. "Is point inside a LaTeX macro or its arguments?"
  17474. (save-match-data
  17475. (org-in-regexp
  17476. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17477. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17478. "Build an overlay between BEG and END using IMAGE file.
  17479. Argument IMAGETYPE is the extension of the displayed image,
  17480. as a string. It defaults to \"png\"."
  17481. (let ((ov (make-overlay beg end))
  17482. (imagetype (or (intern imagetype) 'png)))
  17483. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17484. (overlay-put ov 'evaporate t)
  17485. (overlay-put ov
  17486. 'modification-hooks
  17487. (list (lambda (o _flag _beg _end &optional _l)
  17488. (delete-overlay o))))
  17489. (overlay-put ov
  17490. 'display
  17491. (list 'image :type imagetype :file image :ascent 'center))))
  17492. (defun org--list-latex-overlays (&optional beg end)
  17493. "List all Org LaTeX overlays in current buffer.
  17494. Limit to overlays between BEG and END when those are provided."
  17495. (cl-remove-if-not
  17496. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17497. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17498. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17499. "Remove all overlays with LaTeX fragment images in current buffer.
  17500. When optional arguments BEG and END are non-nil, remove all
  17501. overlays between them instead. Return a non-nil value when some
  17502. overlays were removed, nil otherwise."
  17503. (let ((overlays (org--list-latex-overlays beg end)))
  17504. (mapc #'delete-overlay overlays)
  17505. overlays))
  17506. (defun org-toggle-latex-fragment (&optional arg)
  17507. "Preview the LaTeX fragment at point, or all locally or globally.
  17508. If the cursor is on a LaTeX fragment, create the image and overlay
  17509. it over the source code, if there is none. Remove it otherwise.
  17510. If there is no fragment at point, display all fragments in the
  17511. current section.
  17512. With prefix ARG, preview or clear image for all fragments in the
  17513. current subtree or in the whole buffer when used before the first
  17514. headline. With a double prefix ARG \\[universal-argument] \
  17515. \\[universal-argument] preview or clear images
  17516. for all fragments in the buffer."
  17517. (interactive "P")
  17518. (when (display-graphic-p)
  17519. (catch 'exit
  17520. (save-excursion
  17521. (let (beg end msg)
  17522. (cond
  17523. ((or (equal arg '(16))
  17524. (and (equal arg '(4))
  17525. (org-with-limited-levels (org-before-first-heading-p))))
  17526. (if (org-remove-latex-fragment-image-overlays)
  17527. (progn (message "LaTeX fragments images removed from buffer")
  17528. (throw 'exit nil))
  17529. (setq msg "Creating images for buffer...")))
  17530. ((equal arg '(4))
  17531. (org-with-limited-levels (org-back-to-heading t))
  17532. (setq beg (point))
  17533. (setq end (progn (org-end-of-subtree t) (point)))
  17534. (if (org-remove-latex-fragment-image-overlays beg end)
  17535. (progn
  17536. (message "LaTeX fragment images removed from subtree")
  17537. (throw 'exit nil))
  17538. (setq msg "Creating images for subtree...")))
  17539. ((let ((datum (org-element-context)))
  17540. (when (memq (org-element-type datum)
  17541. '(latex-environment latex-fragment))
  17542. (setq beg (org-element-property :begin datum))
  17543. (setq end (org-element-property :end datum))
  17544. (if (org-remove-latex-fragment-image-overlays beg end)
  17545. (progn (message "LaTeX fragment image removed")
  17546. (throw 'exit nil))
  17547. (setq msg "Creating image...")))))
  17548. (t
  17549. (org-with-limited-levels
  17550. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17551. (outline-previous-heading)
  17552. (point)))
  17553. (setq end (progn (outline-next-heading) (point)))
  17554. (if (org-remove-latex-fragment-image-overlays beg end)
  17555. (progn
  17556. (message "LaTeX fragment images removed from section")
  17557. (throw 'exit nil))
  17558. (setq msg "Creating images for section...")))))
  17559. (let ((file (buffer-file-name (buffer-base-buffer))))
  17560. (org-format-latex
  17561. (concat org-preview-latex-image-directory "org-ltximg")
  17562. beg end
  17563. ;; Emacs cannot overlay images from remote hosts. Create
  17564. ;; it in `temporary-file-directory' instead.
  17565. (if (or (not file) (file-remote-p file))
  17566. temporary-file-directory
  17567. default-directory)
  17568. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17569. (message (concat msg "done")))))))
  17570. (defun org-format-latex
  17571. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17572. "Replace LaTeX fragments with links to an image.
  17573. The function takes care of creating the replacement image.
  17574. Only consider fragments between BEG and END when those are
  17575. provided.
  17576. When optional argument OVERLAYS is non-nil, display the image on
  17577. top of the fragment instead of replacing it.
  17578. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17579. Some of the options can be changed using the variable
  17580. `org-format-latex-options', which see."
  17581. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17582. (unless (eq processing-type 'verbatim)
  17583. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17584. (cnt 0)
  17585. checkdir-flag)
  17586. (goto-char (or beg (point-min)))
  17587. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17588. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17589. (overlay-recenter (or end (point-max))))
  17590. (while (re-search-forward math-regexp end t)
  17591. (unless (and overlays
  17592. (eq (get-char-property (point) 'org-overlay-type)
  17593. 'org-latex-overlay))
  17594. (let* ((context (org-element-context))
  17595. (type (org-element-type context)))
  17596. (when (memq type '(latex-environment latex-fragment))
  17597. (let ((block-type (eq type 'latex-environment))
  17598. (value (org-element-property :value context))
  17599. (beg (org-element-property :begin context))
  17600. (end (save-excursion
  17601. (goto-char (org-element-property :end context))
  17602. (skip-chars-backward " \r\t\n")
  17603. (point))))
  17604. (cond
  17605. ((eq processing-type 'mathjax)
  17606. ;; Prepare for MathJax processing.
  17607. (if (not (string-match "\\`\\$\\$?" value))
  17608. (goto-char end)
  17609. (delete-region beg end)
  17610. (if (string= (match-string 0 value) "$$")
  17611. (insert "\\[" (substring value 2 -2) "\\]")
  17612. (insert "\\(" (substring value 1 -1) "\\)"))))
  17613. ((assq processing-type org-preview-latex-process-alist)
  17614. ;; Process to an image.
  17615. (cl-incf cnt)
  17616. (goto-char beg)
  17617. (let* ((processing-info
  17618. (cdr (assq processing-type org-preview-latex-process-alist)))
  17619. (face (face-at-point))
  17620. ;; Get the colors from the face at point.
  17621. (fg
  17622. (let ((color (plist-get org-format-latex-options
  17623. :foreground)))
  17624. (if (and forbuffer (eq color 'auto))
  17625. (face-attribute face :foreground nil 'default)
  17626. color)))
  17627. (bg
  17628. (let ((color (plist-get org-format-latex-options
  17629. :background)))
  17630. (if (and forbuffer (eq color 'auto))
  17631. (face-attribute face :background nil 'default)
  17632. color)))
  17633. (hash (sha1 (prin1-to-string
  17634. (list org-format-latex-header
  17635. org-latex-default-packages-alist
  17636. org-latex-packages-alist
  17637. org-format-latex-options
  17638. forbuffer value fg bg))))
  17639. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17640. (absprefix (expand-file-name prefix dir))
  17641. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17642. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17643. (sep (and block-type "\n\n"))
  17644. (link (concat sep "[[file:" linkfile "]]" sep))
  17645. (options
  17646. (org-combine-plists
  17647. org-format-latex-options
  17648. `(:foreground ,fg :background ,bg))))
  17649. (when msg (message msg cnt))
  17650. (unless checkdir-flag ; Ensure the directory exists.
  17651. (setq checkdir-flag t)
  17652. (let ((todir (file-name-directory absprefix)))
  17653. (unless (file-directory-p todir)
  17654. (make-directory todir t))))
  17655. (unless (file-exists-p movefile)
  17656. (org-create-formula-image
  17657. value movefile options forbuffer processing-type))
  17658. (if overlays
  17659. (progn
  17660. (dolist (o (overlays-in beg end))
  17661. (when (eq (overlay-get o 'org-overlay-type)
  17662. 'org-latex-overlay)
  17663. (delete-overlay o)))
  17664. (org--format-latex-make-overlay beg end movefile imagetype)
  17665. (goto-char end))
  17666. (delete-region beg end)
  17667. (insert
  17668. (org-add-props link
  17669. (list 'org-latex-src
  17670. (replace-regexp-in-string "\"" "" value)
  17671. 'org-latex-src-embed-type
  17672. (if block-type 'paragraph 'character)))))))
  17673. ((eq processing-type 'mathml)
  17674. ;; Process to MathML.
  17675. (unless (org-format-latex-mathml-available-p)
  17676. (user-error "LaTeX to MathML converter not configured"))
  17677. (cl-incf cnt)
  17678. (when msg (message msg cnt))
  17679. (goto-char beg)
  17680. (delete-region beg end)
  17681. (insert (org-format-latex-as-mathml
  17682. value block-type prefix dir)))
  17683. (t
  17684. (error "Unknown conversion process %s for LaTeX fragments"
  17685. processing-type)))))))))))
  17686. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17687. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17688. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17689. sucessful, return the portion between \"<math...> </math>\"
  17690. elements otherwise return nil. When MATHML-FILE is specified,
  17691. write the results in to that file. When invoked as an
  17692. interactive command, prompt for LATEX-FRAG, with initial value
  17693. set to the current active region and echo the results for user
  17694. inspection."
  17695. (interactive (list (let ((frag (when (org-region-active-p)
  17696. (buffer-substring-no-properties
  17697. (region-beginning) (region-end)))))
  17698. (read-string "LaTeX Fragment: " frag nil frag))))
  17699. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17700. (let* ((tmp-in-file
  17701. (let ((file (file-relative-name
  17702. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17703. (write-region latex-frag nil file)
  17704. file))
  17705. (tmp-out-file (file-relative-name
  17706. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17707. (cmd (format-spec
  17708. org-latex-to-mathml-convert-command
  17709. `((?j . ,(and org-latex-to-mathml-jar-file
  17710. (shell-quote-argument
  17711. (expand-file-name
  17712. org-latex-to-mathml-jar-file))))
  17713. (?I . ,(shell-quote-argument tmp-in-file))
  17714. (?i . ,latex-frag)
  17715. (?o . ,(shell-quote-argument tmp-out-file)))))
  17716. mathml shell-command-output)
  17717. (when (called-interactively-p 'any)
  17718. (unless (org-format-latex-mathml-available-p)
  17719. (user-error "LaTeX to MathML converter not configured")))
  17720. (message "Running %s" cmd)
  17721. (setq shell-command-output (shell-command-to-string cmd))
  17722. (setq mathml
  17723. (when (file-readable-p tmp-out-file)
  17724. (with-current-buffer (find-file-noselect tmp-out-file t)
  17725. (goto-char (point-min))
  17726. (when (re-search-forward
  17727. (concat
  17728. (regexp-quote
  17729. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17730. "[^>]*?>"
  17731. "\\(.\\|\n\\)*"
  17732. "</math>")
  17733. nil t)
  17734. (prog1 (match-string 0) (kill-buffer))))))
  17735. (cond
  17736. (mathml
  17737. (setq mathml
  17738. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17739. (when mathml-file
  17740. (write-region mathml nil mathml-file))
  17741. (when (called-interactively-p 'any)
  17742. (message mathml)))
  17743. ((message "LaTeX to MathML conversion failed")
  17744. (message shell-command-output)))
  17745. (delete-file tmp-in-file)
  17746. (when (file-exists-p tmp-out-file)
  17747. (delete-file tmp-out-file))
  17748. mathml))
  17749. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17750. prefix &optional dir)
  17751. "Use `org-create-math-formula' but check local cache first."
  17752. (let* ((absprefix (expand-file-name prefix dir))
  17753. (print-length nil) (print-level nil)
  17754. (formula-id (concat
  17755. "formula-"
  17756. (sha1
  17757. (prin1-to-string
  17758. (list latex-frag
  17759. org-latex-to-mathml-convert-command)))))
  17760. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17761. (formula-cache-dir (file-name-directory formula-cache)))
  17762. (unless (file-directory-p formula-cache-dir)
  17763. (make-directory formula-cache-dir t))
  17764. (unless (file-exists-p formula-cache)
  17765. (org-create-math-formula latex-frag formula-cache))
  17766. (if (file-exists-p formula-cache)
  17767. ;; Successful conversion. Return the link to MathML file.
  17768. (org-add-props
  17769. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17770. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17771. 'org-latex-src-embed-type (if latex-frag-type
  17772. 'paragraph 'character)))
  17773. ;; Failed conversion. Return the LaTeX fragment verbatim
  17774. latex-frag)))
  17775. (declare-function org-export-get-backend "ox" (name))
  17776. (declare-function org-export--get-global-options "ox" (&optional backend))
  17777. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17778. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17779. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17780. (defun org-create-formula--latex-header ()
  17781. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17782. (let ((info (org-combine-plists (org-export--get-global-options
  17783. (org-export-get-backend 'latex))
  17784. (org-export--get-inbuffer-options
  17785. (org-export-get-backend 'latex)))))
  17786. (org-latex-guess-babel-language
  17787. (org-latex-guess-inputenc
  17788. (org-splice-latex-header
  17789. org-format-latex-header
  17790. org-latex-default-packages-alist
  17791. org-latex-packages-alist t
  17792. (plist-get info :latex-header)))
  17793. info)))
  17794. (defun org--get-display-dpi ()
  17795. "Get the DPI of the display.
  17796. Assumes that the display has the same pixel width in the
  17797. horizontal and vertical directions."
  17798. (if (display-graphic-p)
  17799. (round (/ (display-pixel-height)
  17800. (/ (display-mm-height) 25.4)))
  17801. (error "Attempt to calculate the dpi of a non-graphic display")))
  17802. (defun org-create-formula-image
  17803. (string tofile options buffer &optional processing-type)
  17804. "Create an image from LaTeX source using external processes.
  17805. The LaTeX STRING is saved to a temporary LaTeX file, then
  17806. converted to an image file by process PROCESSING-TYPE defined in
  17807. `org-preview-latex-process-alist'. A nil value defaults to
  17808. `org-preview-latex-default-process'.
  17809. The generated image file is eventually moved to TOFILE.
  17810. The OPTIONS argument controls the size, foreground color and
  17811. background color of the generated image.
  17812. When BUFFER non-nil, this function is used for LaTeX previewing.
  17813. Otherwise, it is used to deal with LaTeX snippets showed in
  17814. a HTML file."
  17815. (let* ((processing-type (or processing-type
  17816. org-preview-latex-default-process))
  17817. (processing-info
  17818. (cdr (assq processing-type org-preview-latex-process-alist)))
  17819. (programs (plist-get processing-info :programs))
  17820. (error-message (or (plist-get processing-info :message) ""))
  17821. (use-xcolor (plist-get processing-info :use-xcolor))
  17822. (image-input-type (plist-get processing-info :image-input-type))
  17823. (image-output-type (plist-get processing-info :image-output-type))
  17824. (post-clean (or (plist-get processing-info :post-clean)
  17825. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17826. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17827. (latex-header (or (plist-get processing-info :latex-header)
  17828. (org-create-formula--latex-header)))
  17829. (latex-compiler (plist-get processing-info :latex-compiler))
  17830. (image-converter (plist-get processing-info :image-converter))
  17831. (tmpdir temporary-file-directory)
  17832. (texfilebase (make-temp-name
  17833. (expand-file-name "orgtex" tmpdir)))
  17834. (texfile (concat texfilebase ".tex"))
  17835. (font-height (face-attribute 'default :height nil))
  17836. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17837. '(1.0 . 1.0)))
  17838. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17839. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17840. (dpi (* scale (floor (if buffer font-height 140.0))))
  17841. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17842. "Black"))
  17843. (bg (or (plist-get options (if buffer :background :html-background))
  17844. "Transparent"))
  17845. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17846. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17847. (dolist (program programs)
  17848. (org-check-external-command program error-message))
  17849. (if use-xcolor
  17850. (progn (if (eq fg 'default)
  17851. (setq fg (org-latex-color :foreground))
  17852. (setq fg (org-latex-color-format fg)))
  17853. (if (eq bg 'default)
  17854. (setq bg (org-latex-color :background))
  17855. (setq bg (org-latex-color-format
  17856. (if (string= bg "Transparent") "white" bg))))
  17857. (with-temp-file texfile
  17858. (insert latex-header)
  17859. (insert "\n\\begin{document}\n"
  17860. "\\definecolor{fg}{rgb}{" fg "}\n"
  17861. "\\definecolor{bg}{rgb}{" bg "}\n"
  17862. "\n\\pagecolor{bg}\n"
  17863. "\n{\\color{fg}\n"
  17864. string
  17865. "\n}\n"
  17866. "\n\\end{document}\n")))
  17867. (if (eq fg 'default)
  17868. (setq fg (org-dvipng-color :foreground))
  17869. (unless (string= fg "Transparent")
  17870. (setq fg (org-dvipng-color-format fg))))
  17871. (if (eq bg 'default)
  17872. (setq bg (org-dvipng-color :background))
  17873. (unless (string= bg "Transparent")
  17874. (setq bg (org-dvipng-color-format bg))))
  17875. (with-temp-file texfile
  17876. (insert latex-header)
  17877. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17878. (let* ((err-msg (format "Please adjust '%s' part of \
  17879. `org-preview-latex-process-alist'."
  17880. processing-type))
  17881. (image-input-file
  17882. (org-compile-file
  17883. texfile latex-compiler image-input-type err-msg log-buf))
  17884. (image-output-file
  17885. (org-compile-file
  17886. image-input-file image-converter image-output-type err-msg log-buf
  17887. `((?F . ,(shell-quote-argument fg))
  17888. (?B . ,(shell-quote-argument bg))
  17889. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17890. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17891. (copy-file image-output-file tofile 'replace)
  17892. (dolist (e post-clean)
  17893. (when (file-exists-p (concat texfilebase e))
  17894. (delete-file (concat texfilebase e))))
  17895. image-output-file)))
  17896. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17897. "Fill a LaTeX header template TPL.
  17898. In the template, the following place holders will be recognized:
  17899. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17900. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17901. [PACKAGES] \\usepackage statements for PKG
  17902. [NO-PACKAGES] do not include PKG
  17903. [EXTRA] the string EXTRA
  17904. [NO-EXTRA] do not include EXTRA
  17905. For backward compatibility, if both the positive and the negative place
  17906. holder is missing, the positive one (without the \"NO-\") will be
  17907. assumed to be present at the end of the template.
  17908. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17909. EXTRA is a string.
  17910. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17911. (let (rpl (end ""))
  17912. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17913. (setq rpl (if (or (match-end 1) (not def-pkg))
  17914. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17915. tpl (replace-match rpl t t tpl))
  17916. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17917. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17918. (setq rpl (if (or (match-end 1) (not pkg))
  17919. "" (org-latex-packages-to-string pkg snippets-p t))
  17920. tpl (replace-match rpl t t tpl))
  17921. (when pkg (setq end
  17922. (concat end "\n"
  17923. (org-latex-packages-to-string pkg snippets-p)))))
  17924. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17925. (setq rpl (if (or (match-end 1) (not extra))
  17926. "" (concat extra "\n"))
  17927. tpl (replace-match rpl t t tpl))
  17928. (when (and extra (string-match "\\S-" extra))
  17929. (setq end (concat end "\n" extra))))
  17930. (if (string-match "\\S-" end)
  17931. (concat tpl "\n" end)
  17932. tpl)))
  17933. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17934. "Turn an alist of packages into a string with the \\usepackage macros."
  17935. (setq pkg (mapconcat (lambda(p)
  17936. (cond
  17937. ((stringp p) p)
  17938. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17939. (format "%% Package %s omitted" (cadr p)))
  17940. ((equal "" (car p))
  17941. (format "\\usepackage{%s}" (cadr p)))
  17942. (t
  17943. (format "\\usepackage[%s]{%s}"
  17944. (car p) (cadr p)))))
  17945. pkg
  17946. "\n"))
  17947. (if newline (concat pkg "\n") pkg))
  17948. (defun org-dvipng-color (attr)
  17949. "Return a RGB color specification for dvipng."
  17950. (apply #'format "rgb %s %s %s"
  17951. (mapcar #'org-normalize-color
  17952. (color-values (face-attribute 'default attr nil)))))
  17953. (defun org-dvipng-color-format (color-name)
  17954. "Convert COLOR-NAME to a RGB color value for dvipng."
  17955. (apply 'format "rgb %s %s %s"
  17956. (mapcar 'org-normalize-color
  17957. (color-values color-name))))
  17958. (defun org-latex-color (attr)
  17959. "Return a RGB color for the LaTeX color package."
  17960. (apply #'format "%s,%s,%s"
  17961. (mapcar #'org-normalize-color
  17962. (color-values (face-attribute 'default attr nil)))))
  17963. (defun org-latex-color-format (color-name)
  17964. "Convert COLOR-NAME to a RGB color value."
  17965. (apply 'format "%s,%s,%s"
  17966. (mapcar 'org-normalize-color
  17967. (color-values color-name))))
  17968. (defun org-normalize-color (value)
  17969. "Return string to be used as color value for an RGB component."
  17970. (format "%g" (/ value 65535.0)))
  17971. ;; Image display
  17972. (defvar-local org-inline-image-overlays nil)
  17973. (defun org-toggle-inline-images (&optional include-linked)
  17974. "Toggle the display of inline images.
  17975. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17976. (interactive "P")
  17977. (if org-inline-image-overlays
  17978. (progn
  17979. (org-remove-inline-images)
  17980. (when (called-interactively-p 'interactive)
  17981. (message "Inline image display turned off")))
  17982. (org-display-inline-images include-linked)
  17983. (when (called-interactively-p 'interactive)
  17984. (message (if org-inline-image-overlays
  17985. (format "%d images displayed inline"
  17986. (length org-inline-image-overlays))
  17987. "No images to display inline")))))
  17988. (defun org-redisplay-inline-images ()
  17989. "Refresh the display of inline images."
  17990. (interactive)
  17991. (if (not org-inline-image-overlays)
  17992. (org-toggle-inline-images)
  17993. (org-toggle-inline-images)
  17994. (org-toggle-inline-images)))
  17995. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17996. "Display inline images.
  17997. An inline image is a link which follows either of these
  17998. conventions:
  17999. 1. Its path is a file with an extension matching return value
  18000. from `image-file-name-regexp' and it has no contents.
  18001. 2. Its description consists in a single link of the previous
  18002. type.
  18003. When optional argument INCLUDE-LINKED is non-nil, also links with
  18004. a text description part will be inlined. This can be nice for
  18005. a quick look at those images, but it does not reflect what
  18006. exported files will look like.
  18007. When optional argument REFRESH is non-nil, refresh existing
  18008. images between BEG and END. This will create new image displays
  18009. only if necessary. BEG and END default to the buffer
  18010. boundaries."
  18011. (interactive "P")
  18012. (when (display-graphic-p)
  18013. (unless refresh
  18014. (org-remove-inline-images)
  18015. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  18016. (org-with-wide-buffer
  18017. (goto-char (or beg (point-min)))
  18018. (let ((case-fold-search t)
  18019. (file-extension-re (image-file-name-regexp)))
  18020. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  18021. (let ((link (save-match-data (org-element-context))))
  18022. ;; Check if we're at an inline image.
  18023. (when (and (equal (org-element-property :type link) "file")
  18024. (or include-linked
  18025. (not (org-element-property :contents-begin link)))
  18026. (let ((parent (org-element-property :parent link)))
  18027. (or (not (eq (org-element-type parent) 'link))
  18028. (not (cdr (org-element-contents parent)))))
  18029. (string-match-p file-extension-re
  18030. (org-element-property :path link)))
  18031. (let ((file (expand-file-name
  18032. (org-link-unescape
  18033. (org-element-property :path link)))))
  18034. (when (file-exists-p file)
  18035. (let ((width
  18036. ;; Apply `org-image-actual-width' specifications.
  18037. (cond
  18038. ((not (image-type-available-p 'imagemagick)) nil)
  18039. ((eq org-image-actual-width t) nil)
  18040. ((listp org-image-actual-width)
  18041. (or
  18042. ;; First try to find a width among
  18043. ;; attributes associated to the paragraph
  18044. ;; containing link.
  18045. (let ((paragraph
  18046. (let ((e link))
  18047. (while (and (setq e (org-element-property
  18048. :parent e))
  18049. (not (eq (org-element-type e)
  18050. 'paragraph))))
  18051. e)))
  18052. (when paragraph
  18053. (save-excursion
  18054. (goto-char (org-element-property :begin paragraph))
  18055. (when
  18056. (re-search-forward
  18057. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18058. (org-element-property
  18059. :post-affiliated paragraph)
  18060. t)
  18061. (string-to-number (match-string 1))))))
  18062. ;; Otherwise, fall-back to provided number.
  18063. (car org-image-actual-width)))
  18064. ((numberp org-image-actual-width)
  18065. org-image-actual-width)))
  18066. (old (get-char-property-and-overlay
  18067. (org-element-property :begin link)
  18068. 'org-image-overlay)))
  18069. (if (and (car-safe old) refresh)
  18070. (image-refresh (overlay-get (cdr old) 'display))
  18071. (let ((image (create-image file
  18072. (and width 'imagemagick)
  18073. nil
  18074. :width width)))
  18075. (when image
  18076. (let* ((link
  18077. ;; If inline image is the description
  18078. ;; of another link, be sure to
  18079. ;; consider the latter as the one to
  18080. ;; apply the overlay on.
  18081. (let ((parent
  18082. (org-element-property :parent link)))
  18083. (if (eq (org-element-type parent) 'link)
  18084. parent
  18085. link)))
  18086. (ov (make-overlay
  18087. (org-element-property :begin link)
  18088. (progn
  18089. (goto-char
  18090. (org-element-property :end link))
  18091. (skip-chars-backward " \t")
  18092. (point)))))
  18093. (overlay-put ov 'display image)
  18094. (overlay-put ov 'face 'default)
  18095. (overlay-put ov 'org-image-overlay t)
  18096. (overlay-put
  18097. ov 'modification-hooks
  18098. (list 'org-display-inline-remove-overlay))
  18099. (push ov org-inline-image-overlays)))))))))))))))
  18100. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18101. "Remove inline-display overlay if a corresponding region is modified."
  18102. (let ((inhibit-modification-hooks t))
  18103. (when (and ov after)
  18104. (delete ov org-inline-image-overlays)
  18105. (delete-overlay ov))))
  18106. (defun org-remove-inline-images ()
  18107. "Remove inline display of images."
  18108. (interactive)
  18109. (mapc #'delete-overlay org-inline-image-overlays)
  18110. (setq org-inline-image-overlays nil))
  18111. ;;;; Key bindings
  18112. ;; Outline functions from `outline-mode-prefix-map'
  18113. ;; that can be remapped in Org:
  18114. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18115. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18116. (define-key org-mode-map [remap outline-forward-same-level]
  18117. 'org-forward-heading-same-level)
  18118. (define-key org-mode-map [remap outline-backward-same-level]
  18119. 'org-backward-heading-same-level)
  18120. (define-key org-mode-map [remap outline-show-branches]
  18121. 'org-kill-note-or-show-branches)
  18122. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18123. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18124. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18125. (define-key org-mode-map [remap outline-next-visible-heading]
  18126. 'org-next-visible-heading)
  18127. (define-key org-mode-map [remap outline-previous-visible-heading]
  18128. 'org-previous-visible-heading)
  18129. (define-key org-mode-map [remap show-children] 'org-show-children)
  18130. ;; Outline functions from `outline-mode-prefix-map' that can not
  18131. ;; be remapped in Org:
  18132. ;; - the column "key binding" shows whether the Outline function is still
  18133. ;; available in Org mode on the same key that it has been bound to in
  18134. ;; Outline mode:
  18135. ;; - "overridden": key used for a different functionality in Org mode
  18136. ;; - else: key still bound to the same Outline function in Org mode
  18137. ;; | Outline function | key binding | Org replacement |
  18138. ;; |------------------------------------+-------------+--------------------------|
  18139. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18140. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18141. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18142. ;; | `show-entry' | overridden | no replacement |
  18143. ;; | `show-branches' | `C-c C-k' | still same function |
  18144. ;; | `show-subtree' | overridden | visibility cycling |
  18145. ;; | `show-all' | overridden | no replacement |
  18146. ;; | `hide-subtree' | overridden | visibility cycling |
  18147. ;; | `hide-body' | overridden | no replacement |
  18148. ;; | `hide-entry' | overridden | visibility cycling |
  18149. ;; | `hide-leaves' | overridden | no replacement |
  18150. ;; | `hide-sublevels' | overridden | no replacement |
  18151. ;; | `hide-other' | overridden | no replacement |
  18152. ;; Make `C-c C-x' a prefix key
  18153. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18154. ;; TAB key with modifiers
  18155. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18156. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18157. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18158. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18159. ;; The following line is necessary under Suse GNU/Linux
  18160. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18161. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18162. (define-key org-mode-map [backtab] 'org-shifttab)
  18163. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18164. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18165. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18166. ;; Cursor keys with modifiers
  18167. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18168. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18169. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18170. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18171. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18172. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18173. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18174. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18175. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18176. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18177. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18178. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18179. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18180. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18181. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18182. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18183. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18184. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18185. ;; Babel keys
  18186. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18187. (dolist (pair org-babel-key-bindings)
  18188. (define-key org-babel-map (car pair) (cdr pair)))
  18189. ;;; Extra keys for tty access.
  18190. ;; We only set them when really needed because otherwise the
  18191. ;; menus don't show the simple keys
  18192. (when (or org-use-extra-keys (not window-system))
  18193. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18194. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18195. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18196. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18197. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18198. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18199. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18200. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18201. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18202. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18203. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18204. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18205. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18206. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18207. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18208. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18209. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18210. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18211. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18212. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18213. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18214. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18215. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18216. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18217. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18218. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18219. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18220. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18221. ;; All the other keys
  18222. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18223. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18224. (if (boundp 'narrow-map)
  18225. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18226. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18227. (if (boundp 'narrow-map)
  18228. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18229. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18230. (if (boundp 'narrow-map)
  18231. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18232. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18233. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18234. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18235. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18236. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18237. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18238. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18239. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18240. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18241. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18242. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18243. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18244. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18245. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18246. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18247. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18248. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18249. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18250. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18251. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18252. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18253. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18254. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18255. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18256. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18257. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18258. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18259. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18260. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18261. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18262. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18263. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18264. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18265. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18266. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18267. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18268. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18269. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18270. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18271. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18272. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18273. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18274. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18275. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18276. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18277. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18278. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18279. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18280. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18281. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18282. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18283. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18284. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18285. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18286. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18287. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18288. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18289. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18290. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18291. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18292. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18293. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18294. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18295. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18296. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18297. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18298. (org-defkey org-mode-map "\C-m" 'org-return)
  18299. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18300. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18301. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18302. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18303. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18304. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18305. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18306. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18307. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18308. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18309. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18310. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18311. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18312. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18313. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18314. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18315. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18316. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18317. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18318. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18319. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18320. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18321. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18322. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18323. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18324. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18325. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18326. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18327. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18328. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18329. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18330. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18331. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18332. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18333. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18334. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18335. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18336. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18337. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18338. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18339. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18340. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18341. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18342. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18343. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18344. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18345. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18346. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18347. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18348. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18349. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18350. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18351. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18352. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18353. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18354. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18355. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18356. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18357. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18358. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18359. (defconst org-speed-commands-default
  18360. '(
  18361. ("Outline Navigation")
  18362. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18363. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18364. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18365. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18366. ("F" . org-next-block)
  18367. ("B" . org-previous-block)
  18368. ("u" . (org-speed-move-safe 'outline-up-heading))
  18369. ("j" . org-goto)
  18370. ("g" . (org-refile t))
  18371. ("Outline Visibility")
  18372. ("c" . org-cycle)
  18373. ("C" . org-shifttab)
  18374. (" " . org-display-outline-path)
  18375. ("s" . org-narrow-to-subtree)
  18376. ("=" . org-columns)
  18377. ("Outline Structure Editing")
  18378. ("U" . org-metaup)
  18379. ("D" . org-metadown)
  18380. ("r" . org-metaright)
  18381. ("l" . org-metaleft)
  18382. ("R" . org-shiftmetaright)
  18383. ("L" . org-shiftmetaleft)
  18384. ("i" . (progn (forward-char 1) (call-interactively
  18385. 'org-insert-heading-respect-content)))
  18386. ("^" . org-sort)
  18387. ("w" . org-refile)
  18388. ("a" . org-archive-subtree-default-with-confirmation)
  18389. ("@" . org-mark-subtree)
  18390. ("#" . org-toggle-comment)
  18391. ("Clock Commands")
  18392. ("I" . org-clock-in)
  18393. ("O" . org-clock-out)
  18394. ("Meta Data Editing")
  18395. ("t" . org-todo)
  18396. ("," . (org-priority))
  18397. ("0" . (org-priority ?\ ))
  18398. ("1" . (org-priority ?A))
  18399. ("2" . (org-priority ?B))
  18400. ("3" . (org-priority ?C))
  18401. (":" . org-set-tags-command)
  18402. ("e" . org-set-effort)
  18403. ("E" . org-inc-effort)
  18404. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18405. (org-entry-put (point) "APPT_WARNTIME" m)))
  18406. ("Agenda Views etc")
  18407. ("v" . org-agenda)
  18408. ("/" . org-sparse-tree)
  18409. ("Misc")
  18410. ("o" . org-open-at-point)
  18411. ("?" . org-speed-command-help)
  18412. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18413. (">" . (org-agenda-remove-restriction-lock))
  18414. )
  18415. "The default speed commands.")
  18416. (defun org-print-speed-command (e)
  18417. (if (> (length (car e)) 1)
  18418. (progn
  18419. (princ "\n")
  18420. (princ (car e))
  18421. (princ "\n")
  18422. (princ (make-string (length (car e)) ?-))
  18423. (princ "\n"))
  18424. (princ (car e))
  18425. (princ " ")
  18426. (if (symbolp (cdr e))
  18427. (princ (symbol-name (cdr e)))
  18428. (prin1 (cdr e)))
  18429. (princ "\n")))
  18430. (defun org-speed-command-help ()
  18431. "Show the available speed commands."
  18432. (interactive)
  18433. (if (not org-use-speed-commands)
  18434. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18435. (with-output-to-temp-buffer "*Help*"
  18436. (princ "User-defined Speed commands\n===========================\n")
  18437. (mapc #'org-print-speed-command org-speed-commands-user)
  18438. (princ "\n")
  18439. (princ "Built-in Speed commands\n=======================\n")
  18440. (mapc #'org-print-speed-command org-speed-commands-default))
  18441. (with-current-buffer "*Help*"
  18442. (setq truncate-lines t))))
  18443. (defun org-speed-move-safe (cmd)
  18444. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18445. If not, return to the original position and throw an error."
  18446. (interactive)
  18447. (let ((pos (point)))
  18448. (call-interactively cmd)
  18449. (unless (and (bolp) (org-at-heading-p))
  18450. (goto-char pos)
  18451. (error "Boundary reached while executing %s" cmd))))
  18452. (defvar org-self-insert-command-undo-counter 0)
  18453. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18454. (defvar org-speed-command nil)
  18455. (defun org-speed-command-activate (keys)
  18456. "Hook for activating single-letter speed commands.
  18457. `org-speed-commands-default' specifies a minimal command set.
  18458. Use `org-speed-commands-user' for further customization."
  18459. (when (or (and (bolp) (looking-at org-outline-regexp))
  18460. (and (functionp org-use-speed-commands)
  18461. (funcall org-use-speed-commands)))
  18462. (cdr (assoc keys (append org-speed-commands-user
  18463. org-speed-commands-default)))))
  18464. (defun org-babel-speed-command-activate (keys)
  18465. "Hook for activating single-letter code block commands."
  18466. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18467. (cdr (assoc keys org-babel-key-bindings))))
  18468. (defcustom org-speed-command-hook
  18469. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18470. "Hook for activating speed commands at strategic locations.
  18471. Hook functions are called in sequence until a valid handler is
  18472. found.
  18473. Each hook takes a single argument, a user-pressed command key
  18474. which is also a `self-insert-command' from the global map.
  18475. Within the hook, examine the cursor position and the command key
  18476. and return nil or a valid handler as appropriate. Handler could
  18477. be one of an interactive command, a function, or a form.
  18478. Set `org-use-speed-commands' to non-nil value to enable this
  18479. hook. The default setting is `org-speed-command-activate'."
  18480. :group 'org-structure
  18481. :version "24.1"
  18482. :type 'hook)
  18483. (defun org-self-insert-command (N)
  18484. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18485. If the cursor is in a table looking at whitespace, the whitespace is
  18486. overwritten, and the table is not marked as requiring realignment."
  18487. (interactive "p")
  18488. (org-check-before-invisible-edit 'insert)
  18489. (cond
  18490. ((and org-use-speed-commands
  18491. (let ((kv (this-command-keys-vector)))
  18492. (setq org-speed-command
  18493. (run-hook-with-args-until-success
  18494. 'org-speed-command-hook
  18495. (make-string 1 (aref kv (1- (length kv))))))))
  18496. (cond
  18497. ((commandp org-speed-command)
  18498. (setq this-command org-speed-command)
  18499. (call-interactively org-speed-command))
  18500. ((functionp org-speed-command)
  18501. (funcall org-speed-command))
  18502. ((and org-speed-command (listp org-speed-command))
  18503. (eval org-speed-command))
  18504. (t (let (org-use-speed-commands)
  18505. (call-interactively 'org-self-insert-command)))))
  18506. ((and
  18507. (org-at-table-p)
  18508. (progn
  18509. ;; Check if we blank the field, and if that triggers align.
  18510. (and (featurep 'org-table) org-table-auto-blank-field
  18511. (memq last-command
  18512. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18513. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18514. ;; Got extra space, this field does not determine
  18515. ;; column width.
  18516. (let (org-table-may-need-update) (org-table-blank-field))
  18517. ;; No extra space, this field may determine column
  18518. ;; width.
  18519. (org-table-blank-field)))
  18520. t)
  18521. (eq N 1)
  18522. (looking-at "[^|\n]* \\( \\)|"))
  18523. ;; There is room for insertion without re-aligning the table.
  18524. (delete-region (match-beginning 1) (match-end 1))
  18525. (self-insert-command N))
  18526. (t
  18527. (setq org-table-may-need-update t)
  18528. (self-insert-command N)
  18529. (org-fix-tags-on-the-fly)
  18530. (when org-self-insert-cluster-for-undo
  18531. (if (not (eq last-command 'org-self-insert-command))
  18532. (setq org-self-insert-command-undo-counter 1)
  18533. (if (>= org-self-insert-command-undo-counter 20)
  18534. (setq org-self-insert-command-undo-counter 1)
  18535. (and (> org-self-insert-command-undo-counter 0)
  18536. buffer-undo-list (listp buffer-undo-list)
  18537. (not (cadr buffer-undo-list)) ; remove nil entry
  18538. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18539. (setq org-self-insert-command-undo-counter
  18540. (1+ org-self-insert-command-undo-counter))))))))
  18541. (defun org-check-before-invisible-edit (kind)
  18542. "Check is editing if kind KIND would be dangerous with invisible text around.
  18543. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18544. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18545. (when (and org-catch-invisible-edits
  18546. (or (not (boundp 'visible-mode)) (not visible-mode))
  18547. (or (get-char-property (point) 'invisible)
  18548. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18549. ;; OK, we need to take a closer look
  18550. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18551. (invisible-before-point (unless (bobp) (get-char-property
  18552. (1- (point)) 'invisible)))
  18553. (border-and-ok-direction
  18554. (or
  18555. ;; Check if we are acting predictably before invisible text
  18556. (and invisible-at-point (not invisible-before-point)
  18557. (memq kind '(insert delete-backward)))
  18558. ;; Check if we are acting predictably after invisible text
  18559. ;; This works not well, and I have turned it off. It seems
  18560. ;; better to always show and stop after invisible text.
  18561. ;; (and (not invisible-at-point) invisible-before-point
  18562. ;; (memq kind '(insert delete)))
  18563. )))
  18564. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18565. (memq invisible-before-point '(outline org-hide-block t)))
  18566. (when (eq org-catch-invisible-edits 'error)
  18567. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18568. (if (and org-custom-properties-overlays
  18569. (y-or-n-p "Display invisible properties in this buffer? "))
  18570. (org-toggle-custom-properties-visibility)
  18571. ;; Make the area visible
  18572. (save-excursion
  18573. (when invisible-before-point
  18574. (goto-char (previous-single-char-property-change
  18575. (point) 'invisible)))
  18576. (outline-show-subtree))
  18577. (cond
  18578. ((eq org-catch-invisible-edits 'show)
  18579. ;; That's it, we do the edit after showing
  18580. (message
  18581. "Unfolding invisible region around point before editing")
  18582. (sit-for 1))
  18583. ((and (eq org-catch-invisible-edits 'smart)
  18584. border-and-ok-direction)
  18585. (message "Unfolding invisible region around point before editing"))
  18586. (t
  18587. ;; Don't do the edit, make the user repeat it in full visibility
  18588. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18589. (defun org-fix-tags-on-the-fly ()
  18590. (when (and (equal (char-after (point-at-bol)) ?*)
  18591. (org-at-heading-p))
  18592. (org-align-tags-here org-tags-column)))
  18593. (defun org-delete-backward-char (N)
  18594. "Like `delete-backward-char', insert whitespace at field end in tables.
  18595. When deleting backwards, in tables this function will insert whitespace in
  18596. front of the next \"|\" separator, to keep the table aligned. The table will
  18597. still be marked for re-alignment if the field did fill the entire column,
  18598. because, in this case the deletion might narrow the column."
  18599. (interactive "p")
  18600. (save-match-data
  18601. (org-check-before-invisible-edit 'delete-backward)
  18602. (if (and (org-at-table-p)
  18603. (eq N 1)
  18604. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18605. (looking-at ".*?|"))
  18606. (let ((pos (point))
  18607. (noalign (looking-at "[^|\n\r]* |"))
  18608. (c org-table-may-need-update))
  18609. (backward-delete-char N)
  18610. (unless overwrite-mode
  18611. (skip-chars-forward "^|")
  18612. (insert " ")
  18613. (goto-char (1- pos)))
  18614. ;; noalign: if there were two spaces at the end, this field
  18615. ;; does not determine the width of the column.
  18616. (when noalign (setq org-table-may-need-update c)))
  18617. (backward-delete-char N)
  18618. (org-fix-tags-on-the-fly))))
  18619. (defun org-delete-char (N)
  18620. "Like `delete-char', but insert whitespace at field end in tables.
  18621. When deleting characters, in tables this function will insert whitespace in
  18622. front of the next \"|\" separator, to keep the table aligned. The table will
  18623. still be marked for re-alignment if the field did fill the entire column,
  18624. because, in this case the deletion might narrow the column."
  18625. (interactive "p")
  18626. (save-match-data
  18627. (org-check-before-invisible-edit 'delete)
  18628. (if (and (org-at-table-p)
  18629. (not (bolp))
  18630. (not (= (char-after) ?|))
  18631. (eq N 1))
  18632. (if (looking-at ".*?|")
  18633. (let ((pos (point))
  18634. (noalign (looking-at "[^|\n\r]* |"))
  18635. (c org-table-may-need-update))
  18636. (replace-match
  18637. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18638. (goto-char pos)
  18639. ;; noalign: if there were two spaces at the end, this field
  18640. ;; does not determine the width of the column.
  18641. (when noalign (setq org-table-may-need-update c)))
  18642. (delete-char N))
  18643. (delete-char N)
  18644. (org-fix-tags-on-the-fly))))
  18645. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18646. (put 'org-self-insert-command 'delete-selection
  18647. (lambda ()
  18648. (not (run-hook-with-args-until-success
  18649. 'self-insert-uses-region-functions))))
  18650. (put 'orgtbl-self-insert-command 'delete-selection
  18651. (lambda ()
  18652. (not (run-hook-with-args-until-success
  18653. 'self-insert-uses-region-functions))))
  18654. (put 'org-delete-char 'delete-selection 'supersede)
  18655. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18656. (put 'org-yank 'delete-selection 'yank)
  18657. ;; Make `flyspell-mode' delay after some commands
  18658. (put 'org-self-insert-command 'flyspell-delayed t)
  18659. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18660. (put 'org-delete-char 'flyspell-delayed t)
  18661. (put 'org-delete-backward-char 'flyspell-delayed t)
  18662. ;; Make pabbrev-mode expand after Org mode commands
  18663. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18664. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18665. (defun org-remap (map &rest commands)
  18666. "In MAP, remap the functions given in COMMANDS.
  18667. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18668. (let (new old)
  18669. (while commands
  18670. (setq old (pop commands) new (pop commands))
  18671. (if (fboundp 'command-remapping)
  18672. (org-defkey map (vector 'remap old) new)
  18673. (substitute-key-definition old new map global-map)))))
  18674. (defun org-transpose-words ()
  18675. "Transpose words for Org.
  18676. This uses the `org-mode-transpose-word-syntax-table' syntax
  18677. table, which interprets characters in `org-emphasis-alist' as
  18678. word constituents."
  18679. (interactive)
  18680. (with-syntax-table org-mode-transpose-word-syntax-table
  18681. (call-interactively 'transpose-words)))
  18682. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18683. (when (eq org-enable-table-editor 'optimized)
  18684. ;; If the user wants maximum table support, we need to hijack
  18685. ;; some standard editing functions
  18686. (org-remap org-mode-map
  18687. 'self-insert-command 'org-self-insert-command
  18688. 'delete-char 'org-delete-char
  18689. 'delete-backward-char 'org-delete-backward-char)
  18690. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18691. (defvar org-ctrl-c-ctrl-c-hook nil
  18692. "Hook for functions attaching themselves to `C-c C-c'.
  18693. This can be used to add additional functionality to the C-c C-c
  18694. key which executes context-dependent commands. This hook is run
  18695. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18696. run after the last test.
  18697. Each function will be called with no arguments. The function
  18698. must check if the context is appropriate for it to act. If yes,
  18699. it should do its thing and then return a non-nil value. If the
  18700. context is wrong, just do nothing and return nil.")
  18701. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18702. "Hook for functions attaching themselves to `C-c C-c'.
  18703. This can be used to add additional functionality to the C-c C-c
  18704. key which executes context-dependent commands. This hook is run
  18705. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18706. before the first test.
  18707. Each function will be called with no arguments. The function
  18708. must check if the context is appropriate for it to act. If yes,
  18709. it should do its thing and then return a non-nil value. If the
  18710. context is wrong, just do nothing and return nil.")
  18711. (defvar org-tab-first-hook nil
  18712. "Hook for functions to attach themselves to TAB.
  18713. See `org-ctrl-c-ctrl-c-hook' for more information.
  18714. This hook runs as the first action when TAB is pressed, even before
  18715. `org-cycle' messes around with the `outline-regexp' to cater for
  18716. inline tasks and plain list item folding.
  18717. If any function in this hook returns t, any other actions that
  18718. would have been caused by TAB (such as table field motion or visibility
  18719. cycling) will not occur.")
  18720. (defvar org-tab-after-check-for-table-hook nil
  18721. "Hook for functions to attach themselves to TAB.
  18722. See `org-ctrl-c-ctrl-c-hook' for more information.
  18723. This hook runs after it has been established that the cursor is not in a
  18724. table, but before checking if the cursor is in a headline or if global cycling
  18725. should be done.
  18726. If any function in this hook returns t, not other actions like visibility
  18727. cycling will be done.")
  18728. (defvar org-tab-after-check-for-cycling-hook nil
  18729. "Hook for functions to attach themselves to TAB.
  18730. See `org-ctrl-c-ctrl-c-hook' for more information.
  18731. This hook runs after it has been established that not table field motion and
  18732. not visibility should be done because of current context. This is probably
  18733. the place where a package like yasnippets can hook in.")
  18734. (defvar org-tab-before-tab-emulation-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 every other options for TAB have been exhausted, but
  18738. before indentation and \t insertion takes place.")
  18739. (defvar org-metaleft-hook nil
  18740. "Hook for functions attaching themselves to `M-left'.
  18741. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18742. (defvar org-metaright-hook nil
  18743. "Hook for functions attaching themselves to `M-right'.
  18744. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18745. (defvar org-metaup-hook nil
  18746. "Hook for functions attaching themselves to `M-up'.
  18747. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18748. (defvar org-metadown-hook nil
  18749. "Hook for functions attaching themselves to `M-down'.
  18750. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18751. (defvar org-shiftmetaleft-hook nil
  18752. "Hook for functions attaching themselves to `M-S-left'.
  18753. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18754. (defvar org-shiftmetaright-hook nil
  18755. "Hook for functions attaching themselves to `M-S-right'.
  18756. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18757. (defvar org-shiftmetaup-hook nil
  18758. "Hook for functions attaching themselves to `M-S-up'.
  18759. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18760. (defvar org-shiftmetadown-hook nil
  18761. "Hook for functions attaching themselves to `M-S-down'.
  18762. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18763. (defvar org-metareturn-hook nil
  18764. "Hook for functions attaching themselves to `M-RET'.
  18765. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18766. (defvar org-shiftup-hook nil
  18767. "Hook for functions attaching themselves to `S-up'.
  18768. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18769. (defvar org-shiftup-final-hook nil
  18770. "Hook for functions attaching themselves to `S-up'.
  18771. This one runs after all other options except shift-select have been excluded.
  18772. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18773. (defvar org-shiftdown-hook nil
  18774. "Hook for functions attaching themselves to `S-down'.
  18775. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18776. (defvar org-shiftdown-final-hook nil
  18777. "Hook for functions attaching themselves to `S-down'.
  18778. This one runs after all other options except shift-select have been excluded.
  18779. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18780. (defvar org-shiftleft-hook nil
  18781. "Hook for functions attaching themselves to `S-left'.
  18782. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18783. (defvar org-shiftleft-final-hook nil
  18784. "Hook for functions attaching themselves to `S-left'.
  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-shiftright-hook nil
  18788. "Hook for functions attaching themselves to `S-right'.
  18789. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18790. (defvar org-shiftright-final-hook nil
  18791. "Hook for functions attaching themselves to `S-right'.
  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. (defun org-modifier-cursor-error ()
  18795. "Throw an error, a modified cursor command was applied in wrong context."
  18796. (user-error "This command is active in special context like tables, headlines or items"))
  18797. (defun org-shiftselect-error ()
  18798. "Throw an error because Shift-Cursor command was applied in wrong context."
  18799. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18800. (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
  18801. (user-error "This command works only in special context like headlines or timestamps")))
  18802. (defun org-call-for-shift-select (cmd)
  18803. (let ((this-command-keys-shift-translated t))
  18804. (call-interactively cmd)))
  18805. (defun org-shifttab (&optional arg)
  18806. "Global visibility cycling or move to previous table field.
  18807. Call `org-table-previous-field' within a table.
  18808. When ARG is nil, cycle globally through visibility states.
  18809. When ARG is a numeric prefix, show contents of this level."
  18810. (interactive "P")
  18811. (cond
  18812. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18813. ((integerp arg)
  18814. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18815. (message "Content view to level: %d" arg)
  18816. (org-content (prefix-numeric-value arg2))
  18817. (org-cycle-show-empty-lines t)
  18818. (setq org-cycle-global-status 'overview)))
  18819. (t (call-interactively 'org-global-cycle))))
  18820. (defun org-shiftmetaleft ()
  18821. "Promote subtree or delete table column.
  18822. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18823. `org-table-delete-column', depending on context. See the
  18824. individual commands for more information."
  18825. (interactive)
  18826. (cond
  18827. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18828. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18829. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18830. ((if (not (org-region-active-p)) (org-at-item-p)
  18831. (save-excursion (goto-char (region-beginning))
  18832. (org-at-item-p)))
  18833. (call-interactively 'org-outdent-item-tree))
  18834. (t (org-modifier-cursor-error))))
  18835. (defun org-shiftmetaright ()
  18836. "Demote subtree or insert table column.
  18837. Calls `org-demote-subtree', `org-indent-item-tree', or
  18838. `org-table-insert-column', depending on context. See the
  18839. individual commands for more information."
  18840. (interactive)
  18841. (cond
  18842. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18843. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18844. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18845. ((if (not (org-region-active-p)) (org-at-item-p)
  18846. (save-excursion (goto-char (region-beginning))
  18847. (org-at-item-p)))
  18848. (call-interactively 'org-indent-item-tree))
  18849. (t (org-modifier-cursor-error))))
  18850. (defun org-shiftmetaup (&optional _arg)
  18851. "Drag the line at point up.
  18852. In a table, kill the current row.
  18853. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18854. but also adjust the previous clocked item in the clock history.
  18855. Everywhere else, drag the line at point up."
  18856. (interactive "P")
  18857. (cond
  18858. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18859. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18860. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18861. (call-interactively 'org-timestamp-up)))
  18862. (t (call-interactively 'org-drag-line-backward))))
  18863. (defun org-shiftmetadown (&optional _arg)
  18864. "Drag the line at point down.
  18865. In a table, insert an empty row at the current line.
  18866. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18867. but also adjust the previous clocked item in the clock history.
  18868. Everywhere else, drag the line at point down."
  18869. (interactive "P")
  18870. (cond
  18871. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18872. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18873. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18874. (call-interactively 'org-timestamp-down)))
  18875. (t (call-interactively 'org-drag-line-forward))))
  18876. (defsubst org-hidden-tree-error ()
  18877. (user-error
  18878. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18879. (defun org-metaleft (&optional _arg)
  18880. "Promote heading, list item at point or move table column left.
  18881. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18882. depending on context. With no specific context, calls the Emacs
  18883. default `backward-word'. See the individual commands for more
  18884. information.
  18885. This function runs the hook `org-metaleft-hook' as a first step,
  18886. and returns at first non-nil value."
  18887. (interactive "P")
  18888. (cond
  18889. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18890. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18891. ((org-with-limited-levels
  18892. (or (org-at-heading-p)
  18893. (and (org-region-active-p)
  18894. (save-excursion
  18895. (goto-char (region-beginning))
  18896. (org-at-heading-p)))))
  18897. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18898. (call-interactively 'org-do-promote))
  18899. ;; At an inline task.
  18900. ((org-at-heading-p)
  18901. (call-interactively 'org-inlinetask-promote))
  18902. ((or (org-at-item-p)
  18903. (and (org-region-active-p)
  18904. (save-excursion
  18905. (goto-char (region-beginning))
  18906. (org-at-item-p))))
  18907. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18908. (call-interactively 'org-outdent-item))
  18909. (t (call-interactively 'backward-word))))
  18910. (defun org-metaright (&optional _arg)
  18911. "Demote heading, list item at point or move table column right.
  18912. In front of a drawer or a block keyword, indent it correctly.
  18913. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18914. `org-indnet-drawer' or `org-indent-block' depending on context.
  18915. With no specific context, calls the Emacs default `forward-word'.
  18916. See the individual commands for more information.
  18917. This function runs the hook `org-metaright-hook' as a first step,
  18918. and returns at first non-nil value."
  18919. (interactive "P")
  18920. (cond
  18921. ((run-hook-with-args-until-success 'org-metaright-hook))
  18922. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18923. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18924. ((org-at-block-p) (call-interactively 'org-indent-block))
  18925. ((org-with-limited-levels
  18926. (or (org-at-heading-p)
  18927. (and (org-region-active-p)
  18928. (save-excursion
  18929. (goto-char (region-beginning))
  18930. (org-at-heading-p)))))
  18931. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18932. (call-interactively 'org-do-demote))
  18933. ;; At an inline task.
  18934. ((org-at-heading-p)
  18935. (call-interactively 'org-inlinetask-demote))
  18936. ((or (org-at-item-p)
  18937. (and (org-region-active-p)
  18938. (save-excursion
  18939. (goto-char (region-beginning))
  18940. (org-at-item-p))))
  18941. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18942. (call-interactively 'org-indent-item))
  18943. (t (call-interactively 'forward-word))))
  18944. (defun org-check-for-hidden (what)
  18945. "Check if there are hidden headlines/items in the current visual line.
  18946. WHAT can be either `headlines' or `items'. If the current line is
  18947. an outline or item heading and it has a folded subtree below it,
  18948. this function returns t, nil otherwise."
  18949. (let ((re (cond
  18950. ((eq what 'headlines) org-outline-regexp-bol)
  18951. ((eq what 'items) (org-item-beginning-re))
  18952. (t (error "This should not happen"))))
  18953. beg end)
  18954. (save-excursion
  18955. (catch 'exit
  18956. (unless (org-region-active-p)
  18957. (setq beg (point-at-bol))
  18958. (beginning-of-line 2)
  18959. (while (and (not (eobp)) ;; this is like `next-line'
  18960. (get-char-property (1- (point)) 'invisible))
  18961. (beginning-of-line 2))
  18962. (setq end (point))
  18963. (goto-char beg)
  18964. (goto-char (point-at-eol))
  18965. (setq end (max end (point)))
  18966. (while (re-search-forward re end t)
  18967. (when (get-char-property (match-beginning 0) 'invisible)
  18968. (throw 'exit t))))
  18969. nil))))
  18970. (defun org-metaup (&optional _arg)
  18971. "Move subtree up or move table row up.
  18972. Calls `org-move-subtree-up' or `org-table-move-row' or
  18973. `org-move-item-up', depending on context. See the individual commands
  18974. for more information."
  18975. (interactive "P")
  18976. (cond
  18977. ((run-hook-with-args-until-success 'org-metaup-hook))
  18978. ((org-region-active-p)
  18979. (let* ((a (min (region-beginning) (region-end)))
  18980. (b (1- (max (region-beginning) (region-end))))
  18981. (c (save-excursion (goto-char a)
  18982. (move-beginning-of-line 0)))
  18983. (d (save-excursion (goto-char a)
  18984. (move-end-of-line 0) (point))))
  18985. (transpose-regions a b c d)
  18986. (goto-char c)))
  18987. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18988. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18989. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18990. (t (org-drag-element-backward))))
  18991. (defun org-metadown (&optional _arg)
  18992. "Move subtree down or move table row down.
  18993. Calls `org-move-subtree-down' or `org-table-move-row' or
  18994. `org-move-item-down', depending on context. See the individual
  18995. commands for more information."
  18996. (interactive "P")
  18997. (cond
  18998. ((run-hook-with-args-until-success 'org-metadown-hook))
  18999. ((org-region-active-p)
  19000. (let* ((a (min (region-beginning) (region-end)))
  19001. (b (max (region-beginning) (region-end)))
  19002. (c (save-excursion (goto-char b)
  19003. (move-beginning-of-line 1)))
  19004. (d (save-excursion (goto-char b)
  19005. (move-end-of-line 1) (1+ (point)))))
  19006. (transpose-regions a b c d)
  19007. (goto-char d)))
  19008. ((org-at-table-p) (call-interactively 'org-table-move-row))
  19009. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  19010. ((org-at-item-p) (call-interactively 'org-move-item-down))
  19011. (t (org-drag-element-forward))))
  19012. (defun org-shiftup (&optional arg)
  19013. "Increase item in timestamp or increase priority of current headline.
  19014. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  19015. depending on context. See the individual commands for more information."
  19016. (interactive "P")
  19017. (cond
  19018. ((run-hook-with-args-until-success 'org-shiftup-hook))
  19019. ((and org-support-shift-select (org-region-active-p))
  19020. (org-call-for-shift-select 'previous-line))
  19021. ((org-at-timestamp-p t)
  19022. (call-interactively (if org-edit-timestamp-down-means-later
  19023. 'org-timestamp-down 'org-timestamp-up)))
  19024. ((and (not (eq org-support-shift-select 'always))
  19025. org-enable-priority-commands
  19026. (org-at-heading-p))
  19027. (call-interactively 'org-priority-up))
  19028. ((and (not org-support-shift-select) (org-at-item-p))
  19029. (call-interactively 'org-previous-item))
  19030. ((org-clocktable-try-shift 'up arg))
  19031. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  19032. (org-support-shift-select
  19033. (org-call-for-shift-select 'previous-line))
  19034. (t (org-shiftselect-error))))
  19035. (defun org-shiftdown (&optional arg)
  19036. "Decrease item in timestamp or decrease priority of current headline.
  19037. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  19038. depending on context. See the individual commands for more information."
  19039. (interactive "P")
  19040. (cond
  19041. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  19042. ((and org-support-shift-select (org-region-active-p))
  19043. (org-call-for-shift-select 'next-line))
  19044. ((org-at-timestamp-p t)
  19045. (call-interactively (if org-edit-timestamp-down-means-later
  19046. 'org-timestamp-up 'org-timestamp-down)))
  19047. ((and (not (eq org-support-shift-select 'always))
  19048. org-enable-priority-commands
  19049. (org-at-heading-p))
  19050. (call-interactively 'org-priority-down))
  19051. ((and (not org-support-shift-select) (org-at-item-p))
  19052. (call-interactively 'org-next-item))
  19053. ((org-clocktable-try-shift 'down arg))
  19054. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19055. (org-support-shift-select
  19056. (org-call-for-shift-select 'next-line))
  19057. (t (org-shiftselect-error))))
  19058. (defun org-shiftright (&optional arg)
  19059. "Cycle the thing at point or in the current line, depending on context.
  19060. Depending on context, this does one of the following:
  19061. - switch a timestamp at point one day into the future
  19062. - on a headline, switch to the next TODO keyword.
  19063. - on an item, switch entire list to the next bullet type
  19064. - on a property line, switch to the next allowed value
  19065. - on a clocktable definition line, move time block into the future"
  19066. (interactive "P")
  19067. (cond
  19068. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19069. ((and org-support-shift-select (org-region-active-p))
  19070. (org-call-for-shift-select 'forward-char))
  19071. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19072. ((and (not (eq org-support-shift-select 'always))
  19073. (org-at-heading-p))
  19074. (let ((org-inhibit-logging
  19075. (not org-treat-S-cursor-todo-selection-as-state-change))
  19076. (org-inhibit-blocking
  19077. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19078. (org-call-with-arg 'org-todo 'right)))
  19079. ((or (and org-support-shift-select
  19080. (not (eq org-support-shift-select 'always))
  19081. (org-at-item-bullet-p))
  19082. (and (not org-support-shift-select) (org-at-item-p)))
  19083. (org-call-with-arg 'org-cycle-list-bullet nil))
  19084. ((and (not (eq org-support-shift-select 'always))
  19085. (org-at-property-p))
  19086. (call-interactively 'org-property-next-allowed-value))
  19087. ((org-clocktable-try-shift 'right arg))
  19088. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19089. (org-support-shift-select
  19090. (org-call-for-shift-select 'forward-char))
  19091. (t (org-shiftselect-error))))
  19092. (defun org-shiftleft (&optional arg)
  19093. "Cycle the thing at point or in the current line, depending on context.
  19094. Depending on context, this does one of the following:
  19095. - switch a timestamp at point one day into the past
  19096. - on a headline, switch to the previous TODO keyword.
  19097. - on an item, switch entire list to the previous bullet type
  19098. - on a property line, switch to the previous allowed value
  19099. - on a clocktable definition line, move time block into the past"
  19100. (interactive "P")
  19101. (cond
  19102. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19103. ((and org-support-shift-select (org-region-active-p))
  19104. (org-call-for-shift-select 'backward-char))
  19105. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19106. ((and (not (eq org-support-shift-select 'always))
  19107. (org-at-heading-p))
  19108. (let ((org-inhibit-logging
  19109. (not org-treat-S-cursor-todo-selection-as-state-change))
  19110. (org-inhibit-blocking
  19111. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19112. (org-call-with-arg 'org-todo 'left)))
  19113. ((or (and org-support-shift-select
  19114. (not (eq org-support-shift-select 'always))
  19115. (org-at-item-bullet-p))
  19116. (and (not org-support-shift-select) (org-at-item-p)))
  19117. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19118. ((and (not (eq org-support-shift-select 'always))
  19119. (org-at-property-p))
  19120. (call-interactively 'org-property-previous-allowed-value))
  19121. ((org-clocktable-try-shift 'left arg))
  19122. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19123. (org-support-shift-select
  19124. (org-call-for-shift-select 'backward-char))
  19125. (t (org-shiftselect-error))))
  19126. (defun org-shiftcontrolright ()
  19127. "Switch to next TODO set."
  19128. (interactive)
  19129. (cond
  19130. ((and org-support-shift-select (org-region-active-p))
  19131. (org-call-for-shift-select 'forward-word))
  19132. ((and (not (eq org-support-shift-select 'always))
  19133. (org-at-heading-p))
  19134. (org-call-with-arg 'org-todo 'nextset))
  19135. (org-support-shift-select
  19136. (org-call-for-shift-select 'forward-word))
  19137. (t (org-shiftselect-error))))
  19138. (defun org-shiftcontrolleft ()
  19139. "Switch to previous TODO set."
  19140. (interactive)
  19141. (cond
  19142. ((and org-support-shift-select (org-region-active-p))
  19143. (org-call-for-shift-select 'backward-word))
  19144. ((and (not (eq org-support-shift-select 'always))
  19145. (org-at-heading-p))
  19146. (org-call-with-arg 'org-todo 'previousset))
  19147. (org-support-shift-select
  19148. (org-call-for-shift-select 'backward-word))
  19149. (t (org-shiftselect-error))))
  19150. (defun org-shiftcontrolup (&optional n)
  19151. "Change timestamps synchronously up in CLOCK log lines.
  19152. Optional argument N tells to change by that many units."
  19153. (interactive "P")
  19154. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19155. (let (org-support-shift-select)
  19156. (org-clock-timestamps-up n))
  19157. (user-error "Not at a clock log")))
  19158. (defun org-shiftcontroldown (&optional n)
  19159. "Change timestamps synchronously down in CLOCK log lines.
  19160. Optional argument N tells to change by that many units."
  19161. (interactive "P")
  19162. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19163. (let (org-support-shift-select)
  19164. (org-clock-timestamps-down n))
  19165. (user-error "Not at a clock log")))
  19166. (defun org-increase-number-at-point (&optional inc)
  19167. "Increment the number at point.
  19168. With an optional prefix numeric argument INC, increment using
  19169. this numeric value."
  19170. (interactive "p")
  19171. (if (not (number-at-point))
  19172. (user-error "Not on a number")
  19173. (unless inc (setq inc 1))
  19174. (let ((pos (point))
  19175. (beg (skip-chars-backward "-+^/*0-9eE."))
  19176. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19177. (setq nap (buffer-substring-no-properties
  19178. (+ pos beg) (+ pos beg end)))
  19179. (delete-region (+ pos beg) (+ pos beg end))
  19180. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19181. (when (org-at-table-p)
  19182. (org-table-align)
  19183. (org-table-end-of-field 1))))
  19184. (defun org-decrease-number-at-point (&optional inc)
  19185. "Decrement the number at point.
  19186. With an optional prefix numeric argument INC, decrement using
  19187. this numeric value."
  19188. (interactive "p")
  19189. (org-increase-number-at-point (- (or inc 1))))
  19190. (defun org-ctrl-c-ret ()
  19191. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19192. (interactive)
  19193. (cond
  19194. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19195. (t (call-interactively 'org-insert-heading))))
  19196. (defun org-find-visible ()
  19197. (let ((s (point)))
  19198. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19199. (get-char-property s 'invisible)))
  19200. s))
  19201. (defun org-find-invisible ()
  19202. (let ((s (point)))
  19203. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19204. (not (get-char-property s 'invisible))))
  19205. s))
  19206. (defun org-copy-visible (beg end)
  19207. "Copy the visible parts of the region."
  19208. (interactive "r")
  19209. (let (snippets s)
  19210. (save-excursion
  19211. (save-restriction
  19212. (narrow-to-region beg end)
  19213. (setq s (goto-char (point-min)))
  19214. (while (not (= (point) (point-max)))
  19215. (goto-char (org-find-invisible))
  19216. (push (buffer-substring s (point)) snippets)
  19217. (setq s (goto-char (org-find-visible))))))
  19218. (kill-new (apply 'concat (nreverse snippets)))))
  19219. (defun org-copy-special ()
  19220. "Copy region in table or copy current subtree.
  19221. Calls `org-table-copy' or `org-copy-subtree', depending on context.
  19222. See the individual commands for more information."
  19223. (interactive)
  19224. (call-interactively
  19225. (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
  19226. (defun org-cut-special ()
  19227. "Cut region in table or cut current subtree.
  19228. Calls `org-table-copy' or `org-cut-subtree', depending on context.
  19229. See the individual commands for more information."
  19230. (interactive)
  19231. (call-interactively
  19232. (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
  19233. (defun org-paste-special (arg)
  19234. "Paste rectangular region into table, or past subtree relative to level.
  19235. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19236. See the individual commands for more information."
  19237. (interactive "P")
  19238. (if (org-at-table-p)
  19239. (org-table-paste-rectangle)
  19240. (org-paste-subtree arg)))
  19241. (defsubst org-in-fixed-width-region-p ()
  19242. "Is point in a fixed-width region?"
  19243. (save-match-data
  19244. (eq 'fixed-width (org-element-type (org-element-at-point)))))
  19245. (defun org-edit-special (&optional arg)
  19246. "Call a special editor for the element at point.
  19247. When at a table, call the formula editor with `org-table-edit-formulas'.
  19248. When in a source code block, call `org-edit-src-code'.
  19249. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19250. When in an export block, call `org-edit-export-block'.
  19251. When at an #+INCLUDE keyword, visit the included file.
  19252. When at a footnote reference, call `org-edit-footnote-reference'
  19253. On a link, call `ffap' to visit the link at point.
  19254. Otherwise, return a user error."
  19255. (interactive "P")
  19256. (let ((element (org-element-at-point)))
  19257. (cl-assert (not buffer-read-only) nil
  19258. "Buffer is read-only: %s" (buffer-name))
  19259. (pcase (org-element-type element)
  19260. (`src-block
  19261. (if (not arg) (org-edit-src-code)
  19262. (let* ((info (org-babel-get-src-block-info))
  19263. (lang (nth 0 info))
  19264. (params (nth 2 info))
  19265. (session (cdr (assq :session params))))
  19266. (if (not session) (org-edit-src-code)
  19267. ;; At a src-block with a session and function called with
  19268. ;; an ARG: switch to the buffer related to the inferior
  19269. ;; process.
  19270. (switch-to-buffer
  19271. (funcall (intern (concat "org-babel-prep-session:" lang))
  19272. session params))))))
  19273. (`keyword
  19274. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19275. (org-open-link-from-string
  19276. (format "[[%s]]"
  19277. (expand-file-name
  19278. (let ((value (org-element-property :value element)))
  19279. (cond ((not (org-string-nw-p value))
  19280. (user-error "No file to edit"))
  19281. ((string-match "\\`\"\\(.*?\\)\"" value)
  19282. (match-string 1 value))
  19283. ((string-match "\\`[^ \t\"]\\S-*" value)
  19284. (match-string 0 value))
  19285. (t (user-error "No valid file specified")))))))
  19286. (user-error "No special environment to edit here")))
  19287. (`table
  19288. (if (eq (org-element-property :type element) 'table.el)
  19289. (org-edit-table.el)
  19290. (call-interactively 'org-table-edit-formulas)))
  19291. ;; Only Org tables contain `table-row' type elements.
  19292. (`table-row (call-interactively 'org-table-edit-formulas))
  19293. (`example-block (org-edit-src-code))
  19294. (`export-block (org-edit-export-block))
  19295. (`fixed-width (org-edit-fixed-width-region))
  19296. (_
  19297. ;; No notable element at point. Though, we may be at a link or
  19298. ;; a footnote reference, which are objects. Thus, scan deeper.
  19299. (let ((context (org-element-context element)))
  19300. (pcase (org-element-type context)
  19301. (`footnote-reference (org-edit-footnote-reference))
  19302. (`inline-src-block (org-edit-inline-src-code))
  19303. (`link (call-interactively #'ffap))
  19304. (_ (user-error "No special environment to edit here"))))))))
  19305. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19306. (defun org-ctrl-c-ctrl-c (&optional arg)
  19307. "Set tags in headline, or update according to changed information at point.
  19308. This command does many different things, depending on context:
  19309. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19310. this is what we do.
  19311. - If the cursor is on a statistics cookie, update it.
  19312. - If the cursor is in a headline, prompt for tags and insert them
  19313. into the current line, aligned to `org-tags-column'. When called
  19314. with prefix arg, realign all tags in the current buffer.
  19315. - If the cursor is in one of the special #+KEYWORD lines, this
  19316. triggers scanning the buffer for these lines and updating the
  19317. information.
  19318. - If the cursor is inside a table, realign the table. This command
  19319. works even if the automatic table editor has been turned off.
  19320. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19321. the entire table.
  19322. - If the cursor is at a footnote reference or definition, jump to
  19323. the corresponding definition or references, respectively.
  19324. - If the cursor is a the beginning of a dynamic block, update it.
  19325. - If the current buffer is a capture buffer, close note and file it.
  19326. - If the cursor is on a <<<target>>>, update radio targets and
  19327. corresponding links in this buffer.
  19328. - If the cursor is on a numbered item in a plain list, renumber the
  19329. ordered list.
  19330. - If the cursor is on a checkbox, toggle it.
  19331. - If the cursor is on a code block, evaluate it. The variable
  19332. `org-confirm-babel-evaluate' can be used to control prompting
  19333. before code block evaluation, by default every code block
  19334. evaluation requires confirmation. Code block evaluation can be
  19335. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19336. (interactive "P")
  19337. (cond
  19338. ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
  19339. org-occur-highlights)
  19340. (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19341. (org-remove-occur-highlights)
  19342. (message "Temporary highlights/overlays removed from current buffer"))
  19343. ((and (local-variable-p 'org-finish-function (current-buffer))
  19344. (fboundp org-finish-function))
  19345. (funcall org-finish-function))
  19346. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19347. (t
  19348. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  19349. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19350. (user-error "C-c C-c can do nothing useful at this location"))
  19351. (let* ((context (org-element-context))
  19352. (type (org-element-type context)))
  19353. (cl-case type
  19354. ;; When at a link, act according to the parent instead.
  19355. (link (setq context (org-element-property :parent context))
  19356. (setq type (org-element-type context)))
  19357. ;; Unsupported object types: refer to the first supported
  19358. ;; element or object containing it.
  19359. ((bold code entity export-snippet inline-babel-call inline-src-block
  19360. italic latex-fragment line-break macro strike-through subscript
  19361. superscript underline verbatim)
  19362. (setq context
  19363. (org-element-lineage
  19364. context '(radio-target paragraph verse-block table-cell)))))
  19365. ;; For convenience: at the first line of a paragraph on the
  19366. ;; same line as an item, apply function on that item instead.
  19367. (when (eq type 'paragraph)
  19368. (let ((parent (org-element-property :parent context)))
  19369. (when (and (eq (org-element-type parent) 'item)
  19370. (= (line-beginning-position)
  19371. (org-element-property :begin parent)))
  19372. (setq context parent type 'item))))
  19373. ;; Act according to type of element or object at point.
  19374. (cl-case type
  19375. (clock (org-clock-update-time-maybe))
  19376. (dynamic-block
  19377. (save-excursion
  19378. (goto-char (org-element-property :post-affiliated context))
  19379. (org-update-dblock)))
  19380. (footnote-definition
  19381. (goto-char (org-element-property :post-affiliated context))
  19382. (call-interactively 'org-footnote-action))
  19383. (footnote-reference (call-interactively 'org-footnote-action))
  19384. ((headline inlinetask)
  19385. (save-excursion (goto-char (org-element-property :begin context))
  19386. (call-interactively 'org-set-tags)))
  19387. (item
  19388. ;; At an item: a double C-u set checkbox to "[-]"
  19389. ;; unconditionally, whereas a single one will toggle its
  19390. ;; presence. Without a universal argument, if the item
  19391. ;; has a checkbox, toggle it. Otherwise repair the list.
  19392. (let* ((box (org-element-property :checkbox context))
  19393. (struct (org-element-property :structure context))
  19394. (old-struct (copy-tree struct))
  19395. (parents (org-list-parents-alist struct))
  19396. (prevs (org-list-prevs-alist struct))
  19397. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19398. (org-list-set-checkbox
  19399. (org-element-property :begin context) struct
  19400. (cond ((equal arg '(16)) "[-]")
  19401. ((and (not box) (equal arg '(4))) "[ ]")
  19402. ((or (not box) (equal arg '(4))) nil)
  19403. ((eq box 'on) "[ ]")
  19404. (t "[X]")))
  19405. ;; Mimic `org-list-write-struct' but with grabbing
  19406. ;; a return value from `org-list-struct-fix-box'.
  19407. (org-list-struct-fix-ind struct parents 2)
  19408. (org-list-struct-fix-item-end struct)
  19409. (org-list-struct-fix-bul struct prevs)
  19410. (org-list-struct-fix-ind struct parents)
  19411. (let ((block-item
  19412. (org-list-struct-fix-box struct parents prevs orderedp)))
  19413. (if (and box (equal struct old-struct))
  19414. (if (equal arg '(16))
  19415. (message "Checkboxes already reset")
  19416. (user-error "Cannot toggle this checkbox: %s"
  19417. (if (eq box 'on)
  19418. "all subitems checked"
  19419. "unchecked subitems")))
  19420. (org-list-struct-apply-struct struct old-struct)
  19421. (org-update-checkbox-count-maybe))
  19422. (when block-item
  19423. (message "Checkboxes were removed due to empty box at line %d"
  19424. (org-current-line block-item))))))
  19425. (keyword
  19426. (let ((org-inhibit-startup-visibility-stuff t)
  19427. (org-startup-align-all-tables nil))
  19428. (when (boundp 'org-table-coordinate-overlays)
  19429. (mapc #'delete-overlay org-table-coordinate-overlays)
  19430. (setq org-table-coordinate-overlays nil))
  19431. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19432. (message "Local setup has been refreshed"))
  19433. (plain-list
  19434. ;; At a plain list, with a double C-u argument, set
  19435. ;; checkboxes of each item to "[-]", whereas a single one
  19436. ;; will toggle their presence according to the state of the
  19437. ;; first item in the list. Without an argument, repair the
  19438. ;; list.
  19439. (let* ((begin (org-element-property :contents-begin context))
  19440. (beginm (move-marker (make-marker) begin))
  19441. (struct (org-element-property :structure context))
  19442. (old-struct (copy-tree struct))
  19443. (first-box (save-excursion
  19444. (goto-char begin)
  19445. (looking-at org-list-full-item-re)
  19446. (match-string-no-properties 3)))
  19447. (new-box (cond ((equal arg '(16)) "[-]")
  19448. ((equal arg '(4)) (unless first-box "[ ]"))
  19449. ((equal first-box "[X]") "[ ]")
  19450. (t "[X]"))))
  19451. (cond
  19452. (arg
  19453. (dolist (pos
  19454. (org-list-get-all-items
  19455. begin struct (org-list-prevs-alist struct)))
  19456. (org-list-set-checkbox pos struct new-box)))
  19457. ((and first-box (eq (point) begin))
  19458. ;; For convenience, when point is at bol on the first
  19459. ;; item of the list and no argument is provided, simply
  19460. ;; toggle checkbox of that item, if any.
  19461. (org-list-set-checkbox begin struct new-box)))
  19462. (org-list-write-struct
  19463. struct (org-list-parents-alist struct) old-struct)
  19464. (org-update-checkbox-count-maybe)
  19465. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19466. ((property-drawer node-property)
  19467. (call-interactively 'org-property-action))
  19468. ((radio-target target)
  19469. (call-interactively 'org-update-radio-target-regexp))
  19470. (statistics-cookie
  19471. (call-interactively 'org-update-statistics-cookies))
  19472. ((table table-cell table-row)
  19473. ;; At a table, recalculate every field and align it. Also
  19474. ;; send the table if necessary. If the table has
  19475. ;; a `table.el' type, just give up. At a table row or
  19476. ;; cell, maybe recalculate line but always align table.
  19477. (if (eq (org-element-property :type context) 'table.el)
  19478. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19479. Use \\[org-edit-special] to edit table.el tables"))
  19480. (let ((org-enable-table-editor t))
  19481. (if (or (eq type 'table)
  19482. ;; Check if point is at a TBLFM line.
  19483. (and (eq type 'table-row)
  19484. (= (point) (org-element-property :end context))))
  19485. (save-excursion
  19486. (if (org-at-TBLFM-p)
  19487. (progn (require 'org-table)
  19488. (org-table-calc-current-TBLFM))
  19489. (goto-char (org-element-property :contents-begin context))
  19490. (org-call-with-arg 'org-table-recalculate (or arg t))
  19491. (orgtbl-send-table 'maybe)))
  19492. (org-table-maybe-eval-formula)
  19493. (cond (arg (call-interactively 'org-table-recalculate))
  19494. ((org-table-maybe-recalculate-line))
  19495. (t (org-table-align)))))))
  19496. (timestamp (org-timestamp-change 0 'day))
  19497. (otherwise
  19498. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19499. (user-error
  19500. "C-c C-c can do nothing useful at this location")))))))))
  19501. (defun org-mode-restart ()
  19502. (interactive)
  19503. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19504. (funcall major-mode)
  19505. (hack-local-variables)
  19506. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19507. (org-indent-mode -1)))
  19508. (message "%s restarted" major-mode))
  19509. (defun org-kill-note-or-show-branches ()
  19510. "If this is a Note buffer, abort storing the note. Else call `show-branches'."
  19511. (interactive)
  19512. (if (not org-finish-function)
  19513. (progn
  19514. (outline-hide-subtree)
  19515. (call-interactively 'outline-show-branches))
  19516. (let ((org-note-abort t))
  19517. (funcall org-finish-function))))
  19518. (defun org-delete-indentation (&optional ARG)
  19519. "Join current line to previous and fix whitespace at join.
  19520. If previous line is a headline add to headline title. Otherwise
  19521. the function calls `delete-indentation'.
  19522. With argument, join this line to following line."
  19523. (interactive "*P")
  19524. (if (save-excursion
  19525. (if ARG (beginning-of-line)
  19526. (forward-line -1))
  19527. (looking-at org-complex-heading-regexp))
  19528. ;; At headline.
  19529. (let ((tags-column (when (match-beginning 5)
  19530. (save-excursion (goto-char (match-beginning 5))
  19531. (current-column))))
  19532. (string (concat " " (progn (when ARG (forward-line 1))
  19533. (org-trim (delete-and-extract-region
  19534. (line-beginning-position)
  19535. (line-end-position)))))))
  19536. (unless (bobp) (delete-region (point) (1- (point))))
  19537. (goto-char (or (match-end 4)
  19538. (match-beginning 5)
  19539. (match-end 0)))
  19540. (skip-chars-backward " \t")
  19541. (save-excursion (insert string))
  19542. ;; Adjust alignment of tags.
  19543. (when tags-column
  19544. (org-align-tags-here (if org-auto-align-tags
  19545. org-tags-column
  19546. tags-column))))
  19547. (delete-indentation ARG)))
  19548. (defun org-open-line (n)
  19549. "Insert a new row in tables, call `open-line' elsewhere.
  19550. If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
  19551. (interactive "*p")
  19552. (cond
  19553. ((not org-special-ctrl-o)
  19554. (open-line n))
  19555. ((org-at-table-p)
  19556. (org-table-insert-row))
  19557. (t
  19558. (open-line n))))
  19559. (defun org-return (&optional indent)
  19560. "Goto next table row or insert a newline.
  19561. Calls `org-table-next-row' or `newline', depending on context.
  19562. When optional INDENT argument is non-nil, call
  19563. `newline-and-indent' instead of `newline'.
  19564. When `org-return-follows-link' is non-nil and point is on
  19565. a timestamp or a link, call `org-open-at-point'. However, it
  19566. will not happen if point is in a table or on a \"dead\"
  19567. object (e.g., within a comment). In these case, you need to use
  19568. `org-open-at-point' directly."
  19569. (interactive)
  19570. (let ((context (if org-return-follows-link (org-element-context)
  19571. (org-element-at-point))))
  19572. (cond
  19573. ;; In a table, call `org-table-next-row'.
  19574. ((or (and (eq (org-element-type context) 'table)
  19575. (>= (point) (org-element-property :contents-begin context))
  19576. (< (point) (org-element-property :contents-end context)))
  19577. (org-element-lineage context '(table-row table-cell) t))
  19578. (org-table-justify-field-maybe)
  19579. (call-interactively #'org-table-next-row))
  19580. ;; On a link or a timestamp, call `org-open-at-point' if
  19581. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19582. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19583. ((and org-return-follows-link
  19584. (or (org-in-regexp org-ts-regexp-both nil t)
  19585. (org-in-regexp org-tsr-regexp-both nil t)
  19586. (org-in-regexp org-any-link-re nil t)))
  19587. (call-interactively #'org-open-at-point))
  19588. ;; Insert newline in heading, but preserve tags.
  19589. ((and (not (bolp))
  19590. (save-excursion (beginning-of-line)
  19591. (looking-at org-complex-heading-regexp)))
  19592. ;; At headline. Split line. However, if point is on keyword,
  19593. ;; priority cookie or tags, do not break any of them: add
  19594. ;; a newline after the headline instead.
  19595. (let ((tags-column (and (match-beginning 5)
  19596. (save-excursion (goto-char (match-beginning 5))
  19597. (current-column))))
  19598. (string
  19599. (when (and (match-end 4)
  19600. (>= (point)
  19601. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19602. (<= (point) (match-end 4)))
  19603. (delete-and-extract-region (point) (match-end 4)))))
  19604. (when (and tags-column string) ; Adjust tag alignment.
  19605. (org-align-tags-here
  19606. (if org-auto-align-tags org-tags-column tags-column)))
  19607. (end-of-line)
  19608. (org-show-entry)
  19609. (if indent (newline-and-indent) (newline))
  19610. (when string (save-excursion (insert (org-trim string))))))
  19611. ;; In a list, make sure indenting keeps trailing text within.
  19612. ((and indent
  19613. (not (eolp))
  19614. (org-element-lineage context '(item)))
  19615. (let ((trailing-data
  19616. (delete-and-extract-region (point) (line-end-position))))
  19617. (newline-and-indent)
  19618. (save-excursion (insert trailing-data))))
  19619. (t (if indent (newline-and-indent) (newline))))))
  19620. (defun org-return-indent ()
  19621. "Goto next table row or insert a newline and indent.
  19622. Calls `org-table-next-row' or `newline-and-indent', depending on
  19623. context. See the individual commands for more information."
  19624. (interactive)
  19625. (org-return t))
  19626. (defun org-ctrl-c-star ()
  19627. "Compute table, or change heading status of lines.
  19628. Calls `org-table-recalculate' or `org-toggle-heading',
  19629. depending on context."
  19630. (interactive)
  19631. (cond
  19632. ((org-at-table-p)
  19633. (call-interactively 'org-table-recalculate))
  19634. (t
  19635. ;; Convert all lines in region to list items
  19636. (call-interactively 'org-toggle-heading))))
  19637. (defun org-ctrl-c-minus ()
  19638. "Insert separator line in table or modify bullet status of line.
  19639. Also turns a plain line or a region of lines into list items.
  19640. Calls `org-table-insert-hline', `org-toggle-item', or
  19641. `org-cycle-list-bullet', depending on context."
  19642. (interactive)
  19643. (cond
  19644. ((org-at-table-p)
  19645. (call-interactively 'org-table-insert-hline))
  19646. ((org-region-active-p)
  19647. (call-interactively 'org-toggle-item))
  19648. ((org-in-item-p)
  19649. (call-interactively 'org-cycle-list-bullet))
  19650. (t
  19651. (call-interactively 'org-toggle-item))))
  19652. (defun org-toggle-heading (&optional nstars)
  19653. "Convert headings to normal text, or items or text to headings.
  19654. If there is no active region, only convert the current line.
  19655. With a \\[universal-argument] prefix, convert the whole list at
  19656. point into heading.
  19657. In a region:
  19658. - If the first non blank line is a headline, remove the stars
  19659. from all headlines in the region.
  19660. - If it is a normal line, turn each and every normal line (i.e.,
  19661. not an heading or an item) in the region into headings. If you
  19662. want to convert only the first line of this region, use one
  19663. universal prefix argument.
  19664. - If it is a plain list item, turn all plain list items into headings.
  19665. When converting a line into a heading, the number of stars is chosen
  19666. such that the lines become children of the current entry. However,
  19667. when a numeric prefix argument is given, its value determines the
  19668. number of stars to add."
  19669. (interactive "P")
  19670. (let ((skip-blanks
  19671. (function
  19672. ;; Return beginning of first non-blank line, starting from
  19673. ;; line at POS.
  19674. (lambda (pos)
  19675. (save-excursion
  19676. (goto-char pos)
  19677. (while (org-at-comment-p) (forward-line))
  19678. (skip-chars-forward " \r\t\n")
  19679. (point-at-bol)))))
  19680. beg end toggled)
  19681. ;; Determine boundaries of changes. If a universal prefix has
  19682. ;; been given, put the list in a region. If region ends at a bol,
  19683. ;; do not consider the last line to be in the region.
  19684. (when (and current-prefix-arg (org-at-item-p))
  19685. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19686. (org-mark-element))
  19687. (if (org-region-active-p)
  19688. (setq beg (funcall skip-blanks (region-beginning))
  19689. end (copy-marker (save-excursion
  19690. (goto-char (region-end))
  19691. (if (bolp) (point) (point-at-eol)))))
  19692. (setq beg (funcall skip-blanks (point-at-bol))
  19693. end (copy-marker (point-at-eol))))
  19694. ;; Ensure inline tasks don't count as headings.
  19695. (org-with-limited-levels
  19696. (save-excursion
  19697. (goto-char beg)
  19698. (cond
  19699. ;; Case 1. Started at an heading: de-star headings.
  19700. ((org-at-heading-p)
  19701. (while (< (point) end)
  19702. (when (org-at-heading-p t)
  19703. (looking-at org-outline-regexp) (replace-match "")
  19704. (setq toggled t))
  19705. (forward-line)))
  19706. ;; Case 2. Started at an item: change items into headlines.
  19707. ;; One star will be added by `org-list-to-subtree'.
  19708. ((org-at-item-p)
  19709. (while (< (point) end)
  19710. (when (org-at-item-p)
  19711. ;; Pay attention to cases when region ends before list.
  19712. (let* ((struct (org-list-struct))
  19713. (list-end
  19714. (min (org-list-get-bottom-point struct) (1+ end))))
  19715. (save-restriction
  19716. (narrow-to-region (point) list-end)
  19717. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19718. (setq toggled t))
  19719. (forward-line)))
  19720. ;; Case 3. Started at normal text: make every line an heading,
  19721. ;; skipping headlines and items.
  19722. (t (let* ((stars
  19723. (make-string
  19724. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19725. (add-stars
  19726. (cond (nstars "") ; stars from prefix only
  19727. ((equal stars "") "*") ; before first heading
  19728. (org-odd-levels-only "**") ; inside heading, odd
  19729. (t "*"))) ; inside heading, oddeven
  19730. (rpl (concat stars add-stars " "))
  19731. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19732. (while (< (point) (if (equal nstars '(4)) lend end))
  19733. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19734. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19735. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19736. (forward-line)))))))
  19737. (unless toggled (message "Cannot toggle heading from here"))))
  19738. (defun org-meta-return (&optional _arg)
  19739. "Insert a new heading or wrap a region in a table.
  19740. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19741. on context. See the individual commands for more information."
  19742. (interactive)
  19743. (org-check-before-invisible-edit 'insert)
  19744. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19745. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19746. #'org-insert-heading))))
  19747. ;;; Menu entries
  19748. (defsubst org-in-subtree-not-table-p ()
  19749. "Are we in a subtree and not in a table?"
  19750. (and (not (org-before-first-heading-p))
  19751. (not (org-at-table-p))))
  19752. ;; Define the Org mode menus
  19753. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19754. '("Tbl"
  19755. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19756. ["Next Field" org-cycle (org-at-table-p)]
  19757. ["Previous Field" org-shifttab (org-at-table-p)]
  19758. ["Next Row" org-return (org-at-table-p)]
  19759. "--"
  19760. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19761. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19762. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19763. "--"
  19764. ("Column"
  19765. ["Move Column Left" org-metaleft (org-at-table-p)]
  19766. ["Move Column Right" org-metaright (org-at-table-p)]
  19767. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19768. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19769. ("Row"
  19770. ["Move Row Up" org-metaup (org-at-table-p)]
  19771. ["Move Row Down" org-metadown (org-at-table-p)]
  19772. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19773. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19774. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19775. "--"
  19776. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19777. ("Rectangle"
  19778. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19779. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19780. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19781. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19782. "--"
  19783. ("Calculate"
  19784. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19785. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19786. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19787. "--"
  19788. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19789. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19790. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19791. "--"
  19792. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19793. "--"
  19794. ["Sum Column/Rectangle" org-table-sum
  19795. (or (org-at-table-p) (org-region-active-p))]
  19796. ["Which Column?" org-table-current-column (org-at-table-p)])
  19797. ["Debug Formulas"
  19798. org-table-toggle-formula-debugger
  19799. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19800. ["Show Col/Row Numbers"
  19801. org-table-toggle-coordinate-overlays
  19802. :style toggle
  19803. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19804. "--"
  19805. ["Create" org-table-create (and (not (org-at-table-p))
  19806. org-enable-table-editor)]
  19807. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19808. ["Import from File" org-table-import (not (org-at-table-p))]
  19809. ["Export to File" org-table-export (org-at-table-p)]
  19810. "--"
  19811. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19812. "--"
  19813. ("Plot"
  19814. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19815. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19816. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19817. '("Org"
  19818. ("Show/Hide"
  19819. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19820. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19821. ["Sparse Tree..." org-sparse-tree t]
  19822. ["Reveal Context" org-reveal t]
  19823. ["Show All" outline-show-all t]
  19824. "--"
  19825. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19826. "--"
  19827. ["New Heading" org-insert-heading t]
  19828. ("Navigate Headings"
  19829. ["Up" outline-up-heading t]
  19830. ["Next" outline-next-visible-heading t]
  19831. ["Previous" outline-previous-visible-heading t]
  19832. ["Next Same Level" outline-forward-same-level t]
  19833. ["Previous Same Level" outline-backward-same-level t]
  19834. "--"
  19835. ["Jump" org-goto t])
  19836. ("Edit Structure"
  19837. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19838. "--"
  19839. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19840. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19841. "--"
  19842. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19843. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19844. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19845. "--"
  19846. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19847. "--"
  19848. ["Copy visible text" org-copy-visible t]
  19849. "--"
  19850. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19851. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19852. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19853. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19854. "--"
  19855. ["Sort Region/Children" org-sort t]
  19856. "--"
  19857. ["Convert to odd levels" org-convert-to-odd-levels t]
  19858. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19859. ("Editing"
  19860. ["Emphasis..." org-emphasize t]
  19861. ["Edit Source Example" org-edit-special t]
  19862. "--"
  19863. ["Footnote new/jump" org-footnote-action t]
  19864. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19865. ("Archive"
  19866. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19867. "--"
  19868. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19869. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19870. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19871. )
  19872. "--"
  19873. ("Hyperlinks"
  19874. ["Store Link (Global)" org-store-link t]
  19875. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19876. ["Insert Link" org-insert-link t]
  19877. ["Follow Link" org-open-at-point t]
  19878. "--"
  19879. ["Next link" org-next-link t]
  19880. ["Previous link" org-previous-link t]
  19881. "--"
  19882. ["Descriptive Links"
  19883. org-toggle-link-display
  19884. :style radio
  19885. :selected org-descriptive-links
  19886. ]
  19887. ["Literal Links"
  19888. org-toggle-link-display
  19889. :style radio
  19890. :selected (not org-descriptive-links)])
  19891. "--"
  19892. ("TODO Lists"
  19893. ["TODO/DONE/-" org-todo t]
  19894. ("Select keyword"
  19895. ["Next keyword" org-shiftright (org-at-heading-p)]
  19896. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19897. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19898. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19899. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19900. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19901. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19902. "--"
  19903. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19904. :selected org-enforce-todo-dependencies :style toggle :active t]
  19905. "Settings for tree at point"
  19906. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19907. :selected (org-entry-get nil "ORDERED")
  19908. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19909. ["Do Children parallel" org-toggle-ordered-property :style radio
  19910. :selected (not (org-entry-get nil "ORDERED"))
  19911. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19912. "--"
  19913. ["Set Priority" org-priority t]
  19914. ["Priority Up" org-shiftup t]
  19915. ["Priority Down" org-shiftdown t]
  19916. "--"
  19917. ["Get news from all feeds" org-feed-update-all t]
  19918. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19919. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19920. ("TAGS and Properties"
  19921. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19922. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19923. "--"
  19924. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19925. ["Column view of properties" org-columns t]
  19926. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19927. ("Dates and Scheduling"
  19928. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19929. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19930. ("Change Date"
  19931. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19932. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19933. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19934. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19935. ["Compute Time Range" org-evaluate-time-range t]
  19936. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19937. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19938. "--"
  19939. ["Custom time format" org-toggle-time-stamp-overlays
  19940. :style radio :selected org-display-custom-times]
  19941. "--"
  19942. ["Goto Calendar" org-goto-calendar t]
  19943. ["Date from Calendar" org-date-from-calendar t]
  19944. "--"
  19945. ["Start/Restart Timer" org-timer-start t]
  19946. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19947. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19948. ["Insert Timer String" org-timer t]
  19949. ["Insert Timer Item" org-timer-item t])
  19950. ("Logging work"
  19951. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19952. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19953. ["Clock out" org-clock-out t]
  19954. ["Clock cancel" org-clock-cancel t]
  19955. "--"
  19956. ["Mark as default task" org-clock-mark-default-task t]
  19957. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19958. ["Goto running clock" org-clock-goto t]
  19959. "--"
  19960. ["Display times" org-clock-display t]
  19961. ["Create clock table" org-clock-report t]
  19962. "--"
  19963. ["Record DONE time"
  19964. (progn (setq org-log-done (not org-log-done))
  19965. (message "Switching to %s will %s record a timestamp"
  19966. (car org-done-keywords)
  19967. (if org-log-done "automatically" "not")))
  19968. :style toggle :selected org-log-done])
  19969. "--"
  19970. ["Agenda Command..." org-agenda t]
  19971. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19972. ("File List for Agenda")
  19973. ("Special views current file"
  19974. ["TODO Tree" org-show-todo-tree t]
  19975. ["Check Deadlines" org-check-deadlines t]
  19976. ["Timeline" org-timeline t]
  19977. ["Tags/Property tree" org-match-sparse-tree t])
  19978. "--"
  19979. ["Export/Publish..." org-export-dispatch t]
  19980. ("LaTeX"
  19981. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19982. :selected org-cdlatex-mode]
  19983. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19984. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19985. ["Modify math symbol" org-cdlatex-math-modify
  19986. (org-inside-LaTeX-fragment-p)]
  19987. ["Insert citation" org-reftex-citation t])
  19988. "--"
  19989. ("MobileOrg"
  19990. ["Push Files and Views" org-mobile-push t]
  19991. ["Get Captured and Flagged" org-mobile-pull t]
  19992. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19993. "--"
  19994. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19995. "--"
  19996. ("Documentation"
  19997. ["Show Version" org-version t]
  19998. ["Info Documentation" org-info t])
  19999. ("Customize"
  20000. ["Browse Org Group" org-customize t]
  20001. "--"
  20002. ["Expand This Menu" org-create-customize-menu
  20003. (fboundp 'customize-menu-create)])
  20004. ["Send bug report" org-submit-bug-report t]
  20005. "--"
  20006. ("Refresh/Reload"
  20007. ["Refresh setup current buffer" org-mode-restart t]
  20008. ["Reload Org (after update)" org-reload t]
  20009. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  20010. ))
  20011. (defun org-info (&optional node)
  20012. "Read documentation for Org in the info system.
  20013. With optional NODE, go directly to that node."
  20014. (interactive)
  20015. (info (format "(org)%s" (or node ""))))
  20016. ;;;###autoload
  20017. (defun org-submit-bug-report ()
  20018. "Submit a bug report on Org via mail.
  20019. Don't hesitate to report any problems or inaccurate documentation.
  20020. If you don't have setup sending mail from (X)Emacs, please copy the
  20021. output buffer into your mail program, as it gives us important
  20022. information about your Org version and configuration."
  20023. (interactive)
  20024. (require 'reporter)
  20025. (defvar reporter-prompt-for-summary-p)
  20026. (org-load-modules-maybe)
  20027. (org-require-autoloaded-modules)
  20028. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  20029. (reporter-submit-bug-report
  20030. "emacs-orgmode@gnu.org"
  20031. (org-version nil 'full)
  20032. (let (list)
  20033. (save-window-excursion
  20034. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  20035. (delete-other-windows)
  20036. (erase-buffer)
  20037. (insert "You are about to submit a bug report to the Org mailing list.
  20038. We would like to add your full Org and Outline configuration to the
  20039. bug report. This greatly simplifies the work of the maintainer and
  20040. other experts on the mailing list.
  20041. HOWEVER, some variables you have customized may contain private
  20042. information. The names of customers, colleagues, or friends, might
  20043. appear in the form of file names, tags, todo states, or search strings.
  20044. If you answer yes to the prompt, you might want to check and remove
  20045. such private information before sending the email.")
  20046. (add-text-properties (point-min) (point-max) '(face org-warning))
  20047. (when (yes-or-no-p "Include your Org configuration ")
  20048. (mapatoms
  20049. (lambda (v)
  20050. (and (boundp v)
  20051. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20052. (or (and (symbol-value v)
  20053. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20054. (and
  20055. (get v 'custom-type) (get v 'standard-value)
  20056. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20057. (push v list)))))
  20058. (kill-buffer (get-buffer "*Warn about privacy*"))
  20059. list))
  20060. nil nil
  20061. "Remember to cover the basics, that is, what you expected to happen and
  20062. what in fact did happen. You don't know how to make a good report? See
  20063. http://orgmode.org/manual/Feedback.html#Feedback
  20064. Your bug report will be posted to the Org mailing list.
  20065. ------------------------------------------------------------------------")
  20066. (save-excursion
  20067. (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20068. (replace-match "\\1Bug: \\3 [\\2]")))))
  20069. (defun org-install-agenda-files-menu ()
  20070. (let ((bl (buffer-list)))
  20071. (save-excursion
  20072. (while bl
  20073. (set-buffer (pop bl))
  20074. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20075. (when (derived-mode-p 'org-mode)
  20076. (easy-menu-change
  20077. '("Org") "File List for Agenda"
  20078. (append
  20079. (list
  20080. ["Edit File List" (org-edit-agenda-file-list) t]
  20081. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20082. ["Remove Current File from List" org-remove-file t]
  20083. ["Cycle through agenda files" org-cycle-agenda-files t]
  20084. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20085. "--")
  20086. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20087. ;;;; Documentation
  20088. (defun org-require-autoloaded-modules ()
  20089. (interactive)
  20090. (mapc #'require
  20091. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20092. org-table org-timer)))
  20093. ;;;###autoload
  20094. (defun org-reload (&optional uncompiled)
  20095. "Reload all org lisp files.
  20096. With prefix arg UNCOMPILED, load the uncompiled versions."
  20097. (interactive "P")
  20098. (require 'loadhist)
  20099. (let* ((org-dir (org-find-library-dir "org"))
  20100. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20101. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20102. (remove-re (format "\\`%s\\'"
  20103. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20104. (feats (delete-dups
  20105. (mapcar 'file-name-sans-extension
  20106. (mapcar 'file-name-nondirectory
  20107. (delq nil
  20108. (mapcar 'feature-file
  20109. features))))))
  20110. (lfeat (append
  20111. (sort
  20112. (setq feats
  20113. (delq nil (mapcar
  20114. (lambda (f)
  20115. (if (and (string-match feature-re f)
  20116. (not (string-match remove-re f)))
  20117. f nil))
  20118. feats)))
  20119. 'string-lessp)
  20120. (list "org-version" "org")))
  20121. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20122. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20123. load-uncore load-misses)
  20124. (setq load-misses
  20125. (delq 't
  20126. (mapcar (lambda (f)
  20127. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20128. (and (string= org-dir contrib-dir)
  20129. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20130. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20131. (add-to-list 'load-uncore f 'append)
  20132. 't)
  20133. f))
  20134. lfeat)))
  20135. (when load-uncore
  20136. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20137. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20138. (if load-misses
  20139. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20140. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20141. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20142. ;;;###autoload
  20143. (defun org-customize ()
  20144. "Call the customize function with org as argument."
  20145. (interactive)
  20146. (org-load-modules-maybe)
  20147. (org-require-autoloaded-modules)
  20148. (customize-browse 'org))
  20149. (defun org-create-customize-menu ()
  20150. "Create a full customization menu for Org-mode, insert it into the menu."
  20151. (interactive)
  20152. (org-load-modules-maybe)
  20153. (org-require-autoloaded-modules)
  20154. (if (fboundp 'customize-menu-create)
  20155. (progn
  20156. (easy-menu-change
  20157. '("Org") "Customize"
  20158. `(["Browse Org group" org-customize t]
  20159. "--"
  20160. ,(customize-menu-create 'org)
  20161. ["Set" Custom-set t]
  20162. ["Save" Custom-save t]
  20163. ["Reset to Current" Custom-reset-current t]
  20164. ["Reset to Saved" Custom-reset-saved t]
  20165. ["Reset to Standard Settings" Custom-reset-standard t]))
  20166. (message "\"Org\"-menu now contains full customization menu"))
  20167. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20168. ;;;; Miscellaneous stuff
  20169. ;;; Generally useful functions
  20170. (defun org-get-at-eol (property n)
  20171. "Get text property PROPERTY at the end of line less N characters."
  20172. (get-text-property (- (point-at-eol) n) property))
  20173. (defun org-find-text-property-in-string (prop s)
  20174. "Return the first non-nil value of property PROP in string S."
  20175. (or (get-text-property 0 prop s)
  20176. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20177. prop s)))
  20178. (defun org-display-warning (message) ;; Copied from Emacs-Muse
  20179. "Display the given MESSAGE as a warning."
  20180. (if (fboundp 'display-warning)
  20181. (display-warning 'org message :warning)
  20182. (let ((buf (get-buffer-create "*Org warnings*")))
  20183. (with-current-buffer buf
  20184. (goto-char (point-max))
  20185. (insert "Warning (Org): " message)
  20186. (unless (bolp)
  20187. (newline)))
  20188. (display-buffer buf)
  20189. (sit-for 0))))
  20190. (defun org-eval (form)
  20191. "Eval FORM and return result."
  20192. (condition-case error
  20193. (eval form)
  20194. (error (format "%%![Error: %s]" error))))
  20195. (defun org-in-clocktable-p ()
  20196. "Check if the cursor is in a clocktable."
  20197. (let ((pos (point)) start)
  20198. (save-excursion
  20199. (end-of-line 1)
  20200. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20201. (setq start (match-beginning 0))
  20202. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20203. (>= (match-end 0) pos)
  20204. start))))
  20205. (defun org-in-verbatim-emphasis ()
  20206. (save-match-data
  20207. (and (org-in-regexp org-emph-re 2)
  20208. (>= (point) (match-beginning 3))
  20209. (<= (point) (match-end 4))
  20210. (member (match-string 3) '("=" "~")))))
  20211. (defun org-overlay-display (ovl text &optional face evap)
  20212. "Make overlay OVL display TEXT with face FACE."
  20213. (overlay-put ovl 'display text)
  20214. (if face (overlay-put ovl 'face face))
  20215. (if evap (overlay-put ovl 'evaporate t)))
  20216. (defun org-overlay-before-string (ovl text &optional face evap)
  20217. "Make overlay OVL display TEXT with face FACE."
  20218. (if face (org-add-props text nil 'face face))
  20219. (overlay-put ovl 'before-string text)
  20220. (if evap (overlay-put ovl 'evaporate t)))
  20221. (defun org-find-overlays (prop &optional pos delete)
  20222. "Find all overlays specifying PROP at POS or point.
  20223. If DELETE is non-nil, delete all those overlays."
  20224. (let (found)
  20225. (dolist (ov (overlays-at (or pos (point))) found)
  20226. (cond ((not (overlay-get ov prop)))
  20227. (delete (delete-overlay ov))
  20228. (t (push ov found))))))
  20229. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20230. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20231. (if (and marker (marker-buffer marker)
  20232. (buffer-live-p (marker-buffer marker)))
  20233. (progn
  20234. (pop-to-buffer-same-window (marker-buffer marker))
  20235. (when (or (> marker (point-max)) (< marker (point-min)))
  20236. (widen))
  20237. (goto-char marker)
  20238. (org-show-context 'org-goto))
  20239. (if bookmark
  20240. (bookmark-jump bookmark)
  20241. (error "Cannot find location"))))
  20242. (defun org-quote-csv-field (s)
  20243. "Quote field for inclusion in CSV material."
  20244. (if (string-match "[\",]" s)
  20245. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20246. s))
  20247. (defun org-force-self-insert (N)
  20248. "Needed to enforce self-insert under remapping."
  20249. (interactive "p")
  20250. (self-insert-command N))
  20251. (defun org-string-width (s)
  20252. "Compute width of string, ignoring invisible characters.
  20253. This ignores character with invisibility property `org-link', and also
  20254. characters with property `org-cwidth', because these will become invisible
  20255. upon the next fontification round."
  20256. (let (b l)
  20257. (when (or (eq t buffer-invisibility-spec)
  20258. (assq 'org-link buffer-invisibility-spec))
  20259. (while (setq b (text-property-any 0 (length s)
  20260. 'invisible 'org-link s))
  20261. (setq s (concat (substring s 0 b)
  20262. (substring s (or (next-single-property-change
  20263. b 'invisible s)
  20264. (length s)))))))
  20265. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20266. (setq s (concat (substring s 0 b)
  20267. (substring s (or (next-single-property-change
  20268. b 'org-cwidth s)
  20269. (length s))))))
  20270. (setq l (string-width s) b -1)
  20271. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20272. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20273. l))
  20274. (defun org-shorten-string (s maxlength)
  20275. "Shorten string S so tht it is no longer than MAXLENGTH characters.
  20276. If the string is shorter or has length MAXLENGTH, just return the
  20277. original string. If it is longer, the functions finds a space in the
  20278. string, breaks this string off at that locations and adds three dots
  20279. as ellipsis. Including the ellipsis, the string will not be longer
  20280. than MAXLENGTH. If finding a good breaking point in the string does
  20281. not work, the string is just chopped off in the middle of a word
  20282. if necessary."
  20283. (if (<= (length s) maxlength)
  20284. s
  20285. (let* ((n (max (- maxlength 4) 1))
  20286. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20287. (if (string-match re s)
  20288. (concat (match-string 1 s) "...")
  20289. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20290. (defun org-get-indentation (&optional line)
  20291. "Get the indentation of the current line, interpreting tabs.
  20292. When LINE is given, assume it represents a line and compute its indentation."
  20293. (if line
  20294. (when (string-match "^ *" (org-remove-tabs line))
  20295. (match-end 0))
  20296. (save-excursion
  20297. (beginning-of-line 1)
  20298. (skip-chars-forward " \t")
  20299. (current-column))))
  20300. (defun org-get-string-indentation (s)
  20301. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20302. (let ((n -1) (i 0) (w tab-width) c)
  20303. (catch 'exit
  20304. (while (< (setq n (1+ n)) (length s))
  20305. (setq c (aref s n))
  20306. (cond ((= c ?\ ) (setq i (1+ i)))
  20307. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20308. (t (throw 'exit t)))))
  20309. i))
  20310. (defun org-remove-tabs (s &optional width)
  20311. "Replace tabulators in S with spaces.
  20312. Assumes that s is a single line, starting in column 0."
  20313. (setq width (or width tab-width))
  20314. (while (string-match "\t" s)
  20315. (setq s (replace-match
  20316. (make-string
  20317. (- (* width (/ (+ (match-beginning 0) width) width))
  20318. (match-beginning 0)) ?\ )
  20319. t t s)))
  20320. s)
  20321. (defun org-fix-indentation (line ind)
  20322. "Fix indentation in LINE.
  20323. IND is a cons cell with target and minimum indentation.
  20324. If the current indentation in LINE is smaller than the minimum,
  20325. leave it alone. If it is larger than ind, set it to the target."
  20326. (let* ((l (org-remove-tabs line))
  20327. (i (org-get-indentation l))
  20328. (i1 (car ind)) (i2 (cdr ind)))
  20329. (when (>= i i2) (setq l (substring line i2)))
  20330. (if (> i1 0)
  20331. (concat (make-string i1 ?\ ) l)
  20332. l)))
  20333. (defun org-remove-indentation (code &optional n)
  20334. "Remove maximum common indentation in string CODE and return it.
  20335. N may optionally be the number of columns to remove. Return CODE
  20336. as-is if removal failed."
  20337. (with-temp-buffer
  20338. (insert code)
  20339. (if (org-do-remove-indentation n) (buffer-string) code)))
  20340. (defun org-do-remove-indentation (&optional n)
  20341. "Remove the maximum common indentation from the buffer.
  20342. When optional argument N is a positive integer, remove exactly
  20343. that much characters from indentation, if possible. Return nil
  20344. if it fails."
  20345. (catch :exit
  20346. (goto-char (point-min))
  20347. ;; Find maximum common indentation, if not specified.
  20348. (let ((n (or n
  20349. (let ((min-ind (point-max)))
  20350. (save-excursion
  20351. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20352. (let ((ind (1- (current-column))))
  20353. (if (zerop ind) (throw :exit nil)
  20354. (setq min-ind (min min-ind ind))))))
  20355. min-ind))))
  20356. (if (zerop n) (throw :exit nil)
  20357. ;; Remove exactly N indentation, but give up if not possible.
  20358. (while (not (eobp))
  20359. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20360. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20361. ((< ind n) (throw :exit nil))
  20362. (t (indent-line-to (- ind n))))
  20363. (forward-line)))
  20364. ;; Signal success.
  20365. t))))
  20366. (defun org-fill-template (template alist)
  20367. "Find each %key of ALIST in TEMPLATE and replace it."
  20368. (let ((case-fold-search nil))
  20369. (dolist (entry (sort (copy-sequence alist)
  20370. (lambda (a b) (< (length (car a)) (length (car b))))))
  20371. (setq template
  20372. (replace-regexp-in-string
  20373. (concat "%" (regexp-quote (car entry)))
  20374. (or (cdr entry) "") template t t)))
  20375. template))
  20376. (defun org-base-buffer (buffer)
  20377. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20378. (if (not buffer)
  20379. buffer
  20380. (or (buffer-base-buffer buffer)
  20381. buffer)))
  20382. (defun org-wrap (string &optional width lines)
  20383. "Wrap string to either a number of lines, or a width in characters.
  20384. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20385. that costs. If there is a word longer than WIDTH, the text is actually
  20386. wrapped to the length of that word.
  20387. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20388. many lines, whatever width that takes.
  20389. The return value is a list of lines, without newlines at the end."
  20390. (let* ((words (org-split-string string "[ \t\n]+"))
  20391. (maxword (apply 'max (mapcar 'org-string-width words)))
  20392. w ll)
  20393. (cond (width
  20394. (org-do-wrap words (max maxword width)))
  20395. (lines
  20396. (setq w maxword)
  20397. (setq ll (org-do-wrap words maxword))
  20398. (if (<= (length ll) lines)
  20399. ll
  20400. (setq ll words)
  20401. (while (> (length ll) lines)
  20402. (setq w (1+ w))
  20403. (setq ll (org-do-wrap words w)))
  20404. ll))
  20405. (t (error "Cannot wrap this")))))
  20406. (defun org-do-wrap (words width)
  20407. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20408. (let (lines line)
  20409. (while words
  20410. (setq line (pop words))
  20411. (while (and words (< (+ (length line) (length (car words))) width))
  20412. (setq line (concat line " " (pop words))))
  20413. (setq lines (push line lines)))
  20414. (nreverse lines)))
  20415. (defun org-split-string (string &optional separators)
  20416. "Splits STRING into substrings at SEPARATORS.
  20417. SEPARATORS is a regular expression.
  20418. No empty strings are returned if there are matches at the beginning
  20419. and end of string."
  20420. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20421. (let ((start 0) notfirst list)
  20422. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20423. (if (and notfirst
  20424. (= start (match-beginning 0))
  20425. (< start (length string)))
  20426. (1+ start) start))
  20427. (< (match-beginning 0) (length string)))
  20428. (setq notfirst t)
  20429. (or (eq (match-beginning 0) 0)
  20430. (and (eq (match-beginning 0) (match-end 0))
  20431. (eq (match-beginning 0) start))
  20432. (push (substring string start (match-beginning 0)) list))
  20433. (setq start (match-end 0)))
  20434. (or (eq start (length string))
  20435. (push (substring string start) list))
  20436. (nreverse list)))
  20437. (defun org-quote-vert (s)
  20438. "Replace \"|\" with \"\\vert\"."
  20439. (while (string-match "|" s)
  20440. (setq s (replace-match "\\vert" t t s)))
  20441. s)
  20442. (defun org-uuidgen-p (s)
  20443. "Is S an ID created by UUIDGEN?"
  20444. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20445. (defun org-in-src-block-p (&optional inside)
  20446. "Whether point is in a code source block.
  20447. When INSIDE is non-nil, don't consider we are within a src block
  20448. when point is at #+BEGIN_SRC or #+END_SRC."
  20449. (let ((case-fold-search t))
  20450. (or (and (eq (get-char-property (point) 'src-block) t))
  20451. (and (not inside)
  20452. (save-match-data
  20453. (save-excursion
  20454. (beginning-of-line)
  20455. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20456. (defun org-context ()
  20457. "Return a list of contexts of the current cursor position.
  20458. If several contexts apply, all are returned.
  20459. Each context entry is a list with a symbol naming the context, and
  20460. two positions indicating start and end of the context. Possible
  20461. contexts are:
  20462. :headline anywhere in a headline
  20463. :headline-stars on the leading stars in a headline
  20464. :todo-keyword on a TODO keyword (including DONE) in a headline
  20465. :tags on the TAGS in a headline
  20466. :priority on the priority cookie in a headline
  20467. :item on the first line of a plain list item
  20468. :item-bullet on the bullet/number of a plain list item
  20469. :checkbox on the checkbox in a plain list item
  20470. :table in an Org table
  20471. :table-special on a special filed in a table
  20472. :table-table in a table.el table
  20473. :clocktable in a clocktable
  20474. :src-block in a source block
  20475. :link on a hyperlink
  20476. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20477. :target on a <<target>>
  20478. :radio-target on a <<<radio-target>>>
  20479. :latex-fragment on a LaTeX fragment
  20480. :latex-preview on a LaTeX fragment with overlaid preview image
  20481. This function expects the position to be visible because it uses font-lock
  20482. faces as a help to recognize the following contexts: :table-special, :link,
  20483. and :keyword."
  20484. (let* ((f (get-text-property (point) 'face))
  20485. (faces (if (listp f) f (list f)))
  20486. (case-fold-search t)
  20487. (p (point)) clist o)
  20488. ;; First the large context
  20489. (cond
  20490. ((org-at-heading-p t)
  20491. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20492. (when (progn
  20493. (beginning-of-line 1)
  20494. (looking-at org-todo-line-tags-regexp))
  20495. (push (org-point-in-group p 1 :headline-stars) clist)
  20496. (push (org-point-in-group p 2 :todo-keyword) clist)
  20497. (push (org-point-in-group p 4 :tags) clist))
  20498. (goto-char p)
  20499. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20500. (when (looking-at "\\[#[A-Z0-9]\\]")
  20501. (push (org-point-in-group p 0 :priority) clist)))
  20502. ((org-at-item-p)
  20503. (push (org-point-in-group p 2 :item-bullet) clist)
  20504. (push (list :item (point-at-bol)
  20505. (save-excursion (org-end-of-item) (point)))
  20506. clist)
  20507. (and (org-at-item-checkbox-p)
  20508. (push (org-point-in-group p 0 :checkbox) clist)))
  20509. ((org-at-table-p)
  20510. (push (list :table (org-table-begin) (org-table-end)) clist)
  20511. (when (memq 'org-formula faces)
  20512. (push (list :table-special
  20513. (previous-single-property-change p 'face)
  20514. (next-single-property-change p 'face)) clist)))
  20515. ((org-at-table-p 'any)
  20516. (push (list :table-table) clist)))
  20517. (goto-char p)
  20518. (let ((case-fold-search t))
  20519. ;; New the "medium" contexts: clocktables, source blocks
  20520. (cond ((org-in-clocktable-p)
  20521. (push (list :clocktable
  20522. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20523. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20524. (match-beginning 1))
  20525. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20526. (match-end 0))) clist))
  20527. ((org-in-src-block-p)
  20528. (push (list :src-block
  20529. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20530. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20531. (match-beginning 1))
  20532. (and (search-forward "#+END_SRC" nil t)
  20533. (match-beginning 0))) clist))))
  20534. (goto-char p)
  20535. ;; Now the small context
  20536. (cond
  20537. ((org-at-timestamp-p)
  20538. (push (org-point-in-group p 0 :timestamp) clist))
  20539. ((memq 'org-link faces)
  20540. (push (list :link
  20541. (previous-single-property-change p 'face)
  20542. (next-single-property-change p 'face)) clist))
  20543. ((memq 'org-special-keyword faces)
  20544. (push (list :keyword
  20545. (previous-single-property-change p 'face)
  20546. (next-single-property-change p 'face)) clist))
  20547. ((org-at-target-p)
  20548. (push (org-point-in-group p 0 :target) clist)
  20549. (goto-char (1- (match-beginning 0)))
  20550. (when (looking-at org-radio-target-regexp)
  20551. (push (org-point-in-group p 0 :radio-target) clist))
  20552. (goto-char p))
  20553. ((setq o (cl-some
  20554. (lambda (o)
  20555. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20556. o))
  20557. (overlays-at (point))))
  20558. (push (list :latex-fragment
  20559. (overlay-start o) (overlay-end o)) clist)
  20560. (push (list :latex-preview
  20561. (overlay-start o) (overlay-end o)) clist))
  20562. ((org-inside-LaTeX-fragment-p)
  20563. ;; FIXME: positions wrong.
  20564. (push (list :latex-fragment (point) (point)) clist)))
  20565. (setq clist (nreverse (delq nil clist)))
  20566. clist))
  20567. (defun org-in-regexp (regexp &optional nlines visually)
  20568. "Check if point is inside a match of REGEXP.
  20569. Normally only the current line is checked, but you can include
  20570. NLINES extra lines around point into the search. If VISUALLY is
  20571. set, require that the cursor is not after the match but really
  20572. on, so that the block visually is on the match.
  20573. Return nil or a cons cell (BEG . END) where BEG and END are,
  20574. respectively, the positions at the beginning and the end of the
  20575. match."
  20576. (catch :exit
  20577. (let ((pos (point))
  20578. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20579. (save-excursion
  20580. (beginning-of-line (- 1 (or nlines 0)))
  20581. (while (and (re-search-forward regexp eol t)
  20582. (<= (match-beginning 0) pos))
  20583. (let ((end (match-end 0)))
  20584. (when (or (> end pos) (and (= end pos) (not visually)))
  20585. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20586. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20587. "Non-nil when point is between matches of START-RE and END-RE.
  20588. Also return a non-nil value when point is on one of the matches.
  20589. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20590. buffer positions. Default values are the positions of headlines
  20591. surrounding the point.
  20592. The functions returns a cons cell whose car (resp. cdr) is the
  20593. position before START-RE (resp. after END-RE)."
  20594. (save-match-data
  20595. (let ((pos (point))
  20596. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20597. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20598. beg end)
  20599. (save-excursion
  20600. ;; Point is on a block when on START-RE or if START-RE can be
  20601. ;; found before it...
  20602. (and (or (org-in-regexp start-re)
  20603. (re-search-backward start-re limit-up t))
  20604. (setq beg (match-beginning 0))
  20605. ;; ... and END-RE after it...
  20606. (goto-char (match-end 0))
  20607. (re-search-forward end-re limit-down t)
  20608. (> (setq end (match-end 0)) pos)
  20609. ;; ... without another START-RE in-between.
  20610. (goto-char (match-beginning 0))
  20611. (not (re-search-backward start-re (1+ beg) t))
  20612. ;; Return value.
  20613. (cons beg end))))))
  20614. (defun org-in-block-p (names)
  20615. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20616. NAMES is a list of strings containing names of blocks.
  20617. Return first block name matched, or nil. Beware that in case of
  20618. nested blocks, the returned name may not belong to the closest
  20619. block from point."
  20620. (save-match-data
  20621. (catch 'exit
  20622. (let ((case-fold-search t)
  20623. (lim-up (save-excursion (outline-previous-heading)))
  20624. (lim-down (save-excursion (outline-next-heading))))
  20625. (dolist (name names)
  20626. (let ((n (regexp-quote name)))
  20627. (when (org-between-regexps-p
  20628. (concat "^[ \t]*#\\+begin_" n)
  20629. (concat "^[ \t]*#\\+end_" n)
  20630. lim-up lim-down)
  20631. (throw 'exit n)))))
  20632. nil)))
  20633. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20634. "Call `multi-occur' with buffers for all agenda files."
  20635. (interactive "sOrg-files matching: ")
  20636. (let* ((files (org-agenda-files))
  20637. (tnames (mapcar #'file-truename files))
  20638. (extra org-agenda-text-search-extra-files))
  20639. (when (eq (car extra) 'agenda-archives)
  20640. (setq extra (cdr extra))
  20641. (setq files (org-add-archive-files files)))
  20642. (dolist (f extra)
  20643. (unless (member (file-truename f) tnames)
  20644. (unless (member f files) (setq files (append files (list f))))
  20645. (setq tnames (append tnames (list (file-truename f))))))
  20646. (multi-occur
  20647. (mapcar (lambda (x)
  20648. (with-current-buffer
  20649. ;; FIXME: Why not just (find-file-noselect x)?
  20650. ;; Is it to avoid the "revert buffer" prompt?
  20651. (or (get-file-buffer x) (find-file-noselect x))
  20652. (widen)
  20653. (current-buffer)))
  20654. files)
  20655. regexp)))
  20656. (add-hook 'occur-mode-find-occurrence-hook
  20657. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20658. (defun org-occur-link-in-agenda-files ()
  20659. "Create a link and search for it in the agendas.
  20660. The link is not stored in `org-stored-links', it is just created
  20661. for the search purpose."
  20662. (interactive)
  20663. (let ((link (condition-case nil
  20664. (org-store-link nil)
  20665. (error "Unable to create a link to here"))))
  20666. (org-occur-in-agenda-files (regexp-quote link))))
  20667. (defun org-reverse-string (string)
  20668. "Return the reverse of STRING."
  20669. (apply 'string (reverse (string-to-list string))))
  20670. ;; defsubst org-uniquify must be defined before first use
  20671. (defun org-uniquify-alist (alist)
  20672. "Merge elements of ALIST with the same key.
  20673. For example, in this alist:
  20674. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20675. => \\='((a 1 3) (b 2))
  20676. merge (a 1) and (a 3) into (a 1 3).
  20677. The function returns the new ALIST."
  20678. (let (rtn)
  20679. (dolist (e alist rtn)
  20680. (let (n)
  20681. (if (not (assoc (car e) rtn))
  20682. (push e rtn)
  20683. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20684. (setq rtn (assq-delete-all (car e) rtn))
  20685. (push n rtn))))))
  20686. (defun org-delete-all (elts list)
  20687. "Remove all elements in ELTS from LIST.
  20688. Comparison is done with `equal'. It is a destructive operation
  20689. that may remove elements by altering the list structure."
  20690. (while elts
  20691. (setq list (delete (pop elts) list)))
  20692. list)
  20693. (defun org-back-over-empty-lines ()
  20694. "Move backwards over whitespace, to the beginning of the first empty line.
  20695. Returns the number of empty lines passed."
  20696. (let ((pos (point)))
  20697. (if (cdr (assoc 'heading org-blank-before-new-entry))
  20698. (skip-chars-backward " \t\n\r")
  20699. (unless (eobp)
  20700. (forward-line -1)))
  20701. (beginning-of-line 2)
  20702. (goto-char (min (point) pos))
  20703. (count-lines (point) pos)))
  20704. (defun org-skip-whitespace ()
  20705. (skip-chars-forward " \t\n\r"))
  20706. (defun org-point-in-group (point group &optional context)
  20707. "Check if POINT is in match-group GROUP.
  20708. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20709. match. If the match group does not exist or point is not inside it,
  20710. return nil."
  20711. (and (match-beginning group)
  20712. (>= point (match-beginning group))
  20713. (<= point (match-end group))
  20714. (if context
  20715. (list context (match-beginning group) (match-end group))
  20716. t)))
  20717. (defun org-switch-to-buffer-other-window (&rest args)
  20718. "Switch to buffer in a second window on the current frame.
  20719. In particular, do not allow pop-up frames.
  20720. Returns the newly created buffer."
  20721. (org-no-popups
  20722. (apply 'switch-to-buffer-other-window args)))
  20723. (defun org-combine-plists (&rest plists)
  20724. "Create a single property list from all plists in PLISTS.
  20725. The process starts by copying the first list, and then setting properties
  20726. from the other lists. Settings in the last list are the most significant
  20727. ones and overrule settings in the other lists."
  20728. (let ((rtn (copy-sequence (pop plists)))
  20729. p v ls)
  20730. (while plists
  20731. (setq ls (pop plists))
  20732. (while ls
  20733. (setq p (pop ls) v (pop ls))
  20734. (setq rtn (plist-put rtn p v))))
  20735. rtn))
  20736. (defun org-replace-escapes (string table)
  20737. "Replace %-escapes in STRING with values in TABLE.
  20738. TABLE is an association list with keys like \"%a\" and string values.
  20739. The sequences in STRING may contain normal field width and padding information,
  20740. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20741. so values can contain further %-escapes if they are define later in TABLE."
  20742. (let ((tbl (copy-alist table))
  20743. (case-fold-search nil)
  20744. (pchg 0)
  20745. re rpl)
  20746. (dolist (e tbl)
  20747. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20748. (when (and (cdr e) (string-match re (cdr e)))
  20749. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20750. (safe "SREF"))
  20751. (add-text-properties 0 3 (list 'sref sref) safe)
  20752. (setcdr e (replace-match safe t t (cdr e)))))
  20753. (while (string-match re string)
  20754. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20755. (cdr e)))
  20756. (setq string (replace-match rpl t t string))))
  20757. (while (setq pchg (next-property-change pchg string))
  20758. (let ((sref (get-text-property pchg 'sref string)))
  20759. (when (and sref (string-match "SREF" string pchg))
  20760. (setq string (replace-match sref t t string)))))
  20761. string))
  20762. (defun org-sublist (list start end)
  20763. "Return a section of LIST, from START to END.
  20764. Counting starts at 1."
  20765. (cl-subseq list (1- start) end))
  20766. (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
  20767. (defun org-find-base-buffer-visiting (file)
  20768. "Like `find-buffer-visiting' but always return the base buffer and
  20769. not an indirect buffer."
  20770. (let ((buf (or (get-file-buffer file)
  20771. (find-buffer-visiting file))))
  20772. (if buf
  20773. (or (buffer-base-buffer buf) buf)
  20774. nil)))
  20775. ;;; TODO: Only called once, from ox-odt which should probably use
  20776. ;;; org-export-inline-image-p or something.
  20777. (defun org-file-image-p (file)
  20778. "Return non-nil if FILE is an image."
  20779. (save-match-data
  20780. (string-match (image-file-name-regexp) file)))
  20781. (defun org-get-cursor-date (&optional with-time)
  20782. "Return the date at cursor in as a time.
  20783. This works in the calendar and in the agenda, anywhere else it just
  20784. returns the current time.
  20785. If WITH-TIME is non-nil, returns the time of the event at point (in
  20786. the agenda) or the current time of the day."
  20787. (let (date day defd tp hod mod)
  20788. (when with-time
  20789. (setq tp (get-text-property (point) 'time))
  20790. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20791. (setq hod (string-to-number (match-string 1 tp))
  20792. mod (string-to-number (match-string 2 tp))))
  20793. (or tp (let ((now (decode-time)))
  20794. (setq hod (nth 2 now)
  20795. mod (nth 1 now)))))
  20796. (cond
  20797. ((eq major-mode 'calendar-mode)
  20798. (setq date (calendar-cursor-to-date)
  20799. defd (encode-time 0 (or mod 0) (or hod 0)
  20800. (nth 1 date) (nth 0 date) (nth 2 date))))
  20801. ((eq major-mode 'org-agenda-mode)
  20802. (setq day (get-text-property (point) 'day))
  20803. (when day
  20804. (setq date (calendar-gregorian-from-absolute day)
  20805. defd (encode-time 0 (or mod 0) (or hod 0)
  20806. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20807. (or defd (current-time))))
  20808. (defun org-mark-subtree (&optional up)
  20809. "Mark the current subtree.
  20810. This puts point at the start of the current subtree, and mark at
  20811. the end. If a numeric prefix UP is given, move up into the
  20812. hierarchy of headlines by UP levels before marking the subtree."
  20813. (interactive "P")
  20814. (org-with-limited-levels
  20815. (cond ((org-at-heading-p) (beginning-of-line))
  20816. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20817. (t (outline-previous-visible-heading 1))))
  20818. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20819. (if (called-interactively-p 'any)
  20820. (call-interactively 'org-mark-element)
  20821. (org-mark-element)))
  20822. (defun org-file-newer-than-p (file time)
  20823. "Non-nil if FILE is newer than TIME.
  20824. FILE is a filename, as a string, TIME is a list of integers, as
  20825. returned by, e.g., `current-time'."
  20826. (and (file-exists-p file)
  20827. ;; Only compare times up to whole seconds as some file-systems
  20828. ;; (e.g. HFS+) do not retain any finer granularity. As
  20829. ;; a consequence, make sure we return non-nil when the two
  20830. ;; times are equal.
  20831. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20832. (cl-subseq time 0 2)))))
  20833. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20834. "Compile a SOURCE file using PROCESS.
  20835. PROCESS is either a function or a list of shell commands, as
  20836. strings. EXT is a file extension, without the leading dot, as
  20837. a string. It is used to check if the process actually succeeded.
  20838. PROCESS must create a file with the same base name and directory
  20839. as SOURCE, but ending with EXT. The function then returns its
  20840. filename. Otherwise, it raises an error. The error message can
  20841. then be refined by providing string ERR-MSG, which is appended to
  20842. the standard message.
  20843. If PROCESS is a function, it is called with a single argument:
  20844. the SOURCE file.
  20845. If it is a list of commands, each of them is called using
  20846. `shell-command'. By default, in each command, %b, %f, %F and %o
  20847. are replaced with, respectively, SOURCE base name, name, full
  20848. name and directory. It is possible, however, to use more
  20849. place-holders by specifying them in optional argument SPEC, as an
  20850. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20851. When PROCESS is a list of commands, optional argument LOG-BUF can
  20852. be set to a buffer or a buffer name. `shell-command' then uses
  20853. it for output.
  20854. `default-directory' is set to SOURCE directory during the whole
  20855. process."
  20856. (let* ((source-name (file-name-nondirectory source))
  20857. (base-name (file-name-sans-extension source-name))
  20858. (full-name (file-truename source))
  20859. (out-dir (file-name-directory source))
  20860. (time (current-time))
  20861. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20862. (save-window-excursion
  20863. (let ((default-directory (file-name-directory full-name)))
  20864. (pcase process
  20865. ((pred functionp) (funcall process (shell-quote-argument source)))
  20866. ((pred consp)
  20867. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20868. (spec (append spec
  20869. `((?b . ,(shell-quote-argument base-name))
  20870. (?f . ,(shell-quote-argument source-name))
  20871. (?F . ,(shell-quote-argument full-name))
  20872. (?o . ,(shell-quote-argument out-dir))))))
  20873. (dolist (command process)
  20874. (shell-command (format-spec command spec) log-buf))))
  20875. (_ (error "No valid command to process %S%s" source err-msg)))))
  20876. ;; Check for process failure.
  20877. (let ((output (concat out-dir base-name "." ext)))
  20878. (unless (org-file-newer-than-p output time)
  20879. (error (format "File %S wasn't produced%s" output err-msg)))
  20880. output)))
  20881. ;;; Indentation
  20882. (defun org--get-expected-indentation (element contentsp)
  20883. "Expected indentation column for current line, according to ELEMENT.
  20884. ELEMENT is an element containing point. CONTENTSP is non-nil
  20885. when indentation is to be computed according to contents of
  20886. ELEMENT."
  20887. (let ((type (org-element-type element))
  20888. (start (org-element-property :begin element))
  20889. (post-affiliated (org-element-property :post-affiliated element)))
  20890. (org-with-wide-buffer
  20891. (cond
  20892. (contentsp
  20893. (cl-case type
  20894. ((diary-sexp footnote-definition) 0)
  20895. ((headline inlinetask nil)
  20896. (if (not org-adapt-indentation) 0
  20897. (let ((level (org-current-level)))
  20898. (if level (1+ level) 0))))
  20899. ((item plain-list) (org-list-item-body-column post-affiliated))
  20900. (t
  20901. (goto-char start)
  20902. (org-get-indentation))))
  20903. ((memq type '(headline inlinetask nil))
  20904. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20905. (org--get-expected-indentation element t)
  20906. 0))
  20907. ((memq type '(diary-sexp footnote-definition)) 0)
  20908. ;; First paragraph of a footnote definition or an item.
  20909. ;; Indent like parent.
  20910. ((< (line-beginning-position) start)
  20911. (org--get-expected-indentation
  20912. (org-element-property :parent element) t))
  20913. ;; At first line: indent according to previous sibling, if any,
  20914. ;; ignoring footnote definitions and inline tasks, or parent's
  20915. ;; contents.
  20916. ((= (line-beginning-position) start)
  20917. (catch 'exit
  20918. (while t
  20919. (if (= (point-min) start) (throw 'exit 0)
  20920. (goto-char (1- start))
  20921. (let* ((previous (org-element-at-point))
  20922. (parent previous))
  20923. (while (and parent (<= (org-element-property :end parent) start))
  20924. (setq previous parent
  20925. parent (org-element-property :parent parent)))
  20926. (cond
  20927. ((not previous) (throw 'exit 0))
  20928. ((> (org-element-property :end previous) start)
  20929. (throw 'exit (org--get-expected-indentation previous t)))
  20930. ((memq (org-element-type previous)
  20931. '(footnote-definition inlinetask))
  20932. (setq start (org-element-property :begin previous)))
  20933. (t (goto-char (org-element-property :begin previous))
  20934. (throw 'exit
  20935. (if (bolp) (org-get-indentation)
  20936. ;; At first paragraph in an item or
  20937. ;; a footnote definition.
  20938. (org--get-expected-indentation
  20939. (org-element-property :parent previous) t))))))))))
  20940. ;; Otherwise, move to the first non-blank line above.
  20941. (t
  20942. (beginning-of-line)
  20943. (let ((pos (point)))
  20944. (skip-chars-backward " \r\t\n")
  20945. (cond
  20946. ;; Two blank lines end a footnote definition or a plain
  20947. ;; list. When we indent an empty line after them, the
  20948. ;; containing list or footnote definition is over, so it
  20949. ;; qualifies as a previous sibling. Therefore, we indent
  20950. ;; like its first line.
  20951. ((and (memq type '(footnote-definition plain-list))
  20952. (> (count-lines (point) pos) 2))
  20953. (goto-char start)
  20954. (org-get-indentation))
  20955. ;; Line above is the first one of a paragraph at the
  20956. ;; beginning of an item or a footnote definition. Indent
  20957. ;; like parent.
  20958. ((< (line-beginning-position) start)
  20959. (org--get-expected-indentation
  20960. (org-element-property :parent element) t))
  20961. ;; Line above is the beginning of an element, i.e., point
  20962. ;; was originally on the blank lines between element's start
  20963. ;; and contents.
  20964. ((= (line-beginning-position) post-affiliated)
  20965. (org--get-expected-indentation element t))
  20966. ;; POS is after contents in a greater element. Indent like
  20967. ;; the beginning of the element.
  20968. ;;
  20969. ;; As a special case, if point is at the end of a footnote
  20970. ;; definition or an item, indent like the very last element
  20971. ;; within. If that last element is an item, indent like its
  20972. ;; contents.
  20973. ((and (not (eq type 'paragraph))
  20974. (let ((cend (org-element-property :contents-end element)))
  20975. (and cend (<= cend pos))))
  20976. (if (memq type '(footnote-definition item plain-list))
  20977. (let ((last (org-element-at-point)))
  20978. (org--get-expected-indentation
  20979. last (eq (org-element-type last) 'item)))
  20980. (goto-char start)
  20981. (org-get-indentation)))
  20982. ;; In any other case, indent like the current line.
  20983. (t (org-get-indentation)))))))))
  20984. (defun org--align-node-property ()
  20985. "Align node property at point.
  20986. Alignment is done according to `org-property-format', which see."
  20987. (when (save-excursion
  20988. (beginning-of-line)
  20989. (looking-at org-property-re))
  20990. (replace-match
  20991. (concat (match-string 4)
  20992. (org-trim
  20993. (format org-property-format (match-string 1) (match-string 3))))
  20994. t t)))
  20995. (defun org-indent-line ()
  20996. "Indent line depending on context.
  20997. Indentation is done according to the following rules:
  20998. - Footnote definitions, diary sexps, headlines and inline tasks
  20999. have to start at column 0.
  21000. - On the very first line of an element, consider, in order, the
  21001. next rules until one matches:
  21002. 1. If there's a sibling element before, ignoring footnote
  21003. definitions and inline tasks, indent like its first line.
  21004. 2. If element has a parent, indent like its contents. More
  21005. precisely, if parent is an item, indent after the
  21006. description part, if any, or the bullet (see
  21007. `org-list-description-max-indent'). Else, indent like
  21008. parent's first line.
  21009. 3. Otherwise, indent relatively to current level, if
  21010. `org-adapt-indentation' is non-nil, or to left margin.
  21011. - On a blank line at the end of an element, indent according to
  21012. the type of the element. More precisely
  21013. 1. If element is a plain list, an item, or a footnote
  21014. definition, indent like the very last element within.
  21015. 2. If element is a paragraph, indent like its last non blank
  21016. line.
  21017. 3. Otherwise, indent like its very first line.
  21018. - In the code part of a source block, use language major mode
  21019. to indent current line if `org-src-tab-acts-natively' is
  21020. non-nil. If it is nil, do nothing.
  21021. - Otherwise, indent like the first non-blank line above.
  21022. The function doesn't indent an item as it could break the whole
  21023. list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
  21024. \\[org-shiftmetaright].
  21025. Also align node properties according to `org-property-format'."
  21026. (interactive)
  21027. (cond
  21028. (orgstruct-is-++
  21029. (let ((indent-line-function
  21030. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  21031. (indent-according-to-mode)))
  21032. ((org-at-heading-p) 'noindent)
  21033. (t
  21034. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  21035. (type (org-element-type element)))
  21036. (cond ((and (memq type '(plain-list item))
  21037. (= (line-beginning-position)
  21038. (org-element-property :post-affiliated element)))
  21039. 'noindent)
  21040. ((and (eq type 'src-block)
  21041. org-src-tab-acts-natively
  21042. (> (line-beginning-position)
  21043. (org-element-property :post-affiliated element))
  21044. (< (line-beginning-position)
  21045. (org-with-wide-buffer
  21046. (goto-char (org-element-property :end element))
  21047. (skip-chars-backward " \r\t\n")
  21048. (line-beginning-position))))
  21049. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  21050. (t
  21051. (let ((column (org--get-expected-indentation element nil)))
  21052. ;; Preserve current column.
  21053. (if (<= (current-column) (current-indentation))
  21054. (indent-line-to column)
  21055. (save-excursion (indent-line-to column))))
  21056. ;; Align node property. Also preserve current column.
  21057. (when (eq type 'node-property)
  21058. (let ((column (current-column)))
  21059. (org--align-node-property)
  21060. (org-move-to-column column)))))))))
  21061. (defun org-indent-region (start end)
  21062. "Indent each non-blank line in the region.
  21063. Called from a program, START and END specify the region to
  21064. indent. The function will not indent contents of example blocks,
  21065. verse blocks and export blocks as leading white spaces are
  21066. assumed to be significant there."
  21067. (interactive "r")
  21068. (save-excursion
  21069. (goto-char start)
  21070. (skip-chars-forward " \r\t\n")
  21071. (unless (eobp) (beginning-of-line))
  21072. (let ((indent-to
  21073. (lambda (ind pos)
  21074. ;; Set IND as indentation for all lines between point and
  21075. ;; POS. Blank lines are ignored. Leave point after POS
  21076. ;; once done.
  21077. (let ((limit (copy-marker pos)))
  21078. (while (< (point) limit)
  21079. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21080. (forward-line))
  21081. (set-marker limit nil))))
  21082. (end (copy-marker end)))
  21083. (while (< (point) end)
  21084. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21085. (let* ((element (org-element-at-point))
  21086. (type (org-element-type element))
  21087. (element-end (copy-marker (org-element-property :end element)))
  21088. (ind (org--get-expected-indentation element nil)))
  21089. (cond
  21090. ((or (memq type '(paragraph table table-row))
  21091. (not (or (org-element-property :contents-begin element)
  21092. (memq type
  21093. '(example-block export-block src-block)))))
  21094. ;; Elements here are indented as a single block. Also
  21095. ;; align node properties.
  21096. (when (eq type 'node-property)
  21097. (org--align-node-property)
  21098. (beginning-of-line))
  21099. (funcall indent-to ind (min element-end end)))
  21100. (t
  21101. ;; Elements in this category consist of three parts:
  21102. ;; before the contents, the contents, and after the
  21103. ;; contents. The contents are treated specially,
  21104. ;; according to the element type, or not indented at
  21105. ;; all. Other parts are indented as a single block.
  21106. (let* ((post (copy-marker
  21107. (org-element-property :post-affiliated element)))
  21108. (cbeg
  21109. (copy-marker
  21110. (cond
  21111. ((not (org-element-property :contents-begin element))
  21112. ;; Fake contents for source blocks.
  21113. (org-with-wide-buffer
  21114. (goto-char post)
  21115. (forward-line)
  21116. (point)))
  21117. ((memq type '(footnote-definition item plain-list))
  21118. ;; Contents in these elements could start on
  21119. ;; the same line as the beginning of the
  21120. ;; element. Make sure we start indenting
  21121. ;; from the second line.
  21122. (org-with-wide-buffer
  21123. (goto-char post)
  21124. (end-of-line)
  21125. (skip-chars-forward " \r\t\n")
  21126. (if (eobp) (point) (line-beginning-position))))
  21127. (t (org-element-property :contents-begin element)))))
  21128. (cend (copy-marker
  21129. (or (org-element-property :contents-end element)
  21130. ;; Fake contents for source blocks.
  21131. (org-with-wide-buffer
  21132. (goto-char element-end)
  21133. (skip-chars-backward " \r\t\n")
  21134. (line-beginning-position)))
  21135. t)))
  21136. ;; Do not change items indentation individually as it
  21137. ;; might break the list as a whole. On the other
  21138. ;; hand, when at a plain list, indent it as a whole.
  21139. (cond ((eq type 'plain-list)
  21140. (let ((offset (- ind (org-get-indentation))))
  21141. (unless (zerop offset)
  21142. (indent-rigidly (org-element-property :begin element)
  21143. (org-element-property :end element)
  21144. offset))
  21145. (goto-char cbeg)))
  21146. ((eq type 'item) (goto-char cbeg))
  21147. (t (funcall indent-to ind (min cbeg end))))
  21148. (when (< (point) end)
  21149. (cl-case type
  21150. ((example-block export-block verse-block))
  21151. (src-block
  21152. ;; In a source block, indent source code
  21153. ;; according to language major mode, but only if
  21154. ;; `org-src-tab-acts-natively' is non-nil.
  21155. (when (and (< (point) end) org-src-tab-acts-natively)
  21156. (ignore-errors
  21157. (org-babel-do-in-edit-buffer
  21158. (indent-region (point-min) (point-max))))))
  21159. (t (org-indent-region (point) (min cend end))))
  21160. (goto-char (min cend end))
  21161. (when (< (point) end)
  21162. (funcall indent-to ind (min element-end end))))
  21163. (set-marker post nil)
  21164. (set-marker cbeg nil)
  21165. (set-marker cend nil))))
  21166. (set-marker element-end nil))))
  21167. (set-marker end nil))))
  21168. (defun org-indent-drawer ()
  21169. "Indent the drawer at point."
  21170. (interactive)
  21171. (unless (save-excursion
  21172. (beginning-of-line)
  21173. (looking-at-p org-drawer-regexp))
  21174. (user-error "Not at a drawer"))
  21175. (let ((element (org-element-at-point)))
  21176. (unless (memq (org-element-type element) '(drawer property-drawer))
  21177. (user-error "Not at a drawer"))
  21178. (org-with-wide-buffer
  21179. (org-indent-region (org-element-property :begin element)
  21180. (org-element-property :end element))))
  21181. (message "Drawer at point indented"))
  21182. (defun org-indent-block ()
  21183. "Indent the block at point."
  21184. (interactive)
  21185. (unless (save-excursion
  21186. (beginning-of-line)
  21187. (let ((case-fold-search t))
  21188. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21189. (user-error "Not at a block"))
  21190. (let ((element (org-element-at-point)))
  21191. (unless (memq (org-element-type element)
  21192. '(comment-block center-block dynamic-block example-block
  21193. export-block quote-block special-block
  21194. src-block verse-block))
  21195. (user-error "Not at a block"))
  21196. (org-with-wide-buffer
  21197. (org-indent-region (org-element-property :begin element)
  21198. (org-element-property :end element))))
  21199. (message "Block at point indented"))
  21200. ;;; Filling
  21201. ;; We use our own fill-paragraph and auto-fill functions.
  21202. ;; `org-fill-paragraph' relies on adaptive filling and context
  21203. ;; checking. Appropriate `fill-prefix' is computed with
  21204. ;; `org-adaptive-fill-function'.
  21205. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21206. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21207. ;; `org-adaptive-fill-function' value. Internally,
  21208. ;; `org-comment-line-break-function' breaks the line.
  21209. ;; `org-setup-filling' installs filling and auto-filling related
  21210. ;; variables during `org-mode' initialization.
  21211. (defvar org-element-paragraph-separate) ; org-element.el
  21212. (defun org-setup-filling ()
  21213. (require 'org-element)
  21214. ;; Prevent auto-fill from inserting unwanted new items.
  21215. (when (boundp 'fill-nobreak-predicate)
  21216. (setq-local
  21217. fill-nobreak-predicate
  21218. (org-uniquify
  21219. (append fill-nobreak-predicate
  21220. '(org-fill-line-break-nobreak-p
  21221. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21222. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21223. (setq-local paragraph-start paragraph-ending)
  21224. (setq-local paragraph-separate paragraph-ending))
  21225. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21226. (setq-local auto-fill-inhibit-regexp nil)
  21227. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21228. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21229. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21230. (defun org-fill-line-break-nobreak-p ()
  21231. "Non-nil when a new line at point would create an Org line break."
  21232. (save-excursion
  21233. (skip-chars-backward "[ \t]")
  21234. (skip-chars-backward "\\\\")
  21235. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21236. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21237. "Non-nil when a new line at point would split a timestamp."
  21238. (and (org-at-timestamp-p t)
  21239. (not (looking-at org-ts-regexp-both))))
  21240. (declare-function message-in-body-p "message" ())
  21241. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21242. (defun org-adaptive-fill-function ()
  21243. "Compute a fill prefix for the current line.
  21244. Return fill prefix, as a string, or nil if current line isn't
  21245. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21246. matches in paragraphs or comments, use it."
  21247. (catch 'exit
  21248. (when (derived-mode-p 'message-mode)
  21249. (save-excursion
  21250. (beginning-of-line)
  21251. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21252. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21253. ((looking-at message-cite-prefix-regexp)
  21254. (throw 'exit (match-string-no-properties 0)))
  21255. ((looking-at org-outline-regexp)
  21256. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21257. (org-with-wide-buffer
  21258. (unless (org-at-heading-p)
  21259. (let* ((p (line-beginning-position))
  21260. (element (save-excursion
  21261. (beginning-of-line)
  21262. (org-element-at-point)))
  21263. (type (org-element-type element))
  21264. (post-affiliated (org-element-property :post-affiliated element)))
  21265. (unless (< p post-affiliated)
  21266. (cl-case type
  21267. (comment
  21268. (save-excursion
  21269. (beginning-of-line)
  21270. (looking-at "[ \t]*")
  21271. (concat (match-string 0) "# ")))
  21272. (footnote-definition "")
  21273. ((item plain-list)
  21274. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21275. (paragraph
  21276. ;; Fill prefix is usually the same as the current line,
  21277. ;; unless the paragraph is at the beginning of an item.
  21278. (let ((parent (org-element-property :parent element)))
  21279. (save-excursion
  21280. (beginning-of-line)
  21281. (cond ((eq (org-element-type parent) 'item)
  21282. (make-string (org-list-item-body-column
  21283. (org-element-property :begin parent))
  21284. ?\s))
  21285. ((and adaptive-fill-regexp
  21286. ;; Locally disable
  21287. ;; `adaptive-fill-function' to let
  21288. ;; `fill-context-prefix' handle
  21289. ;; `adaptive-fill-regexp' variable.
  21290. (let (adaptive-fill-function)
  21291. (fill-context-prefix
  21292. post-affiliated
  21293. (org-element-property :end element)))))
  21294. ((looking-at "[ \t]+") (match-string 0))
  21295. (t "")))))
  21296. (comment-block
  21297. ;; Only fill contents if P is within block boundaries.
  21298. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21299. (forward-line)
  21300. (point)))
  21301. (cend (save-excursion
  21302. (goto-char (org-element-property :end element))
  21303. (skip-chars-backward " \r\t\n")
  21304. (line-beginning-position))))
  21305. (when (and (>= p cbeg) (< p cend))
  21306. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21307. (match-string 0)
  21308. "")))))))))))
  21309. (declare-function message-goto-body "message" ())
  21310. (defvar message-cite-prefix-regexp) ; From message.el
  21311. (defun org-fill-paragraph (&optional justify)
  21312. "Fill element at point, when applicable.
  21313. This function only applies to comment blocks, comments, example
  21314. blocks and paragraphs. Also, as a special case, re-align table
  21315. when point is at one.
  21316. If JUSTIFY is non-nil (interactively, with prefix argument),
  21317. justify as well. If `sentence-end-double-space' is non-nil, then
  21318. period followed by one space does not end a sentence, so don't
  21319. break a line there. The variable `fill-column' controls the
  21320. width for filling.
  21321. For convenience, when point is at a plain list, an item or
  21322. a footnote definition, try to fill the first paragraph within."
  21323. (interactive)
  21324. (if (and (derived-mode-p 'message-mode)
  21325. (or (not (message-in-body-p))
  21326. (save-excursion (move-beginning-of-line 1)
  21327. (looking-at message-cite-prefix-regexp))))
  21328. ;; First ensure filling is correct in message-mode.
  21329. (let ((fill-paragraph-function
  21330. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21331. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21332. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21333. (paragraph-separate
  21334. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21335. (fill-paragraph nil))
  21336. (with-syntax-table org-mode-transpose-word-syntax-table
  21337. ;; Move to end of line in order to get the first paragraph
  21338. ;; within a plain list or a footnote definition.
  21339. (let ((element (save-excursion
  21340. (end-of-line)
  21341. (or (ignore-errors (org-element-at-point))
  21342. (user-error "An element cannot be parsed line %d"
  21343. (line-number-at-pos (point)))))))
  21344. ;; First check if point is in a blank line at the beginning of
  21345. ;; the buffer. In that case, ignore filling.
  21346. (cl-case (org-element-type element)
  21347. ;; Use major mode filling function is src blocks.
  21348. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21349. ;; Align Org tables, leave table.el tables as-is.
  21350. (table-row (org-table-align) t)
  21351. (table
  21352. (when (eq (org-element-property :type element) 'org)
  21353. (save-excursion
  21354. (goto-char (org-element-property :post-affiliated element))
  21355. (org-table-align)))
  21356. t)
  21357. (paragraph
  21358. ;; Paragraphs may contain `line-break' type objects.
  21359. (let ((beg (max (point-min)
  21360. (org-element-property :contents-begin element)))
  21361. (end (min (point-max)
  21362. (org-element-property :contents-end element))))
  21363. ;; Do nothing if point is at an affiliated keyword.
  21364. (if (< (line-end-position) beg) t
  21365. (when (derived-mode-p 'message-mode)
  21366. ;; In `message-mode', do not fill following citation
  21367. ;; in current paragraph nor text before message body.
  21368. (let ((body-start (save-excursion (message-goto-body))))
  21369. (when body-start (setq beg (max body-start beg))))
  21370. (when (save-excursion
  21371. (re-search-forward
  21372. (concat "^" message-cite-prefix-regexp) end t))
  21373. (setq end (match-beginning 0))))
  21374. ;; Fill paragraph, taking line breaks into account.
  21375. (save-excursion
  21376. (goto-char beg)
  21377. (let ((cuts (list beg)))
  21378. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21379. (when (eq 'line-break
  21380. (org-element-type
  21381. (save-excursion (backward-char)
  21382. (org-element-context))))
  21383. (push (point) cuts)))
  21384. (dolist (c (delq end cuts))
  21385. (fill-region-as-paragraph c end justify)
  21386. (setq end c))))
  21387. t)))
  21388. ;; Contents of `comment-block' type elements should be
  21389. ;; filled as plain text, but only if point is within block
  21390. ;; markers.
  21391. (comment-block
  21392. (let* ((case-fold-search t)
  21393. (beg (save-excursion
  21394. (goto-char (org-element-property :begin element))
  21395. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21396. (forward-line)
  21397. (point)))
  21398. (end (save-excursion
  21399. (goto-char (org-element-property :end element))
  21400. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21401. (line-beginning-position))))
  21402. (if (or (< (point) beg) (> (point) end)) t
  21403. (fill-region-as-paragraph
  21404. (save-excursion (end-of-line)
  21405. (re-search-backward "^[ \t]*$" beg 'move)
  21406. (line-beginning-position))
  21407. (save-excursion (beginning-of-line)
  21408. (re-search-forward "^[ \t]*$" end 'move)
  21409. (line-beginning-position))
  21410. justify))))
  21411. ;; Fill comments.
  21412. (comment
  21413. (let ((begin (org-element-property :post-affiliated element))
  21414. (end (org-element-property :end element)))
  21415. (when (and (>= (point) begin) (<= (point) end))
  21416. (let ((begin (save-excursion
  21417. (end-of-line)
  21418. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21419. (progn (forward-line) (point))
  21420. begin)))
  21421. (end (save-excursion
  21422. (end-of-line)
  21423. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21424. (1- (line-beginning-position))
  21425. (skip-chars-backward " \r\t\n")
  21426. (line-end-position)))))
  21427. ;; Do not fill comments when at a blank line.
  21428. (when (> end begin)
  21429. (let ((fill-prefix
  21430. (save-excursion
  21431. (beginning-of-line)
  21432. (looking-at "[ \t]*#")
  21433. (let ((comment-prefix (match-string 0)))
  21434. (goto-char (match-end 0))
  21435. (if (looking-at adaptive-fill-regexp)
  21436. (concat comment-prefix (match-string 0))
  21437. (concat comment-prefix " "))))))
  21438. (save-excursion
  21439. (fill-region-as-paragraph begin end justify))))))
  21440. t))
  21441. ;; Ignore every other element.
  21442. (otherwise t))))))
  21443. (defun org-auto-fill-function ()
  21444. "Auto-fill function."
  21445. ;; Check if auto-filling is meaningful.
  21446. (let ((fc (current-fill-column)))
  21447. (when (and fc (> (current-column) fc))
  21448. (let* ((fill-prefix (org-adaptive-fill-function))
  21449. ;; Enforce empty fill prefix, if required. Otherwise, it
  21450. ;; will be computed again.
  21451. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21452. (when fill-prefix (do-auto-fill))))))
  21453. (defun org-comment-line-break-function (&optional soft)
  21454. "Break line at point and indent, continuing comment if within one.
  21455. The inserted newline is marked hard if variable
  21456. `use-hard-newlines' is true, unless optional argument SOFT is
  21457. non-nil."
  21458. (if soft (insert-and-inherit ?\n) (newline 1))
  21459. (save-excursion (forward-char -1) (delete-horizontal-space))
  21460. (delete-horizontal-space)
  21461. (indent-to-left-margin)
  21462. (insert-before-markers-and-inherit fill-prefix))
  21463. ;;; Fixed Width Areas
  21464. (defun org-toggle-fixed-width ()
  21465. "Toggle fixed-width markup.
  21466. Add or remove fixed-width markup on current line, whenever it
  21467. makes sense. Return an error otherwise.
  21468. If a region is active and if it contains only fixed-width areas
  21469. or blank lines, remove all fixed-width markup in it. If the
  21470. region contains anything else, convert all non-fixed-width lines
  21471. to fixed-width ones.
  21472. Blank lines at the end of the region are ignored unless the
  21473. region only contains such lines."
  21474. (interactive)
  21475. (if (not (org-region-active-p))
  21476. ;; No region:
  21477. ;;
  21478. ;; Remove fixed width marker only in a fixed-with element.
  21479. ;;
  21480. ;; Add fixed width maker in paragraphs, in blank lines after
  21481. ;; elements or at the beginning of a headline or an inlinetask,
  21482. ;; and before any one-line elements (e.g., a clock).
  21483. (progn
  21484. (beginning-of-line)
  21485. (let* ((element (org-element-at-point))
  21486. (type (org-element-type element)))
  21487. (cond
  21488. ((and (eq type 'fixed-width)
  21489. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21490. (replace-match
  21491. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21492. ((and (memq type '(babel-call clock comment diary-sexp headline
  21493. horizontal-rule keyword paragraph
  21494. planning))
  21495. (<= (org-element-property :post-affiliated element) (point)))
  21496. (skip-chars-forward " \t")
  21497. (insert ": "))
  21498. ((and (looking-at-p "[ \t]*$")
  21499. (or (eq type 'inlinetask)
  21500. (save-excursion
  21501. (skip-chars-forward " \r\t\n")
  21502. (<= (org-element-property :end element) (point)))))
  21503. (delete-region (point) (line-end-position))
  21504. (org-indent-line)
  21505. (insert ": "))
  21506. (t (user-error "Cannot insert a fixed-width line here")))))
  21507. ;; Region active.
  21508. (let* ((begin (save-excursion
  21509. (goto-char (region-beginning))
  21510. (line-beginning-position)))
  21511. (end (copy-marker
  21512. (save-excursion
  21513. (goto-char (region-end))
  21514. (unless (eolp) (beginning-of-line))
  21515. (if (save-excursion (re-search-backward "\\S-" begin t))
  21516. (progn (skip-chars-backward " \r\t\n") (point))
  21517. (point)))))
  21518. (all-fixed-width-p
  21519. (catch 'not-all-p
  21520. (save-excursion
  21521. (goto-char begin)
  21522. (skip-chars-forward " \r\t\n")
  21523. (when (eobp) (throw 'not-all-p nil))
  21524. (while (< (point) end)
  21525. (let ((element (org-element-at-point)))
  21526. (if (eq (org-element-type element) 'fixed-width)
  21527. (goto-char (org-element-property :end element))
  21528. (throw 'not-all-p nil))))
  21529. t))))
  21530. (if all-fixed-width-p
  21531. (save-excursion
  21532. (goto-char begin)
  21533. (while (< (point) end)
  21534. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21535. (replace-match
  21536. "" nil nil nil
  21537. (if (= (line-end-position) (match-end 0)) 0 1)))
  21538. (forward-line)))
  21539. (let ((min-ind (point-max)))
  21540. ;; Find minimum indentation across all lines.
  21541. (save-excursion
  21542. (goto-char begin)
  21543. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21544. (setq min-ind 0)
  21545. (catch 'zerop
  21546. (while (< (point) end)
  21547. (unless (looking-at-p "[ \t]*$")
  21548. (let ((ind (org-get-indentation)))
  21549. (setq min-ind (min min-ind ind))
  21550. (when (zerop ind) (throw 'zerop t))))
  21551. (forward-line)))))
  21552. ;; Loop over all lines and add fixed-width markup everywhere
  21553. ;; but in fixed-width lines.
  21554. (save-excursion
  21555. (goto-char begin)
  21556. (while (< (point) end)
  21557. (cond
  21558. ((org-at-heading-p)
  21559. (insert ": ")
  21560. (forward-line)
  21561. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21562. (insert ":")
  21563. (forward-line)))
  21564. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21565. (let* ((element (org-element-at-point))
  21566. (element-end (org-element-property :end element)))
  21567. (if (eq (org-element-type element) 'fixed-width)
  21568. (progn (goto-char element-end)
  21569. (skip-chars-backward " \r\t\n")
  21570. (forward-line))
  21571. (let ((limit (min end element-end)))
  21572. (while (< (point) limit)
  21573. (org-move-to-column min-ind t)
  21574. (insert ": ")
  21575. (forward-line))))))
  21576. (t
  21577. (org-move-to-column min-ind t)
  21578. (insert ": ")
  21579. (forward-line)))))))
  21580. (set-marker end nil))))
  21581. ;;; Comments
  21582. ;; Org comments syntax is quite complex. It requires the entire line
  21583. ;; to be just a comment. Also, even with the right syntax at the
  21584. ;; beginning of line, some some elements (i.e. verse-block or
  21585. ;; example-block) don't accept comments. Usual Emacs comment commands
  21586. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21587. ;; Org still relies on `comment-dwim', but cannot trust
  21588. ;; `comment-only-p'. So, `comment-region-function' and
  21589. ;; `uncomment-region-function' both point
  21590. ;; to`org-comment-or-uncomment-region'. Eventually,
  21591. ;; `org-insert-comment' takes care of insertion of comments at the
  21592. ;; beginning of line.
  21593. ;; `org-setup-comments-handling' install comments related variables
  21594. ;; during `org-mode' initialization.
  21595. (defun org-setup-comments-handling ()
  21596. (interactive)
  21597. (setq-local comment-use-syntax nil)
  21598. (setq-local comment-start "# ")
  21599. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21600. (setq-local comment-insert-comment-function 'org-insert-comment)
  21601. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21602. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21603. (defun org-insert-comment ()
  21604. "Insert an empty comment above current line.
  21605. If the line is empty, insert comment at its beginning. When
  21606. point is within a source block, comment according to the related
  21607. major mode."
  21608. (if (let ((element (org-element-at-point)))
  21609. (and (eq (org-element-type element) 'src-block)
  21610. (< (save-excursion
  21611. (goto-char (org-element-property :post-affiliated element))
  21612. (line-end-position))
  21613. (point))
  21614. (> (save-excursion
  21615. (goto-char (org-element-property :end element))
  21616. (skip-chars-backward " \r\t\n")
  21617. (line-beginning-position))
  21618. (point))))
  21619. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21620. (beginning-of-line)
  21621. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21622. (open-line 1))
  21623. (org-indent-line)
  21624. (insert "# ")))
  21625. (defvar comment-empty-lines) ; From newcomment.el.
  21626. (defun org-comment-or-uncomment-region (beg end &rest _)
  21627. "Comment or uncomment each non-blank line in the region.
  21628. Uncomment each non-blank line between BEG and END if it only
  21629. contains commented lines. Otherwise, comment them. If region is
  21630. strictly within a source block, use appropriate comment syntax."
  21631. (if (let ((element (org-element-at-point)))
  21632. (and (eq (org-element-type element) 'src-block)
  21633. (< (save-excursion
  21634. (goto-char (org-element-property :post-affiliated element))
  21635. (line-end-position))
  21636. beg)
  21637. (>= (save-excursion
  21638. (goto-char (org-element-property :end element))
  21639. (skip-chars-backward " \r\t\n")
  21640. (line-beginning-position))
  21641. end)))
  21642. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21643. (save-restriction
  21644. ;; Restrict region
  21645. (narrow-to-region (save-excursion (goto-char beg)
  21646. (skip-chars-forward " \r\t\n" end)
  21647. (line-beginning-position))
  21648. (save-excursion (goto-char end)
  21649. (skip-chars-backward " \r\t\n" beg)
  21650. (line-end-position)))
  21651. (let ((uncommentp
  21652. ;; UNCOMMENTP is non-nil when every non blank line between
  21653. ;; BEG and END is a comment.
  21654. (save-excursion
  21655. (goto-char (point-min))
  21656. (while (and (not (eobp))
  21657. (let ((element (org-element-at-point)))
  21658. (and (eq (org-element-type element) 'comment)
  21659. (goto-char (min (point-max)
  21660. (org-element-property
  21661. :end element)))))))
  21662. (eobp))))
  21663. (if uncommentp
  21664. ;; Only blank lines and comments in region: uncomment it.
  21665. (save-excursion
  21666. (goto-char (point-min))
  21667. (while (not (eobp))
  21668. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21669. (replace-match "" nil nil nil 1))
  21670. (forward-line)))
  21671. ;; Comment each line in region.
  21672. (let ((min-indent (point-max)))
  21673. ;; First find the minimum indentation across all lines.
  21674. (save-excursion
  21675. (goto-char (point-min))
  21676. (while (and (not (eobp)) (not (zerop min-indent)))
  21677. (unless (looking-at "[ \t]*$")
  21678. (setq min-indent (min min-indent (current-indentation))))
  21679. (forward-line)))
  21680. ;; Then loop over all lines.
  21681. (save-excursion
  21682. (goto-char (point-min))
  21683. (while (not (eobp))
  21684. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21685. ;; Don't get fooled by invisible text (e.g. link path)
  21686. ;; when moving to column MIN-INDENT.
  21687. (let ((buffer-invisibility-spec nil))
  21688. (org-move-to-column min-indent t))
  21689. (insert comment-start))
  21690. (forward-line)))))))))
  21691. (defun org-comment-dwim (_arg)
  21692. "Call `comment-dwim' within a source edit buffer if needed."
  21693. (interactive "*P")
  21694. (if (org-in-src-block-p)
  21695. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21696. (call-interactively 'comment-dwim)))
  21697. ;;; Timestamps API
  21698. ;; This section contains tools to operate on timestamp objects, as
  21699. ;; returned by, e.g. `org-element-context'.
  21700. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21701. "Encode TIMESTAMP object into Emacs internal time.
  21702. Use end of date range or time range when END is non-nil."
  21703. (apply #'encode-time
  21704. (cons 0
  21705. (mapcar
  21706. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21707. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21708. '(:minute-start :hour-start :day-start :month-start
  21709. :year-start))))))
  21710. (defun org-timestamp-has-time-p (timestamp)
  21711. "Non-nil when TIMESTAMP has a time specified."
  21712. (org-element-property :hour-start timestamp))
  21713. (defun org-timestamp-format (timestamp format &optional end utc)
  21714. "Format a TIMESTAMP object into a string.
  21715. FORMAT is a format specifier to be passed to
  21716. `format-time-string'.
  21717. When optional argument END is non-nil, use end of date-range or
  21718. time-range, if possible.
  21719. When optional argument UTC is non-nil, time will be expressed as
  21720. Universal Time."
  21721. (format-time-string
  21722. format (org-timestamp--to-internal-time timestamp end)
  21723. (and utc t)))
  21724. (defun org-timestamp-split-range (timestamp &optional end)
  21725. "Extract a TIMESTAMP object from a date or time range.
  21726. END, when non-nil, means extract the end of the range.
  21727. Otherwise, extract its start.
  21728. Return a new timestamp object."
  21729. (let ((type (org-element-property :type timestamp)))
  21730. (if (memq type '(active inactive diary)) timestamp
  21731. (let ((split-ts (org-element-copy timestamp)))
  21732. ;; Set new type.
  21733. (org-element-put-property
  21734. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21735. ;; Copy start properties over end properties if END is
  21736. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21737. (let ((p-alist '((:minute-start . :minute-end)
  21738. (:hour-start . :hour-end)
  21739. (:day-start . :day-end)
  21740. (:month-start . :month-end)
  21741. (:year-start . :year-end))))
  21742. (dolist (p-cell p-alist)
  21743. (org-element-put-property
  21744. split-ts
  21745. (funcall (if end #'car #'cdr) p-cell)
  21746. (org-element-property
  21747. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21748. ;; Eventually refresh `:raw-value'.
  21749. (org-element-put-property split-ts :raw-value nil)
  21750. (org-element-put-property
  21751. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21752. (defun org-timestamp-translate (timestamp &optional boundary)
  21753. "Translate TIMESTAMP object to custom format.
  21754. Format string is defined in `org-time-stamp-custom-formats',
  21755. which see.
  21756. When optional argument BOUNDARY is non-nil, it is either the
  21757. symbol `start' or `end'. In this case, only translate the
  21758. starting or ending part of TIMESTAMP if it is a date or time
  21759. range. Otherwise, translate both parts.
  21760. Return timestamp as-is if `org-display-custom-times' is nil or if
  21761. it has a `diary' type."
  21762. (let ((type (org-element-property :type timestamp)))
  21763. (if (or (not org-display-custom-times) (eq type 'diary))
  21764. (org-element-interpret-data timestamp)
  21765. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21766. org-time-stamp-custom-formats)))
  21767. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21768. (concat (org-timestamp-format timestamp fmt)
  21769. "--"
  21770. (org-timestamp-format timestamp fmt t))
  21771. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21772. ;;; Other stuff.
  21773. (defvar reftex-docstruct-symbol)
  21774. (defvar reftex-cite-format)
  21775. (defvar org--rds)
  21776. (defun org-reftex-citation ()
  21777. "Use reftex-citation to insert a citation into the buffer.
  21778. This looks for a line like
  21779. #+BIBLIOGRAPHY: foo plain option:-d
  21780. and derives from it that foo.bib is the bibliography file relevant
  21781. for this document. It then installs the necessary environment for RefTeX
  21782. to work in this buffer and calls `reftex-citation' to insert a citation
  21783. into the buffer.
  21784. Export of such citations to both LaTeX and HTML is handled by the contributed
  21785. package ox-bibtex by Taru Karttunen."
  21786. (interactive)
  21787. (let ((reftex-docstruct-symbol 'org--rds)
  21788. (reftex-cite-format "\\cite{%l}")
  21789. org--rds bib)
  21790. (save-excursion
  21791. (save-restriction
  21792. (widen)
  21793. (let ((case-fold-search t)
  21794. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21795. (if (not (save-excursion
  21796. (or (re-search-forward re nil t)
  21797. (re-search-backward re nil t))))
  21798. (user-error "No bibliography defined in file")
  21799. (setq bib (concat (match-string 1) ".bib")
  21800. org--rds (list (list 'bib bib)))))))
  21801. (call-interactively 'reftex-citation)))
  21802. ;;;; Functions extending outline functionality
  21803. (defun org-beginning-of-line (&optional arg)
  21804. "Go to the beginning of the current line. If that is invisible, continue
  21805. to a visible line beginning. This makes the function of C-a more intuitive.
  21806. If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
  21807. first attempt, and only move to after the tags when the cursor is already
  21808. beyond the end of the headline."
  21809. (interactive "P")
  21810. (let ((pos (point))
  21811. (special (if (consp org-special-ctrl-a/e)
  21812. (car org-special-ctrl-a/e)
  21813. org-special-ctrl-a/e))
  21814. deactivate-mark refpos)
  21815. (call-interactively (if (bound-and-true-p visual-line-mode)
  21816. #'beginning-of-visual-line
  21817. #'move-beginning-of-line))
  21818. (cond
  21819. ((or arg (not special)))
  21820. ((and (looking-at org-complex-heading-regexp)
  21821. (eq (char-after (match-end 1)) ?\s))
  21822. (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21823. (point-at-eol)))
  21824. (goto-char
  21825. (if (eq special t)
  21826. (cond ((> pos refpos) refpos)
  21827. ((= pos (point)) refpos)
  21828. (t (point)))
  21829. (cond ((> pos (point)) (point))
  21830. ((not (eq last-command this-command)) (point))
  21831. (t refpos)))))
  21832. ((org-at-item-p)
  21833. ;; Being at an item and not looking at an the item means point
  21834. ;; was previously moved to beginning of a visual line, which
  21835. ;; doesn't contain the item. Therefore, do nothing special,
  21836. ;; just stay here.
  21837. (when (looking-at org-list-full-item-re)
  21838. ;; Set special position at first white space character after
  21839. ;; bullet, and check-box, if any.
  21840. (let ((after-bullet
  21841. (let ((box (match-end 3)))
  21842. (if (not box) (match-end 1)
  21843. (let ((after (char-after box)))
  21844. (if (and after (= after ? )) (1+ box) box))))))
  21845. ;; Special case: Move point to special position when
  21846. ;; currently after it or at beginning of line.
  21847. (if (eq special t)
  21848. (when (or (> pos after-bullet) (= (point) pos))
  21849. (goto-char after-bullet))
  21850. ;; Reversed case: Move point to special position when
  21851. ;; point was already at beginning of line and command is
  21852. ;; repeated.
  21853. (when (and (= (point) pos) (eq last-command this-command))
  21854. (goto-char after-bullet))))))))
  21855. (setq disable-point-adjustment
  21856. (or (not (invisible-p (point)))
  21857. (not (invisible-p (max (point-min) (1- (point))))))))
  21858. (defun org-end-of-line (&optional arg)
  21859. "Go to the end of the line.
  21860. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21861. tags on the first attempt, and only move to after the tags when
  21862. the cursor is already beyond the end of the headline."
  21863. (interactive "P")
  21864. (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
  21865. org-special-ctrl-a/e))
  21866. (move-fun (cond ((bound-and-true-p visual-line-mode)
  21867. 'end-of-visual-line)
  21868. ((fboundp 'move-end-of-line) 'move-end-of-line)
  21869. (t 'end-of-line)))
  21870. deactivate-mark)
  21871. (if (or (not special) arg) (call-interactively move-fun)
  21872. (let* ((element (save-excursion (beginning-of-line)
  21873. (org-element-at-point)))
  21874. (type (org-element-type element)))
  21875. (cond
  21876. ((memq type '(headline inlinetask))
  21877. (let ((pos (point)))
  21878. (beginning-of-line 1)
  21879. (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
  21880. (if (eq special t)
  21881. (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
  21882. (goto-char (match-beginning 1))
  21883. (goto-char (match-end 0)))
  21884. (if (or (< pos (match-end 0))
  21885. (not (eq this-command last-command)))
  21886. (goto-char (match-end 0))
  21887. (goto-char (match-beginning 1))))
  21888. (call-interactively move-fun))))
  21889. ((outline-invisible-p (line-end-position))
  21890. ;; If element is hidden, `move-end-of-line' would put point
  21891. ;; after it. Use `end-of-line' to stay on current line.
  21892. (call-interactively 'end-of-line))
  21893. (t (call-interactively move-fun))))))
  21894. (setq disable-point-adjustment
  21895. (or (not (invisible-p (point)))
  21896. (not (invisible-p (max (point-min) (1- (point))))))))
  21897. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21898. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21899. (defun org-backward-sentence (&optional _arg)
  21900. "Go to beginning of sentence, or beginning of table field.
  21901. This will call `backward-sentence' or `org-table-beginning-of-field',
  21902. depending on context."
  21903. (interactive)
  21904. (let* ((element (org-element-at-point))
  21905. (contents-begin (org-element-property :contents-begin element))
  21906. (table (org-element-lineage element '(table) t)))
  21907. (if (and table
  21908. (> (point) contents-begin)
  21909. (<= (point) (org-element-property :contents-end table)))
  21910. (call-interactively #'org-table-beginning-of-field)
  21911. (save-restriction
  21912. (when (and contents-begin
  21913. (< (point-min) contents-begin)
  21914. (> (point) contents-begin))
  21915. (narrow-to-region contents-begin
  21916. (org-element-property :contents-end element)))
  21917. (call-interactively #'backward-sentence)))))
  21918. (defun org-forward-sentence (&optional _arg)
  21919. "Go to end of sentence, or end of table field.
  21920. This will call `forward-sentence' or `org-table-end-of-field',
  21921. depending on context."
  21922. (interactive)
  21923. (let* ((element (org-element-at-point))
  21924. (contents-end (org-element-property :contents-end element))
  21925. (table (org-element-lineage element '(table) t)))
  21926. (if (and table
  21927. (>= (point) (org-element-property :contents-begin table))
  21928. (< (point) contents-end))
  21929. (call-interactively #'org-table-end-of-field)
  21930. (save-restriction
  21931. (when (and contents-end
  21932. (> (point-max) contents-end)
  21933. ;; Skip blank lines between elements.
  21934. (< (org-element-property :end element)
  21935. (save-excursion (goto-char contents-end)
  21936. (skip-chars-forward " \r\t\n"))))
  21937. (narrow-to-region (org-element-property :contents-begin element)
  21938. contents-end))
  21939. (call-interactively #'forward-sentence)))))
  21940. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21941. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21942. (defun org-kill-line (&optional _arg)
  21943. "Kill line, to tags or end of line."
  21944. (interactive)
  21945. (cond
  21946. ((or (not org-special-ctrl-k)
  21947. (bolp)
  21948. (not (org-at-heading-p)))
  21949. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21950. org-ctrl-k-protect-subtree
  21951. (or (eq org-ctrl-k-protect-subtree 'error)
  21952. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21953. (user-error "C-k aborted as it would kill a hidden subtree"))
  21954. (call-interactively
  21955. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21956. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21957. (kill-region (point) (match-beginning 1))
  21958. (org-set-tags nil t))
  21959. (t (kill-region (point) (point-at-eol)))))
  21960. (define-key org-mode-map "\C-k" 'org-kill-line)
  21961. (defun org-yank (&optional arg)
  21962. "Yank. If the kill is a subtree, treat it specially.
  21963. This command will look at the current kill and check if is a single
  21964. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21965. cursor is at the beginning of a line or after the stars of a currently
  21966. empty headline, then the yank is handled specially. How exactly depends
  21967. on the value of the following variables.
  21968. `org-yank-folded-subtrees'
  21969. By default, this variable is non-nil, which results in subtree(s)
  21970. being folded after insertion, but only if doing so would now
  21971. swallow text after the yanked text.
  21972. `org-yank-adjusted-subtrees'
  21973. When non-nil (the default value is nil), the subtree will be
  21974. promoted or demoted in order to fit into the local outline tree
  21975. structure, which means that the level will be adjusted so that it
  21976. becomes the smaller one of the two *visible* surrounding headings.
  21977. Any prefix to this command will cause `yank' to be called directly with
  21978. no special treatment. In particular, a simple \\[universal-argument] prefix \
  21979. will just
  21980. plainly yank the text as it is.
  21981. \[1] The test checks if the first non-white line is a heading
  21982. and if there are no other headings with fewer stars."
  21983. (interactive "P")
  21984. (org-yank-generic 'yank arg))
  21985. (defun org-yank-generic (command arg)
  21986. "Perform some yank-like command.
  21987. This function implements the behavior described in the `org-yank'
  21988. documentation. However, it has been generalized to work for any
  21989. interactive command with similar behavior."
  21990. ;; pretend to be command COMMAND
  21991. (setq this-command command)
  21992. (if arg
  21993. (call-interactively command)
  21994. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21995. (and (org-kill-is-subtree-p)
  21996. (or (bolp)
  21997. (and (looking-at "[ \t]*$")
  21998. (string-match
  21999. "\\`\\*+\\'"
  22000. (buffer-substring (point-at-bol) (point)))))))
  22001. swallowp)
  22002. (cond
  22003. ((and subtreep org-yank-folded-subtrees)
  22004. (let ((beg (point))
  22005. end)
  22006. (if (and subtreep org-yank-adjusted-subtrees)
  22007. (org-paste-subtree nil nil 'for-yank)
  22008. (call-interactively command))
  22009. (setq end (point))
  22010. (goto-char beg)
  22011. (when (and (bolp) subtreep
  22012. (not (setq swallowp
  22013. (org-yank-folding-would-swallow-text beg end))))
  22014. (org-with-limited-levels
  22015. (or (looking-at org-outline-regexp)
  22016. (re-search-forward org-outline-regexp-bol end t))
  22017. (while (and (< (point) end) (looking-at org-outline-regexp))
  22018. (outline-hide-subtree)
  22019. (org-cycle-show-empty-lines 'folded)
  22020. (condition-case nil
  22021. (outline-forward-same-level 1)
  22022. (error (goto-char end))))))
  22023. (when swallowp
  22024. (message
  22025. "Inserted text not folded because that would swallow text"))
  22026. (goto-char end)
  22027. (skip-chars-forward " \t\n\r")
  22028. (beginning-of-line 1)
  22029. (push-mark beg 'nomsg)))
  22030. ((and subtreep org-yank-adjusted-subtrees)
  22031. (let ((beg (point-at-bol)))
  22032. (org-paste-subtree nil nil 'for-yank)
  22033. (push-mark beg 'nomsg)))
  22034. (t
  22035. (call-interactively command))))))
  22036. (defun org-yank-folding-would-swallow-text (beg end)
  22037. "Would hide-subtree at BEG swallow any text after END?"
  22038. (let (level)
  22039. (org-with-limited-levels
  22040. (save-excursion
  22041. (goto-char beg)
  22042. (when (or (looking-at org-outline-regexp)
  22043. (re-search-forward org-outline-regexp-bol end t))
  22044. (setq level (org-outline-level)))
  22045. (goto-char end)
  22046. (skip-chars-forward " \t\r\n\v\f")
  22047. (not (or (eobp)
  22048. (and (bolp) (looking-at-p org-outline-regexp)
  22049. (<= (org-outline-level) level))))))))
  22050. (define-key org-mode-map "\C-y" 'org-yank)
  22051. (defun org-truely-invisible-p ()
  22052. "Check if point is at a character currently not visible.
  22053. This version does not only check the character property, but also
  22054. `visible-mode'."
  22055. ;; Early versions of noutline don't have `outline-invisible-p'.
  22056. (unless (bound-and-true-p visible-mode)
  22057. (outline-invisible-p)))
  22058. (defun org-invisible-p2 ()
  22059. "Check if point is at a character currently not visible."
  22060. (save-excursion
  22061. (when (and (eolp) (not (bobp))) (backward-char 1))
  22062. ;; Early versions of noutline don't have `outline-invisible-p'.
  22063. (outline-invisible-p)))
  22064. (defun org-back-to-heading (&optional invisible-ok)
  22065. "Call `outline-back-to-heading', but provide a better error message."
  22066. (condition-case nil
  22067. (outline-back-to-heading invisible-ok)
  22068. (error (error "Before first headline at position %d in buffer %s"
  22069. (point) (current-buffer)))))
  22070. (defun org-before-first-heading-p ()
  22071. "Before first heading?"
  22072. (save-excursion
  22073. (end-of-line)
  22074. (null (re-search-backward org-outline-regexp-bol nil t))))
  22075. (defun org-at-heading-p (&optional ignored)
  22076. (outline-on-heading-p t))
  22077. (defun org-in-commented-heading-p (&optional no-inheritance)
  22078. "Non-nil if point is under a commented heading.
  22079. This function also checks ancestors of the current headline,
  22080. unless optional argument NO-INHERITANCE is non-nil."
  22081. (cond
  22082. ((org-before-first-heading-p) nil)
  22083. ((let ((headline (nth 4 (org-heading-components))))
  22084. (and headline
  22085. (let ((case-fold-search nil))
  22086. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22087. headline)))))
  22088. (no-inheritance nil)
  22089. (t
  22090. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22091. (defun org-at-comment-p nil
  22092. "Is cursor in a commented line?"
  22093. (save-excursion
  22094. (save-match-data
  22095. (beginning-of-line)
  22096. (looking-at "^[ \t]*# "))))
  22097. (defun org-at-drawer-p nil
  22098. "Is cursor at a drawer keyword?"
  22099. (save-excursion
  22100. (move-beginning-of-line 1)
  22101. (looking-at org-drawer-regexp)))
  22102. (defun org-at-block-p nil
  22103. "Is cursor at a block keyword?"
  22104. (save-excursion
  22105. (move-beginning-of-line 1)
  22106. (looking-at org-block-regexp)))
  22107. (defun org-point-at-end-of-empty-headline ()
  22108. "If point is at the end of an empty headline, return t, else nil.
  22109. If the heading only contains a TODO keyword, it is still still considered
  22110. empty."
  22111. (and (looking-at "[ \t]*$")
  22112. (when org-todo-line-regexp
  22113. (save-excursion
  22114. (beginning-of-line 1)
  22115. (let ((case-fold-search nil))
  22116. (looking-at org-todo-line-regexp)
  22117. (string= (match-string 3) ""))))))
  22118. (defun org-at-heading-or-item-p ()
  22119. (or (org-at-heading-p) (org-at-item-p)))
  22120. (defun org-at-target-p ()
  22121. (or (org-in-regexp org-radio-target-regexp)
  22122. (org-in-regexp org-target-regexp)))
  22123. ;; Compatibility alias with Org versions < 7.8.03
  22124. (defalias 'org-on-target-p 'org-at-target-p)
  22125. (defun org-up-heading-all (arg)
  22126. "Move to the heading line of which the present line is a subheading.
  22127. This function considers both visible and invisible heading lines.
  22128. With argument, move up ARG levels."
  22129. (outline-up-heading arg t))
  22130. (defun org-up-heading-safe ()
  22131. "Move to the heading line of which the present line is a subheading.
  22132. This version will not throw an error. It will return the level of the
  22133. headline found, or nil if no higher level is found.
  22134. Also, this function will be a lot faster than `outline-up-heading',
  22135. because it relies on stars being the outline starters. This can really
  22136. make a significant difference in outlines with very many siblings."
  22137. (when (ignore-errors (org-back-to-heading t))
  22138. (let ((level-up (1- (funcall outline-level))))
  22139. (and (> level-up 0)
  22140. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22141. (funcall outline-level)))))
  22142. (defun org-first-sibling-p ()
  22143. "Is this heading the first child of its parents?"
  22144. (interactive)
  22145. (let ((re org-outline-regexp-bol)
  22146. level l)
  22147. (unless (org-at-heading-p t)
  22148. (user-error "Not at a heading"))
  22149. (setq level (funcall outline-level))
  22150. (save-excursion
  22151. (if (not (re-search-backward re nil t))
  22152. t
  22153. (setq l (funcall outline-level))
  22154. (< l level)))))
  22155. (defun org-goto-sibling (&optional previous)
  22156. "Goto the next sibling, even if it is invisible.
  22157. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22158. when a sibling was found. When none is found, return nil and don't
  22159. move point."
  22160. (let ((fun (if previous 're-search-backward 're-search-forward))
  22161. (pos (point))
  22162. (re org-outline-regexp-bol)
  22163. level l)
  22164. (when (ignore-errors (org-back-to-heading t))
  22165. (setq level (funcall outline-level))
  22166. (catch 'exit
  22167. (or previous (forward-char 1))
  22168. (while (funcall fun re nil t)
  22169. (setq l (funcall outline-level))
  22170. (when (< l level) (goto-char pos) (throw 'exit nil))
  22171. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22172. (goto-char pos)
  22173. nil))))
  22174. (defun org-show-siblings ()
  22175. "Show all siblings of the current headline."
  22176. (save-excursion
  22177. (while (org-goto-sibling) (org-flag-heading nil)))
  22178. (save-excursion
  22179. (while (org-goto-sibling 'previous)
  22180. (org-flag-heading nil))))
  22181. (defun org-goto-first-child ()
  22182. "Goto the first child, even if it is invisible.
  22183. Return t when a child was found. Otherwise don't move point and
  22184. return nil."
  22185. (let (level (pos (point)) (re org-outline-regexp-bol))
  22186. (when (ignore-errors (org-back-to-heading t))
  22187. (setq level (outline-level))
  22188. (forward-char 1)
  22189. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22190. (progn (goto-char (match-beginning 0)) t)
  22191. (goto-char pos) nil))))
  22192. (defun org-show-hidden-entry ()
  22193. "Show an entry where even the heading is hidden."
  22194. (save-excursion
  22195. (org-show-entry)))
  22196. (defun org-flag-heading (flag &optional entry)
  22197. "Flag the current heading. FLAG non-nil means make invisible.
  22198. When ENTRY is non-nil, show the entire entry."
  22199. (save-excursion
  22200. (org-back-to-heading t)
  22201. ;; Check if we should show the entire entry
  22202. (if entry
  22203. (progn
  22204. (org-show-entry)
  22205. (save-excursion
  22206. (and (outline-next-heading)
  22207. (org-flag-heading nil))))
  22208. (outline-flag-region (max (point-min) (1- (point)))
  22209. (save-excursion (outline-end-of-heading) (point))
  22210. flag))))
  22211. (defun org-get-next-sibling ()
  22212. "Move to next heading of the same level, and return point.
  22213. If there is no such heading, return nil.
  22214. This is like outline-next-sibling, but invisible headings are ok."
  22215. (let ((level (funcall outline-level)))
  22216. (outline-next-heading)
  22217. (while (and (not (eobp)) (> (funcall outline-level) level))
  22218. (outline-next-heading))
  22219. (unless (or (eobp) (< (funcall outline-level) level))
  22220. (point))))
  22221. (defun org-get-last-sibling ()
  22222. "Move to previous heading of the same level, and return point.
  22223. If there is no such heading, return nil."
  22224. (let ((opoint (point))
  22225. (level (funcall outline-level)))
  22226. (outline-previous-heading)
  22227. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22228. (while (and (> (funcall outline-level) level)
  22229. (not (bobp)))
  22230. (outline-previous-heading))
  22231. (unless (< (funcall outline-level) level)
  22232. (point)))))
  22233. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22234. "Goto to the end of a subtree."
  22235. ;; This contains an exact copy of the original function, but it uses
  22236. ;; `org-back-to-heading', to make it work also in invisible
  22237. ;; trees. And is uses an invisible-ok argument.
  22238. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22239. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22240. ;; with many children and grandchildren etc, this can be much faster
  22241. ;; than the outline version.
  22242. (org-back-to-heading invisible-ok)
  22243. (let ((first t)
  22244. (level (funcall outline-level)))
  22245. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22246. ;; A true heading (not a plain list item), in Org
  22247. ;; This means we can easily find the end by looking
  22248. ;; only for the right number of stars. Using a regexp to do
  22249. ;; this is so much faster than using a Lisp loop.
  22250. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22251. (forward-char 1)
  22252. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22253. ;; something else, do it the slow way
  22254. (while (and (not (eobp))
  22255. (or first (> (funcall outline-level) level)))
  22256. (setq first nil)
  22257. (outline-next-heading)))
  22258. (unless to-heading
  22259. (when (memq (preceding-char) '(?\n ?\^M))
  22260. ;; Go to end of line before heading
  22261. (forward-char -1)
  22262. (when (memq (preceding-char) '(?\n ?\^M))
  22263. ;; leave blank line before heading
  22264. (forward-char -1)))))
  22265. (point))
  22266. (defun org-end-of-meta-data (&optional full)
  22267. "Skip planning line and properties drawer in current entry.
  22268. When optional argument FULL is non-nil, also skip empty lines,
  22269. clocking lines and regular drawers at the beginning of the
  22270. entry."
  22271. (org-back-to-heading t)
  22272. (forward-line)
  22273. (when (looking-at-p org-planning-line-re) (forward-line))
  22274. (when (looking-at org-property-drawer-re)
  22275. (goto-char (match-end 0))
  22276. (forward-line))
  22277. (when (and full (not (org-at-heading-p)))
  22278. (catch 'exit
  22279. (let ((end (save-excursion (outline-next-heading) (point)))
  22280. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22281. (while (not (eobp))
  22282. (cond ((looking-at-p org-drawer-regexp)
  22283. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22284. (forward-line)
  22285. (throw 'exit t)))
  22286. ((looking-at-p re) (forward-line))
  22287. (t (throw 'exit t))))))))
  22288. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22289. "Move forward to the ARG'th subheading at same level as this one.
  22290. Stop at the first and last subheadings of a superior heading.
  22291. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22292. non-nil it will also look at invisible ones."
  22293. (interactive "p")
  22294. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22295. (if (and arg (< arg 0))
  22296. (goto-char (point-min))
  22297. (outline-next-heading))
  22298. (org-at-heading-p)
  22299. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22300. (f (if (and arg (< arg 0))
  22301. 're-search-backward
  22302. 're-search-forward))
  22303. (count (if arg (abs arg) 1))
  22304. (result (point)))
  22305. (while (and (prog1 (> count 0)
  22306. (forward-char (if (and arg (< arg 0)) -1 1)))
  22307. (funcall f org-outline-regexp-bol nil 'move))
  22308. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22309. (cond ((< l level) (setq count 0))
  22310. ((and (= l level)
  22311. (or invisible-ok
  22312. (progn
  22313. (goto-char (line-beginning-position))
  22314. (not (outline-invisible-p)))))
  22315. (setq count (1- count))
  22316. (when (eq l level)
  22317. (setq result (point)))))))
  22318. (goto-char result))
  22319. (beginning-of-line 1)))
  22320. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22321. "Move backward to the ARG'th subheading at same level as this one.
  22322. Stop at the first and last subheadings of a superior heading."
  22323. (interactive "p")
  22324. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22325. (defun org-next-visible-heading (arg)
  22326. "Move to the next visible heading.
  22327. This function wraps `outline-next-visible-heading' with
  22328. `org-with-limited-levels' in order to skip over inline tasks and
  22329. respect customization of `org-odd-levels-only'."
  22330. (interactive "p")
  22331. (org-with-limited-levels
  22332. (outline-next-visible-heading arg)))
  22333. (defun org-previous-visible-heading (arg)
  22334. "Move to the previous visible heading.
  22335. This function wraps `outline-previous-visible-heading' with
  22336. `org-with-limited-levels' in order to skip over inline tasks and
  22337. respect customization of `org-odd-levels-only'."
  22338. (interactive "p")
  22339. (org-with-limited-levels
  22340. (outline-previous-visible-heading arg)))
  22341. (defun org-next-block (arg &optional backward block-regexp)
  22342. "Jump to the next block.
  22343. With a prefix argument ARG, jump forward ARG many blocks.
  22344. When BACKWARD is non-nil, jump to the previous block.
  22345. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22346. Match data is set according to this regexp when the function
  22347. returns.
  22348. Return point at beginning of the opening line of found block.
  22349. Throw an error if no block is found."
  22350. (interactive "p")
  22351. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22352. (case-fold-search t)
  22353. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22354. (count (or arg 1))
  22355. (origin (point))
  22356. last-element)
  22357. (if backward (beginning-of-line) (end-of-line))
  22358. (while (and (> count 0) (funcall search-fn re nil t))
  22359. (let ((element (save-excursion
  22360. (goto-char (match-beginning 0))
  22361. (save-match-data (org-element-at-point)))))
  22362. (when (and (memq (org-element-type element)
  22363. '(center-block comment-block dynamic-block
  22364. example-block export-block quote-block
  22365. special-block src-block verse-block))
  22366. (<= (match-beginning 0)
  22367. (org-element-property :post-affiliated element)))
  22368. (setq last-element element)
  22369. (cl-decf count))))
  22370. (if (= count 0)
  22371. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22372. (save-match-data (org-show-context)))
  22373. (goto-char origin)
  22374. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22375. (defun org-previous-block (arg &optional block-regexp)
  22376. "Jump to the previous block.
  22377. With a prefix argument ARG, jump backward ARG many source blocks.
  22378. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22379. (interactive "p")
  22380. (org-next-block arg t block-regexp))
  22381. (defun org-forward-paragraph ()
  22382. "Move forward to beginning of next paragraph or equivalent.
  22383. The function moves point to the beginning of the next visible
  22384. structural element, which can be a paragraph, a table, a list
  22385. item, etc. It also provides some special moves for convenience:
  22386. - On an affiliated keyword, jump to the beginning of the
  22387. relative element.
  22388. - On an item or a footnote definition, move to the second
  22389. element inside, if any.
  22390. - On a table or a property drawer, jump after it.
  22391. - On a verse or source block, stop after blank lines."
  22392. (interactive)
  22393. (when (eobp) (user-error "Cannot move further down"))
  22394. (let* ((deactivate-mark nil)
  22395. (element (org-element-at-point))
  22396. (type (org-element-type element))
  22397. (post-affiliated (org-element-property :post-affiliated element))
  22398. (contents-begin (org-element-property :contents-begin element))
  22399. (contents-end (org-element-property :contents-end element))
  22400. (end (let ((end (org-element-property :end element)) (parent element))
  22401. (while (and (setq parent (org-element-property :parent parent))
  22402. (= (org-element-property :contents-end parent) end))
  22403. (setq end (org-element-property :end parent)))
  22404. end)))
  22405. (cond ((not element)
  22406. (skip-chars-forward " \r\t\n")
  22407. (or (eobp) (beginning-of-line)))
  22408. ;; On affiliated keywords, move to element's beginning.
  22409. ((< (point) post-affiliated)
  22410. (goto-char post-affiliated))
  22411. ;; At a table row, move to the end of the table. Similarly,
  22412. ;; at a node property, move to the end of the property
  22413. ;; drawer.
  22414. ((memq type '(node-property table-row))
  22415. (goto-char (org-element-property
  22416. :end (org-element-property :parent element))))
  22417. ((memq type '(property-drawer table)) (goto-char end))
  22418. ;; Consider blank lines as separators in verse and source
  22419. ;; blocks to ease editing.
  22420. ((memq type '(src-block verse-block))
  22421. (when (eq type 'src-block)
  22422. (setq contents-end
  22423. (save-excursion (goto-char end)
  22424. (skip-chars-backward " \r\t\n")
  22425. (line-beginning-position))))
  22426. (beginning-of-line)
  22427. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22428. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22429. (goto-char end)
  22430. (skip-chars-forward " \r\t\n")
  22431. (if (= (point) contents-end) (goto-char end)
  22432. (beginning-of-line))))
  22433. ;; With no contents, just skip element.
  22434. ((not contents-begin) (goto-char end))
  22435. ;; If contents are invisible, skip the element altogether.
  22436. ((outline-invisible-p (line-end-position))
  22437. (cl-case type
  22438. (headline
  22439. (org-with-limited-levels (outline-next-visible-heading 1)))
  22440. ;; At a plain list, make sure we move to the next item
  22441. ;; instead of skipping the whole list.
  22442. (plain-list (forward-char)
  22443. (org-forward-paragraph))
  22444. (otherwise (goto-char end))))
  22445. ((>= (point) contents-end) (goto-char end))
  22446. ((>= (point) contents-begin)
  22447. ;; This can only happen on paragraphs and plain lists.
  22448. (cl-case type
  22449. (paragraph (goto-char end))
  22450. ;; At a plain list, try to move to second element in
  22451. ;; first item, if possible.
  22452. (plain-list (end-of-line)
  22453. (org-forward-paragraph))))
  22454. ;; When contents start on the middle of a line (e.g. in
  22455. ;; items and footnote definitions), try to reach first
  22456. ;; element starting after current line.
  22457. ((> (line-end-position) contents-begin)
  22458. (end-of-line)
  22459. (org-forward-paragraph))
  22460. (t (goto-char contents-begin)))))
  22461. (defun org-backward-paragraph ()
  22462. "Move backward to start of previous paragraph or equivalent.
  22463. The function moves point to the beginning of the current
  22464. structural element, which can be a paragraph, a table, a list
  22465. item, etc., or to the beginning of the previous visible one if
  22466. point is already there. It also provides some special moves for
  22467. convenience:
  22468. - On an affiliated keyword, jump to the first one.
  22469. - On a table or a property drawer, move to its beginning.
  22470. - On a verse or source block, stop before blank lines."
  22471. (interactive)
  22472. (when (bobp) (user-error "Cannot move further up"))
  22473. (let* ((deactivate-mark nil)
  22474. (element (org-element-at-point))
  22475. (type (org-element-type element))
  22476. (contents-begin (org-element-property :contents-begin element))
  22477. (contents-end (org-element-property :contents-end element))
  22478. (post-affiliated (org-element-property :post-affiliated element))
  22479. (begin (org-element-property :begin element)))
  22480. (cond
  22481. ((not element) (goto-char (point-min)))
  22482. ((= (point) begin)
  22483. (backward-char)
  22484. (org-backward-paragraph))
  22485. ((<= (point) post-affiliated) (goto-char begin))
  22486. ((memq type '(node-property table-row))
  22487. (goto-char (org-element-property
  22488. :post-affiliated (org-element-property :parent element))))
  22489. ((memq type '(property-drawer table)) (goto-char begin))
  22490. ((memq type '(src-block verse-block))
  22491. (when (eq type 'src-block)
  22492. (setq contents-begin
  22493. (save-excursion (goto-char begin) (forward-line) (point))))
  22494. (if (= (point) contents-begin) (goto-char post-affiliated)
  22495. ;; Inside a verse block, see blank lines as paragraph
  22496. ;; separators.
  22497. (let ((origin (point)))
  22498. (skip-chars-backward " \r\t\n" contents-begin)
  22499. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22500. (skip-chars-forward " \r\t\n" origin)
  22501. (if (= (point) origin) (goto-char contents-begin)
  22502. (beginning-of-line))))))
  22503. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22504. ((eq type 'paragraph)
  22505. (goto-char contents-begin)
  22506. ;; When at first paragraph in an item or a footnote definition,
  22507. ;; move directly to beginning of line.
  22508. (let ((parent-contents
  22509. (org-element-property
  22510. :contents-begin (org-element-property :parent element))))
  22511. (when (and parent-contents (= parent-contents contents-begin))
  22512. (beginning-of-line))))
  22513. ;; At the end of a greater element, move to the beginning of the
  22514. ;; last element within.
  22515. ((>= (point) contents-end)
  22516. (goto-char (1- contents-end))
  22517. (org-backward-paragraph))
  22518. (t (goto-char (or post-affiliated begin))))
  22519. ;; Ensure we never leave point invisible.
  22520. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22521. (defun org-forward-element ()
  22522. "Move forward by one element.
  22523. Move to the next element at the same level, when possible."
  22524. (interactive)
  22525. (cond ((eobp) (user-error "Cannot move further down"))
  22526. ((org-with-limited-levels (org-at-heading-p))
  22527. (let ((origin (point)))
  22528. (goto-char (org-end-of-subtree nil t))
  22529. (unless (org-with-limited-levels (org-at-heading-p))
  22530. (goto-char origin)
  22531. (user-error "Cannot move further down"))))
  22532. (t
  22533. (let* ((elem (org-element-at-point))
  22534. (end (org-element-property :end elem))
  22535. (parent (org-element-property :parent elem)))
  22536. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22537. (goto-char (org-element-property :end parent)))
  22538. ((integer-or-marker-p end) (goto-char end))
  22539. (t (message "No element at point")))))))
  22540. (defun org-backward-element ()
  22541. "Move backward by one element.
  22542. Move to the previous element at the same level, when possible."
  22543. (interactive)
  22544. (cond ((bobp) (user-error "Cannot move further up"))
  22545. ((org-with-limited-levels (org-at-heading-p))
  22546. ;; At a headline, move to the previous one, if any, or stay
  22547. ;; here.
  22548. (let ((origin (point)))
  22549. (org-with-limited-levels (org-backward-heading-same-level 1))
  22550. ;; When current headline has no sibling above, move to its
  22551. ;; parent.
  22552. (when (= (point) origin)
  22553. (or (org-with-limited-levels (org-up-heading-safe))
  22554. (progn (goto-char origin)
  22555. (user-error "Cannot move further up"))))))
  22556. (t
  22557. (let* ((elem (org-element-at-point))
  22558. (beg (org-element-property :begin elem)))
  22559. (cond
  22560. ;; Move to beginning of current element if point isn't
  22561. ;; there already.
  22562. ((null beg) (message "No element at point"))
  22563. ((/= (point) beg) (goto-char beg))
  22564. (t (goto-char beg)
  22565. (skip-chars-backward " \r\t\n")
  22566. (unless (bobp)
  22567. (let ((prev (org-element-at-point)))
  22568. (goto-char (org-element-property :begin prev))
  22569. (while (and (setq prev (org-element-property :parent prev))
  22570. (<= (org-element-property :end prev) beg))
  22571. (goto-char (org-element-property :begin prev)))))))))))
  22572. (defun org-up-element ()
  22573. "Move to upper element."
  22574. (interactive)
  22575. (if (org-with-limited-levels (org-at-heading-p))
  22576. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22577. (let* ((elem (org-element-at-point))
  22578. (parent (org-element-property :parent elem)))
  22579. (if parent (goto-char (org-element-property :begin parent))
  22580. (if (org-with-limited-levels (org-before-first-heading-p))
  22581. (user-error "No surrounding element")
  22582. (org-with-limited-levels (org-back-to-heading)))))))
  22583. (defvar org-element-greater-elements)
  22584. (defun org-down-element ()
  22585. "Move to inner element."
  22586. (interactive)
  22587. (let ((element (org-element-at-point)))
  22588. (cond
  22589. ((memq (org-element-type element) '(plain-list table))
  22590. (goto-char (org-element-property :contents-begin element))
  22591. (forward-char))
  22592. ((memq (org-element-type element) org-element-greater-elements)
  22593. ;; If contents are hidden, first disclose them.
  22594. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22595. (goto-char (or (org-element-property :contents-begin element)
  22596. (user-error "No content for this element"))))
  22597. (t (user-error "No inner element")))))
  22598. (defun org-drag-element-backward ()
  22599. "Move backward element at point."
  22600. (interactive)
  22601. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22602. (let* ((elem (org-element-at-point))
  22603. (prev-elem
  22604. (save-excursion
  22605. (goto-char (org-element-property :begin elem))
  22606. (skip-chars-backward " \r\t\n")
  22607. (unless (bobp)
  22608. (let* ((beg (org-element-property :begin elem))
  22609. (prev (org-element-at-point))
  22610. (up prev))
  22611. (while (and (setq up (org-element-property :parent up))
  22612. (<= (org-element-property :end up) beg))
  22613. (setq prev up))
  22614. prev)))))
  22615. ;; Error out if no previous element or previous element is
  22616. ;; a parent of the current one.
  22617. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22618. (user-error "Cannot drag element backward")
  22619. (let ((pos (point)))
  22620. (org-element-swap-A-B prev-elem elem)
  22621. (goto-char (+ (org-element-property :begin prev-elem)
  22622. (- pos (org-element-property :begin elem)))))))))
  22623. (defun org-drag-element-forward ()
  22624. "Move forward element at point."
  22625. (interactive)
  22626. (let* ((pos (point))
  22627. (elem (org-element-at-point)))
  22628. (when (= (point-max) (org-element-property :end elem))
  22629. (user-error "Cannot drag element forward"))
  22630. (goto-char (org-element-property :end elem))
  22631. (let ((next-elem (org-element-at-point)))
  22632. (when (or (org-element-nested-p elem next-elem)
  22633. (and (eq (org-element-type next-elem) 'headline)
  22634. (not (eq (org-element-type elem) 'headline))))
  22635. (goto-char pos)
  22636. (user-error "Cannot drag element forward"))
  22637. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22638. ;; body's length (without final blanks) and by the length of
  22639. ;; blanks between ELEM and NEXT-ELEM.
  22640. (let ((size-next (- (save-excursion
  22641. (goto-char (org-element-property :end next-elem))
  22642. (skip-chars-backward " \r\t\n")
  22643. (forward-line)
  22644. ;; Small correction if buffer doesn't end
  22645. ;; with a newline character.
  22646. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22647. (org-element-property :begin next-elem)))
  22648. (size-blank (- (org-element-property :end elem)
  22649. (save-excursion
  22650. (goto-char (org-element-property :end elem))
  22651. (skip-chars-backward " \r\t\n")
  22652. (forward-line)
  22653. (point)))))
  22654. (org-element-swap-A-B elem next-elem)
  22655. (goto-char (+ pos size-next size-blank))))))
  22656. (defun org-drag-line-forward (arg)
  22657. "Drag the line at point ARG lines forward."
  22658. (interactive "p")
  22659. (dotimes (_ (abs arg))
  22660. (let ((c (current-column)))
  22661. (if (< 0 arg)
  22662. (progn
  22663. (beginning-of-line 2)
  22664. (transpose-lines 1)
  22665. (beginning-of-line 0))
  22666. (transpose-lines 1)
  22667. (beginning-of-line -1))
  22668. (org-move-to-column c))))
  22669. (defun org-drag-line-backward (arg)
  22670. "Drag the line at point ARG lines backward."
  22671. (interactive "p")
  22672. (org-drag-line-forward (- arg)))
  22673. (defun org-mark-element ()
  22674. "Put point at beginning of this element, mark at end.
  22675. Interactively, if this command is repeated or (in Transient Mark
  22676. mode) if the mark is active, it marks the next element after the
  22677. ones already marked."
  22678. (interactive)
  22679. (let (deactivate-mark)
  22680. (if (and (called-interactively-p 'any)
  22681. (or (and (eq last-command this-command) (mark t))
  22682. (and transient-mark-mode mark-active)))
  22683. (set-mark
  22684. (save-excursion
  22685. (goto-char (mark))
  22686. (goto-char (org-element-property :end (org-element-at-point)))))
  22687. (let ((element (org-element-at-point)))
  22688. (end-of-line)
  22689. (push-mark (org-element-property :end element) t t)
  22690. (goto-char (org-element-property :begin element))))))
  22691. (defun org-narrow-to-element ()
  22692. "Narrow buffer to current element."
  22693. (interactive)
  22694. (let ((elem (org-element-at-point)))
  22695. (cond
  22696. ((eq (car elem) 'headline)
  22697. (narrow-to-region
  22698. (org-element-property :begin elem)
  22699. (org-element-property :end elem)))
  22700. ((memq (car elem) org-element-greater-elements)
  22701. (narrow-to-region
  22702. (org-element-property :contents-begin elem)
  22703. (org-element-property :contents-end elem)))
  22704. (t
  22705. (narrow-to-region
  22706. (org-element-property :begin elem)
  22707. (org-element-property :end elem))))))
  22708. (defun org-transpose-element ()
  22709. "Transpose current and previous elements, keeping blank lines between.
  22710. Point is moved after both elements."
  22711. (interactive)
  22712. (org-skip-whitespace)
  22713. (let ((end (org-element-property :end (org-element-at-point))))
  22714. (org-drag-element-backward)
  22715. (goto-char end)))
  22716. (defun org-unindent-buffer ()
  22717. "Un-indent the visible part of the buffer.
  22718. Relative indentation (between items, inside blocks, etc.) isn't
  22719. modified."
  22720. (interactive)
  22721. (unless (eq major-mode 'org-mode)
  22722. (user-error "Cannot un-indent a buffer not in Org mode"))
  22723. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22724. (unindent-tree
  22725. (lambda (contents)
  22726. (dolist (element (reverse contents))
  22727. (if (memq (org-element-type element) '(headline section))
  22728. (funcall unindent-tree (org-element-contents element))
  22729. (save-excursion
  22730. (save-restriction
  22731. (narrow-to-region
  22732. (org-element-property :begin element)
  22733. (org-element-property :end element))
  22734. (org-do-remove-indentation))))))))
  22735. (funcall unindent-tree (org-element-contents parse-tree))))
  22736. (defun org-show-children (&optional level)
  22737. "Show all direct subheadings of this heading.
  22738. Prefix arg LEVEL is how many levels below the current level
  22739. should be shown. Default is enough to cause the following
  22740. heading to appear."
  22741. (interactive "p")
  22742. ;; If `orgstruct-mode' is active, use the slower version.
  22743. (if orgstruct-mode (call-interactively #'outline-show-children)
  22744. (save-excursion
  22745. (org-back-to-heading t)
  22746. (let* ((current-level (funcall outline-level))
  22747. (max-level (org-get-valid-level
  22748. current-level
  22749. (if level (prefix-numeric-value level) 1)))
  22750. (end (save-excursion (org-end-of-subtree t t)))
  22751. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22752. (past-first-child nil)
  22753. ;; Make sure to skip inlinetasks.
  22754. (re (format regexp-fmt
  22755. current-level
  22756. (cond
  22757. ((not (featurep 'org-inlinetask)) "")
  22758. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22759. 3))
  22760. (t (1- org-inlinetask-min-level))))))
  22761. ;; Display parent heading.
  22762. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22763. (forward-line)
  22764. ;; Display children. First child may be deeper than expected
  22765. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22766. ;; MAX-LEVEL accordingly.
  22767. (while (re-search-forward re end t)
  22768. (unless past-first-child
  22769. (setq re (format regexp-fmt
  22770. current-level
  22771. (max (funcall outline-level) max-level)))
  22772. (setq past-first-child t))
  22773. (outline-flag-region
  22774. (line-end-position 0) (line-end-position) nil))))))
  22775. (defun org-show-subtree ()
  22776. "Show everything after this heading at deeper levels."
  22777. (interactive)
  22778. (outline-flag-region
  22779. (point)
  22780. (save-excursion
  22781. (org-end-of-subtree t t))
  22782. nil))
  22783. (defun org-show-entry ()
  22784. "Show the body directly following this heading.
  22785. Show the heading too, if it is currently invisible."
  22786. (interactive)
  22787. (save-excursion
  22788. (ignore-errors
  22789. (org-back-to-heading t)
  22790. (outline-flag-region
  22791. (max (point-min) (1- (point)))
  22792. (save-excursion
  22793. (if (re-search-forward
  22794. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22795. (match-beginning 1)
  22796. (point-max)))
  22797. nil)
  22798. (org-cycle-hide-drawers 'children))))
  22799. (defun org-make-options-regexp (kwds &optional extra)
  22800. "Make a regular expression for keyword lines.
  22801. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22802. when non-nil, is a regexp matching keywords names."
  22803. (concat "^[ \t]*#\\+\\("
  22804. (regexp-opt kwds)
  22805. (and extra (concat (and kwds "\\|") extra))
  22806. "\\):[ \t]*\\(.*\\)"))
  22807. ;;;; Integration with and fixes for other packages
  22808. ;;; Imenu support
  22809. (defvar-local org-imenu-markers nil
  22810. "All markers currently used by Imenu.")
  22811. (defun org-imenu-new-marker (&optional pos)
  22812. "Return a new marker for use by Imenu, and remember the marker."
  22813. (let ((m (make-marker)))
  22814. (move-marker m (or pos (point)))
  22815. (push m org-imenu-markers)
  22816. m))
  22817. (defun org-imenu-get-tree ()
  22818. "Produce the index for Imenu."
  22819. (dolist (x org-imenu-markers) (move-marker x nil))
  22820. (setq org-imenu-markers nil)
  22821. (let* ((case-fold-search nil)
  22822. (n org-imenu-depth)
  22823. (re (concat "^" (org-get-limited-outline-regexp)))
  22824. (subs (make-vector (1+ n) nil))
  22825. (last-level 0)
  22826. m level head0 head)
  22827. (save-excursion
  22828. (save-restriction
  22829. (widen)
  22830. (goto-char (point-max))
  22831. (while (re-search-backward re nil t)
  22832. (setq level (org-reduced-level (funcall outline-level)))
  22833. (when (and (<= level n)
  22834. (looking-at org-complex-heading-regexp)
  22835. (setq head0 (match-string-no-properties 4)))
  22836. (setq head (org-link-display-format head0)
  22837. m (org-imenu-new-marker))
  22838. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22839. (if (>= level last-level)
  22840. (push (cons head m) (aref subs level))
  22841. (push (cons head (aref subs (1+ level))) (aref subs level))
  22842. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22843. (setq last-level level)))))
  22844. (aref subs 1)))
  22845. (eval-after-load "imenu"
  22846. '(progn
  22847. (add-hook 'imenu-after-jump-hook
  22848. (lambda ()
  22849. (when (derived-mode-p 'org-mode)
  22850. (org-show-context 'org-goto))))))
  22851. (defun org-link-display-format (s)
  22852. "Replace links in string S with their description.
  22853. If there is no description, use the link target."
  22854. (save-match-data
  22855. (replace-regexp-in-string
  22856. org-bracket-link-analytic-regexp
  22857. (lambda (m)
  22858. (if (match-end 5) (match-string 5 m)
  22859. (concat (match-string 1 m) (match-string 3 m))))
  22860. s nil t)))
  22861. (defun org-toggle-link-display ()
  22862. "Toggle the literal or descriptive display of links."
  22863. (interactive)
  22864. (if org-descriptive-links
  22865. (progn (org-remove-from-invisibility-spec '(org-link))
  22866. (org-restart-font-lock)
  22867. (setq org-descriptive-links nil))
  22868. (progn (add-to-invisibility-spec '(org-link))
  22869. (org-restart-font-lock)
  22870. (setq org-descriptive-links t))))
  22871. ;; Speedbar support
  22872. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22873. "Overlay marking the agenda restriction line in speedbar.")
  22874. (overlay-put org-speedbar-restriction-lock-overlay
  22875. 'face 'org-agenda-restriction-lock)
  22876. (overlay-put org-speedbar-restriction-lock-overlay
  22877. 'help-echo "Agendas are currently limited to this item.")
  22878. (delete-overlay org-speedbar-restriction-lock-overlay)
  22879. (defun org-speedbar-set-agenda-restriction ()
  22880. "Restrict future agenda commands to the location at point in speedbar.
  22881. To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
  22882. (interactive)
  22883. (require 'org-agenda)
  22884. (let (p m tp np dir txt)
  22885. (cond
  22886. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22887. 'org-imenu t))
  22888. (setq m (get-text-property p 'org-imenu-marker))
  22889. (with-current-buffer (marker-buffer m)
  22890. (goto-char m)
  22891. (org-agenda-set-restriction-lock 'subtree)))
  22892. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22893. 'speedbar-function 'speedbar-find-file))
  22894. (setq tp (previous-single-property-change
  22895. (1+ p) 'speedbar-function)
  22896. np (next-single-property-change
  22897. tp 'speedbar-function)
  22898. dir (speedbar-line-directory)
  22899. txt (buffer-substring-no-properties (or tp (point-min))
  22900. (or np (point-max))))
  22901. (with-current-buffer (find-file-noselect
  22902. (let ((default-directory dir))
  22903. (expand-file-name txt)))
  22904. (unless (derived-mode-p 'org-mode)
  22905. (user-error "Cannot restrict to non-Org-mode file"))
  22906. (org-agenda-set-restriction-lock 'file)))
  22907. (t (user-error "Don't know how to restrict Org-mode's agenda")))
  22908. (move-overlay org-speedbar-restriction-lock-overlay
  22909. (point-at-bol) (point-at-eol))
  22910. (setq current-prefix-arg nil)
  22911. (org-agenda-maybe-redo)))
  22912. (defvar speedbar-file-key-map)
  22913. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22914. (eval-after-load "speedbar"
  22915. '(progn
  22916. (speedbar-add-supported-extension ".org")
  22917. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22918. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22919. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22920. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22921. (add-hook 'speedbar-visiting-tag-hook
  22922. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22923. ;;; Fixes and Hacks for problems with other packages
  22924. (defun org--flyspell-object-check-p (element)
  22925. "Non-nil when Flyspell can check object at point.
  22926. ELEMENT is the element at point."
  22927. (let ((object (save-excursion
  22928. (when (looking-at-p "\\>") (backward-char))
  22929. (org-element-context element))))
  22930. (cl-case (org-element-type object)
  22931. ;; Prevent checks in links due to keybinding conflict with
  22932. ;; Flyspell.
  22933. ((code entity export-snippet inline-babel-call
  22934. inline-src-block line-break latex-fragment link macro
  22935. statistics-cookie target timestamp verbatim)
  22936. nil)
  22937. (footnote-reference
  22938. ;; Only in inline footnotes, within the definition.
  22939. (and (eq (org-element-property :type object) 'inline)
  22940. (< (save-excursion
  22941. (goto-char (org-element-property :begin object))
  22942. (search-forward ":" nil t 2))
  22943. (point))))
  22944. (otherwise t))))
  22945. (defun org-mode-flyspell-verify ()
  22946. "Function used for `flyspell-generic-check-word-predicate'."
  22947. (if (org-at-heading-p)
  22948. ;; At a headline or an inlinetask, check title only. This is
  22949. ;; faster than relying on `org-element-at-point'.
  22950. (and (save-excursion (beginning-of-line)
  22951. (and (let ((case-fold-search t))
  22952. (not (looking-at "\\*+ END[ \t]*$")))
  22953. (looking-at org-complex-heading-regexp)))
  22954. (match-beginning 4)
  22955. (>= (point) (match-beginning 4))
  22956. (or (not (match-beginning 5))
  22957. (< (point) (match-beginning 5))))
  22958. (let* ((element (org-element-at-point))
  22959. (post-affiliated (org-element-property :post-affiliated element)))
  22960. (cond
  22961. ;; Ignore checks in all affiliated keywords but captions.
  22962. ((< (point) post-affiliated)
  22963. (and (save-excursion
  22964. (beginning-of-line)
  22965. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22966. (> (point) (match-end 0))
  22967. (org--flyspell-object-check-p element)))
  22968. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22969. ((let ((log (org-log-into-drawer)))
  22970. (and log
  22971. (let ((drawer (org-element-lineage element '(drawer))))
  22972. (and drawer
  22973. (eq (compare-strings
  22974. log nil nil
  22975. (org-element-property :drawer-name drawer) nil nil t)
  22976. t)))))
  22977. nil)
  22978. (t
  22979. (cl-case (org-element-type element)
  22980. ((comment quote-section) t)
  22981. (comment-block
  22982. ;; Allow checks between block markers, not on them.
  22983. (and (> (line-beginning-position) post-affiliated)
  22984. (save-excursion
  22985. (end-of-line)
  22986. (skip-chars-forward " \r\t\n")
  22987. (< (point) (org-element-property :end element)))))
  22988. ;; Arbitrary list of keywords where checks are meaningful.
  22989. ;; Make sure point is on the value part of the element.
  22990. (keyword
  22991. (and (member (org-element-property :key element)
  22992. '("DESCRIPTION" "TITLE"))
  22993. (save-excursion
  22994. (search-backward ":" (line-beginning-position) t))))
  22995. ;; Check is globally allowed in paragraphs verse blocks and
  22996. ;; table rows (after affiliated keywords) but some objects
  22997. ;; must not be affected.
  22998. ((paragraph table-row verse-block)
  22999. (let ((cbeg (org-element-property :contents-begin element))
  23000. (cend (org-element-property :contents-end element)))
  23001. (and cbeg (>= (point) cbeg) (< (point) cend)
  23002. (org--flyspell-object-check-p element))))))))))
  23003. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  23004. (defun org-remove-flyspell-overlays-in (beg end)
  23005. "Remove flyspell overlays in region."
  23006. (and (bound-and-true-p flyspell-mode)
  23007. (fboundp 'flyspell-delete-region-overlays)
  23008. (flyspell-delete-region-overlays beg end)))
  23009. (defvar flyspell-delayed-commands)
  23010. (eval-after-load "flyspell"
  23011. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  23012. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  23013. (eval-after-load "bookmark"
  23014. '(if (boundp 'bookmark-after-jump-hook)
  23015. ;; We can use the hook
  23016. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  23017. ;; Hook not available, use advice
  23018. (defadvice bookmark-jump (after org-make-visible activate)
  23019. "Make the position visible."
  23020. (org-bookmark-jump-unhide))))
  23021. ;; Make sure saveplace shows the location if it was hidden
  23022. (eval-after-load "saveplace"
  23023. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  23024. "Make the position visible."
  23025. (org-bookmark-jump-unhide)))
  23026. ;; Make sure ecb shows the location if it was hidden
  23027. (eval-after-load "ecb"
  23028. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  23029. "Make hierarchy visible when jumping into location from ECB tree buffer."
  23030. (when (derived-mode-p 'org-mode)
  23031. (org-show-context))))
  23032. (defun org-bookmark-jump-unhide ()
  23033. "Unhide the current position, to show the bookmark location."
  23034. (and (derived-mode-p 'org-mode)
  23035. (or (outline-invisible-p)
  23036. (save-excursion (goto-char (max (point-min) (1- (point))))
  23037. (outline-invisible-p)))
  23038. (org-show-context 'bookmark-jump)))
  23039. (defun org-mark-jump-unhide ()
  23040. "Make the point visible with `org-show-context' after jumping to the mark."
  23041. (when (and (derived-mode-p 'org-mode)
  23042. (outline-invisible-p))
  23043. (org-show-context 'mark-goto)))
  23044. (eval-after-load "simple"
  23045. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23046. "Make the point visible with `org-show-context'."
  23047. (org-mark-jump-unhide)))
  23048. (eval-after-load "simple"
  23049. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23050. "Make the point visible with `org-show-context'."
  23051. (org-mark-jump-unhide)))
  23052. (eval-after-load "simple"
  23053. '(defadvice pop-global-mark (after org-make-visible activate)
  23054. "Make the point visible with `org-show-context'."
  23055. (org-mark-jump-unhide)))
  23056. ;; Make session.el ignore our circular variable
  23057. (defvar session-globals-exclude)
  23058. (eval-after-load "session"
  23059. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23060. ;;;; Finish up
  23061. (provide 'org)
  23062. (run-hooks 'org-load-hook)
  23063. ;;; org.el ends here