org.el 942 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocktable-shift "org-clock" (dir n))
  118. (declare-function
  119. org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  120. (declare-function org-element-at-point "org-element" ())
  121. (declare-function org-element-cache-refresh "org-element" (pos))
  122. (declare-function org-element-cache-reset "org-element" (&optional all))
  123. (declare-function org-element-contents "org-element" (element))
  124. (declare-function org-element-context "org-element" (&optional element))
  125. (declare-function org-element-copy "org-element" (datum))
  126. (declare-function org-element-interpret-data "org-element" (data))
  127. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  128. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  129. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  130. (declare-function org-element-property "org-element" (property element))
  131. (declare-function org-element-put-property "org-element" (element property value))
  132. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  133. (declare-function org-element-type "org-element" (element))
  134. (declare-function org-element-update-syntax "org-element" ())
  135. (declare-function org-id-find-id-file "org-id" (id))
  136. (declare-function org-id-get-create "org-id" (&optional force))
  137. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  138. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  139. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  140. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  141. (declare-function org-table-align "org-table" ())
  142. (declare-function org-table-begin "org-table" (&optional table-type))
  143. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  144. (declare-function org-table-blank-field "org-table" ())
  145. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  146. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  147. (declare-function org-table-cut-region "org-table" (beg end))
  148. (declare-function org-table-edit-field "org-table" (arg))
  149. (declare-function org-table-end "org-table" (&optional table-type))
  150. (declare-function org-table-end-of-field "org-table" (&optional n))
  151. (declare-function org-table-insert-row "org-table" (&optional arg))
  152. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  153. (declare-function org-table-maybe-eval-formula "org-table" ())
  154. (declare-function org-table-maybe-recalculate-line "org-table" ())
  155. (declare-function org-table-next-row "org-table" ())
  156. (declare-function org-table-paste-rectangle "org-table" ())
  157. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  158. (declare-function
  159. org-table-sort-lines "org-table"
  160. (&optional with-case sorting-type getkey-func compare-func interactive?))
  161. (declare-function org-table-wrap-region "org-table" (arg))
  162. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  163. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  164. (declare-function orgtbl-mode "org-table" (&optional arg))
  165. (declare-function org-export-get-backend "ox" (name))
  166. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  167. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  168. (defsubst org-uniquify (list)
  169. "Non-destructively remove duplicate elements from LIST."
  170. (let ((res (copy-sequence list))) (delete-dups res)))
  171. (defsubst org-get-at-bol (property)
  172. "Get text property PROPERTY at the beginning of line."
  173. (get-text-property (point-at-bol) property))
  174. (defsubst org-trim (s &optional keep-lead)
  175. "Remove whitespace at the beginning and the end of string S.
  176. When optional argument KEEP-LEAD is non-nil, removing blank lines
  177. at the beginning of the string does not affect leading indentation."
  178. (replace-regexp-in-string
  179. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  180. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  181. ;; load languages based on value of `org-babel-load-languages'
  182. (defvar org-babel-load-languages)
  183. ;;;###autoload
  184. (defun org-babel-do-load-languages (sym value)
  185. "Load the languages defined in `org-babel-load-languages'."
  186. (set-default sym value)
  187. (dolist (pair org-babel-load-languages)
  188. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  189. (if active
  190. (require (intern (concat "ob-" lang)))
  191. (funcall 'fmakunbound
  192. (intern (concat "org-babel-execute:" lang)))
  193. (funcall 'fmakunbound
  194. (intern (concat "org-babel-expand-body:" lang)))))))
  195. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  196. ;;;###autoload
  197. (defun org-babel-load-file (file &optional compile)
  198. "Load Emacs Lisp source code blocks in the Org FILE.
  199. This function exports the source code using `org-babel-tangle'
  200. and then loads the resulting file using `load-file'. With prefix
  201. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  202. file to byte-code before it is loaded."
  203. (interactive "fFile to load: \nP")
  204. (let* ((age (lambda (file)
  205. (float-time
  206. (time-subtract (current-time)
  207. (nth 5 (or (file-attributes (file-truename file))
  208. (file-attributes file)))))))
  209. (base-name (file-name-sans-extension file))
  210. (exported-file (concat base-name ".el")))
  211. ;; tangle if the Org file is newer than the elisp file
  212. (unless (and (file-exists-p exported-file)
  213. (> (funcall age file) (funcall age exported-file)))
  214. ;; Tangle-file traversal returns reversed list of tangled files
  215. ;; and we want to evaluate the first target.
  216. (setq exported-file
  217. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  218. (message "%s %s"
  219. (if compile
  220. (progn (byte-compile-file exported-file 'load)
  221. "Compiled and loaded")
  222. (progn (load-file exported-file) "Loaded"))
  223. exported-file)))
  224. (defcustom org-babel-load-languages '((emacs-lisp . t))
  225. "Languages which can be evaluated in Org buffers.
  226. This list can be used to load support for any of the languages
  227. below, note that each language will depend on a different set of
  228. system executables and/or Emacs modes. When a language is
  229. \"loaded\", then code blocks in that language can be evaluated
  230. with `org-babel-execute-src-block' bound by default to C-c
  231. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  232. be set to remove code block evaluation from the C-c C-c
  233. keybinding. By default only Emacs Lisp (which has no
  234. requirements) is loaded."
  235. :group 'org-babel
  236. :set 'org-babel-do-load-languages
  237. :version "24.1"
  238. :type '(alist :tag "Babel Languages"
  239. :key-type
  240. (choice
  241. (const :tag "Awk" awk)
  242. (const :tag "C" C)
  243. (const :tag "R" R)
  244. (const :tag "Asymptote" asymptote)
  245. (const :tag "Calc" calc)
  246. (const :tag "Clojure" clojure)
  247. (const :tag "CSS" css)
  248. (const :tag "Ditaa" ditaa)
  249. (const :tag "Dot" dot)
  250. (const :tag "Emacs Lisp" emacs-lisp)
  251. (const :tag "Forth" forth)
  252. (const :tag "Fortran" fortran)
  253. (const :tag "Gnuplot" gnuplot)
  254. (const :tag "Haskell" haskell)
  255. (const :tag "hledger" hledger)
  256. (const :tag "IO" io)
  257. (const :tag "J" J)
  258. (const :tag "Java" java)
  259. (const :tag "Javascript" js)
  260. (const :tag "LaTeX" latex)
  261. (const :tag "Ledger" ledger)
  262. (const :tag "Lilypond" lilypond)
  263. (const :tag "Lisp" lisp)
  264. (const :tag "Makefile" makefile)
  265. (const :tag "Maxima" maxima)
  266. (const :tag "Matlab" matlab)
  267. (const :tag "Mscgen" mscgen)
  268. (const :tag "Ocaml" ocaml)
  269. (const :tag "Octave" octave)
  270. (const :tag "Org" org)
  271. (const :tag "Perl" perl)
  272. (const :tag "Pico Lisp" picolisp)
  273. (const :tag "PlantUML" plantuml)
  274. (const :tag "Python" python)
  275. (const :tag "Ruby" ruby)
  276. (const :tag "Sass" sass)
  277. (const :tag "Scala" scala)
  278. (const :tag "Scheme" scheme)
  279. (const :tag "Screen" screen)
  280. (const :tag "Shell Script" shell)
  281. (const :tag "Shen" shen)
  282. (const :tag "Sql" sql)
  283. (const :tag "Sqlite" sqlite)
  284. (const :tag "Stan" stan)
  285. (const :tag "ebnf2ps" ebnf2ps))
  286. :value-type (boolean :tag "Activate" :value t)))
  287. ;;;; Customization variables
  288. (defcustom org-clone-delete-id nil
  289. "Remove ID property of clones of a subtree.
  290. When non-nil, clones of a subtree don't inherit the ID property.
  291. Otherwise they inherit the ID property with a new unique
  292. identifier."
  293. :type 'boolean
  294. :version "24.1"
  295. :group 'org-id)
  296. ;;; Version
  297. (org-check-version)
  298. ;;;###autoload
  299. (defun org-version (&optional here full message)
  300. "Show the Org version.
  301. Interactively, or when MESSAGE is non-nil, show it in echo area.
  302. With prefix argument, or when HERE is non-nil, insert it at point.
  303. In non-interactive uses, a reduced version string is output unless
  304. FULL is given."
  305. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  306. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  307. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  308. (load-suffixes (list ".el"))
  309. (org-install-dir
  310. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  311. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  312. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  313. (let* ((load-suffixes save-load-suffixes)
  314. (release (org-release))
  315. (git-version (org-git-version))
  316. (version (format "Org mode version %s (%s @ %s)"
  317. release
  318. git-version
  319. (if org-install-dir
  320. (if (string= org-dir org-install-dir)
  321. org-install-dir
  322. (concat "mixed installation! "
  323. org-install-dir
  324. " and "
  325. org-dir))
  326. "org-loaddefs.el can not be found!")))
  327. (version1 (if full version release)))
  328. (when here (insert version1))
  329. (when message (message "%s" version1))
  330. version1)))
  331. (defconst org-version (org-version))
  332. ;;; Syntax Constants
  333. ;;;; Block
  334. (defconst org-block-regexp
  335. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  336. "Regular expression for hiding blocks.")
  337. (defconst org-dblock-start-re
  338. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  339. "Matches the start line of a dynamic block, with parameters.")
  340. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  341. "Matches the end of a dynamic block.")
  342. ;;;; Clock and Planning
  343. (defconst org-clock-string "CLOCK:"
  344. "String used as prefix for timestamps clocking work hours on an item.")
  345. (defvar org-closed-string "CLOSED:"
  346. "String used as the prefix for timestamps logging closing a TODO entry.")
  347. (defvar org-deadline-string "DEADLINE:"
  348. "String to mark deadline entries.
  349. \\<org-mode-map>
  350. A deadline is this string, followed by a time stamp. It must be
  351. a word, terminated by a colon. You can insert a schedule keyword
  352. and a timestamp with `\\[org-deadline]'.")
  353. (defvar org-scheduled-string "SCHEDULED:"
  354. "String to mark scheduled TODO entries.
  355. \\<org-mode-map>
  356. A schedule is this string, followed by a time stamp. It must be
  357. a word, terminated by a colon. You can insert a schedule keyword
  358. and a timestamp with `\\[org-schedule]'.")
  359. (defconst org-ds-keyword-length
  360. (+ 2
  361. (apply #'max
  362. (mapcar #'length
  363. (list org-deadline-string org-scheduled-string
  364. org-clock-string org-closed-string))))
  365. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  366. (defconst org-planning-line-re
  367. (concat "^[ \t]*"
  368. (regexp-opt
  369. (list org-closed-string org-deadline-string org-scheduled-string)
  370. t))
  371. "Matches a line with planning info.
  372. Matched keyword is in group 1.")
  373. (defconst org-clock-line-re
  374. (concat "^[ \t]*" org-clock-string)
  375. "Matches a line with clock info.")
  376. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  377. "Matches the DEADLINE keyword.")
  378. (defconst org-deadline-time-regexp
  379. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  380. "Matches the DEADLINE keyword together with a time stamp.")
  381. (defconst org-deadline-time-hour-regexp
  382. (concat "\\<" org-deadline-string
  383. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  384. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  385. (defconst org-deadline-line-regexp
  386. (concat "\\<\\(" org-deadline-string "\\).*")
  387. "Matches the DEADLINE keyword and the rest of the line.")
  388. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  389. "Matches the SCHEDULED keyword.")
  390. (defconst org-scheduled-time-regexp
  391. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  392. "Matches the SCHEDULED keyword together with a time stamp.")
  393. (defconst org-scheduled-time-hour-regexp
  394. (concat "\\<" org-scheduled-string
  395. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  396. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  397. (defconst org-closed-time-regexp
  398. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  399. "Matches the CLOSED keyword together with a time stamp.")
  400. (defconst org-keyword-time-regexp
  401. (concat "\\<"
  402. (regexp-opt
  403. (list org-scheduled-string org-deadline-string org-closed-string
  404. org-clock-string)
  405. t)
  406. " *[[<]\\([^]>]+\\)[]>]")
  407. "Matches any of the 4 keywords, together with the time stamp.")
  408. (defconst org-keyword-time-not-clock-regexp
  409. (concat
  410. "\\<"
  411. (regexp-opt
  412. (list org-scheduled-string org-deadline-string org-closed-string) t)
  413. " *[[<]\\([^]>]+\\)[]>]")
  414. "Matches any of the 3 keywords, together with the time stamp.")
  415. (defconst org-maybe-keyword-time-regexp
  416. (concat "\\(\\<"
  417. (regexp-opt
  418. (list org-scheduled-string org-deadline-string org-closed-string
  419. org-clock-string)
  420. t)
  421. "\\)?"
  422. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  423. "\\|"
  424. "<%%([^\r\n>]*>\\)")
  425. "Matches a timestamp, possibly preceded by a keyword.")
  426. (defconst org-all-time-keywords
  427. (mapcar (lambda (w) (substring w 0 -1))
  428. (list org-scheduled-string org-deadline-string
  429. org-clock-string org-closed-string))
  430. "List of time keywords.")
  431. ;;;; Drawer
  432. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  433. "Matches first or last line of a hidden block.
  434. Group 1 contains drawer's name or \"END\".")
  435. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  436. "Regular expression matching the first line of a property drawer.")
  437. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  438. "Regular expression matching the last line of a property drawer.")
  439. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  440. "Regular expression matching the first line of a clock drawer.")
  441. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  442. "Regular expression matching the last line of a clock drawer.")
  443. (defconst org-property-drawer-re
  444. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  445. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  446. "[ \t]*:END:[ \t]*$")
  447. "Matches an entire property drawer.")
  448. (defconst org-clock-drawer-re
  449. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  450. org-clock-drawer-end-re "\\)\n?")
  451. "Matches an entire clock drawer.")
  452. ;;;; Headline
  453. (defconst org-heading-keyword-regexp-format
  454. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  455. "Printf format for a regexp matching a headline with some keyword.
  456. This regexp will match the headline of any node which has the
  457. exact keyword that is put into the format. The keyword isn't in
  458. any group by default, but the stars and the body are.")
  459. (defconst org-heading-keyword-maybe-regexp-format
  460. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  461. "Printf format for a regexp matching a headline, possibly with some keyword.
  462. This regexp can match any headline with the specified keyword, or
  463. without a keyword. The keyword isn't in any group by default,
  464. but the stars and the body are.")
  465. (defconst org-archive-tag "ARCHIVE"
  466. "The tag that marks a subtree as archived.
  467. An archived subtree does not open during visibility cycling, and does
  468. not contribute to the agenda listings.")
  469. (eval-and-compile
  470. (defconst org-comment-string "COMMENT"
  471. "Entries starting with this keyword will never be exported.
  472. \\<org-mode-map>
  473. An entry can be toggled between COMMENT and normal with
  474. `\\[org-toggle-comment]'."))
  475. ;;;; LaTeX Environments and Fragments
  476. (defconst org-latex-regexps
  477. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  478. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  479. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  480. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  481. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  482. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  483. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  484. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  485. "Regular expressions for matching embedded LaTeX.")
  486. ;;;; Node Property
  487. (defconst org-effort-property "Effort"
  488. "The property that is being used to keep track of effort estimates.
  489. Effort estimates given in this property need to have the format H:MM.")
  490. ;;;; Table
  491. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  492. "Detect an org-type or table-type table.")
  493. (defconst org-table-line-regexp "^[ \t]*|"
  494. "Detect an org-type table line.")
  495. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  496. "Detect an org-type table line.")
  497. (defconst org-table-hline-regexp "^[ \t]*|-"
  498. "Detect an org-type table hline.")
  499. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  500. "Detect a table-type table hline.")
  501. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  502. "Detect the first line outside a table when searching from within it.
  503. This works for both table types.")
  504. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  505. "Detect a #+TBLFM line.")
  506. ;;;; Timestamp
  507. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  508. "Regular expression for fast time stamp matching.")
  509. (defconst org-ts-regexp-inactive
  510. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  511. "Regular expression for fast inactive time stamp matching.")
  512. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  513. "Regular expression for fast time stamp matching.")
  514. (defconst org-ts-regexp0
  515. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  516. "Regular expression matching time strings for analysis.
  517. This one does not require the space after the date, so it can be used
  518. on a string that terminates immediately after the date.")
  519. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  520. "Regular expression matching time strings for analysis.")
  521. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  522. "Regular expression matching time stamps, with groups.")
  523. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  524. "Regular expression matching time stamps (also [..]), with groups.")
  525. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  526. "Regular expression matching a time stamp range.")
  527. (defconst org-tr-regexp-both
  528. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  529. "Regular expression matching a time stamp range.")
  530. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  531. org-ts-regexp "\\)?")
  532. "Regular expression matching a time stamp or time stamp range.")
  533. (defconst org-tsr-regexp-both
  534. (concat org-ts-regexp-both "\\(--?-?"
  535. org-ts-regexp-both "\\)?")
  536. "Regular expression matching a time stamp or time stamp range.
  537. The time stamps may be either active or inactive.")
  538. (defconst org-repeat-re
  539. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  540. "Regular expression for specifying repeated events.
  541. After a match, group 1 contains the repeat expression.")
  542. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  543. "Formats for `format-time-string' which are used for time stamps.")
  544. ;;; The custom variables
  545. (defgroup org nil
  546. "Outline-based notes management and organizer."
  547. :tag "Org"
  548. :group 'outlines
  549. :group 'calendar)
  550. (defcustom org-mode-hook nil
  551. "Mode hook for Org mode, run after the mode was turned on."
  552. :group 'org
  553. :type 'hook)
  554. (defcustom org-load-hook nil
  555. "Hook that is run after org.el has been loaded."
  556. :group 'org
  557. :type 'hook)
  558. (defcustom org-log-buffer-setup-hook nil
  559. "Hook that is run after an Org log buffer is created."
  560. :group 'org
  561. :version "24.1"
  562. :type 'hook)
  563. (defvar org-modules) ; defined below
  564. (defvar org-modules-loaded nil
  565. "Have the modules been loaded already?")
  566. (defun org-load-modules-maybe (&optional force)
  567. "Load all extensions listed in `org-modules'."
  568. (when (or force (not org-modules-loaded))
  569. (dolist (ext org-modules)
  570. (condition-case nil (require ext)
  571. (error (message "Problems while trying to load feature `%s'" ext))))
  572. (setq org-modules-loaded t)))
  573. (defun org-set-modules (var value)
  574. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  575. (set var value)
  576. (when (featurep 'org)
  577. (org-load-modules-maybe 'force)
  578. (org-element-cache-reset 'all)))
  579. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  580. "Modules that should always be loaded together with org.el.
  581. If a description starts with <C>, the file is not part of Emacs
  582. and loading it will require that you have downloaded and properly
  583. installed the Org mode distribution.
  584. You can also use this system to load external packages (i.e. neither Org
  585. core modules, nor modules from the CONTRIB directory). Just add symbols
  586. to the end of the list. If the package is called org-xyz.el, then you need
  587. to add the symbol `xyz', and the package must have a call to:
  588. (provide \\='org-xyz)
  589. For export specific modules, see also `org-export-backends'."
  590. :group 'org
  591. :set 'org-set-modules
  592. :version "24.4"
  593. :package-version '(Org . "8.0")
  594. :type
  595. '(set :greedy t
  596. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  597. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  598. (const :tag " crypt: Encryption of subtrees" org-crypt)
  599. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  600. (const :tag " docview: Links to doc-view buffers" org-docview)
  601. (const :tag " eww: Store link to url of eww" org-eww)
  602. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  603. (const :tag " habit: Track your consistency with habits" org-habit)
  604. (const :tag " id: Global IDs for identifying entries" org-id)
  605. (const :tag " info: Links to Info nodes" org-info)
  606. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  607. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  608. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  609. (const :tag " mouse: Additional mouse support" org-mouse)
  610. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  611. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  612. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  613. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  614. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  615. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  616. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  617. (const :tag "C collector: Collect properties into tables" org-collector)
  618. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  619. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  620. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  621. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  622. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  623. (const :tag "C eval: Include command output as text" org-eval)
  624. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  625. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  626. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  627. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  628. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  629. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  630. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  631. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  632. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  633. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  634. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  635. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  636. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  637. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  638. (const :tag "C registry: A registry for Org links" org-registry)
  639. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  640. (const :tag "C secretary: Team management with org-mode" org-secretary)
  641. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  642. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  643. (const :tag "C track: Keep up with Org mode development" org-track)
  644. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  645. (const :tag "C vm: Links to VM folders/messages" org-vm)
  646. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  647. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  648. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  649. (defvar org-export-registered-backends) ; From ox.el.
  650. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  651. (declare-function org-export-backend-name "ox" (backend) t)
  652. (defcustom org-export-backends '(ascii html icalendar latex odt)
  653. "List of export back-ends that should be always available.
  654. If a description starts with <C>, the file is not part of Emacs
  655. and loading it will require that you have downloaded and properly
  656. installed the Org mode distribution.
  657. Unlike to `org-modules', libraries in this list will not be
  658. loaded along with Org, but only once the export framework is
  659. needed.
  660. This variable needs to be set before org.el is loaded. If you
  661. need to make a change while Emacs is running, use the customize
  662. interface or run the following code, where VAL stands for the new
  663. value of the variable, after updating it:
  664. (progn
  665. (setq org-export-registered-backends
  666. (cl-remove-if-not
  667. (lambda (backend)
  668. (let ((name (org-export-backend-name backend)))
  669. (or (memq name val)
  670. (catch \\='parentp
  671. (dolist (b val)
  672. (and (org-export-derived-backend-p b name)
  673. (throw \\='parentp t)))))))
  674. org-export-registered-backends))
  675. (let ((new-list (mapcar #\\='org-export-backend-name
  676. org-export-registered-backends)))
  677. (dolist (backend val)
  678. (cond
  679. ((not (load (format \"ox-%s\" backend) t t))
  680. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  681. backend))
  682. ((not (memq backend new-list)) (push backend new-list))))
  683. (set-default \\='org-export-backends new-list)))
  684. Adding a back-end to this list will also pull the back-end it
  685. depends on, if any."
  686. :group 'org
  687. :group 'org-export
  688. :version "26.1"
  689. :package-version '(Org . "9.0")
  690. :initialize 'custom-initialize-set
  691. :set (lambda (var val)
  692. (if (not (featurep 'ox)) (set-default var val)
  693. ;; Any back-end not required anymore (not present in VAL and not
  694. ;; a parent of any back-end in the new value) is removed from the
  695. ;; list of registered back-ends.
  696. (setq org-export-registered-backends
  697. (cl-remove-if-not
  698. (lambda (backend)
  699. (let ((name (org-export-backend-name backend)))
  700. (or (memq name val)
  701. (catch 'parentp
  702. (dolist (b val)
  703. (and (org-export-derived-backend-p b name)
  704. (throw 'parentp t)))))))
  705. org-export-registered-backends))
  706. ;; Now build NEW-LIST of both new back-ends and required
  707. ;; parents.
  708. (let ((new-list (mapcar #'org-export-backend-name
  709. org-export-registered-backends)))
  710. (dolist (backend val)
  711. (cond
  712. ((not (load (format "ox-%s" backend) t t))
  713. (message "Problems while trying to load export back-end `%s'"
  714. backend))
  715. ((not (memq backend new-list)) (push backend new-list))))
  716. ;; Set VAR to that list with fixed dependencies.
  717. (set-default var new-list))))
  718. :type '(set :greedy t
  719. (const :tag " ascii Export buffer to ASCII format" ascii)
  720. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  721. (const :tag " html Export buffer to HTML format" html)
  722. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  723. (const :tag " latex Export buffer to LaTeX format" latex)
  724. (const :tag " man Export buffer to MAN format" man)
  725. (const :tag " md Export buffer to Markdown format" md)
  726. (const :tag " odt Export buffer to ODT format" odt)
  727. (const :tag " org Export buffer to Org format" org)
  728. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  729. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  730. (const :tag "C deck Export buffer to deck.js presentations" deck)
  731. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  732. (const :tag "C groff Export buffer to Groff format" groff)
  733. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  734. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  735. (const :tag "C s5 Export buffer to s5 presentations" s5)
  736. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  737. (eval-after-load 'ox
  738. '(dolist (backend org-export-backends)
  739. (condition-case nil (require (intern (format "ox-%s" backend)))
  740. (error (message "Problems while trying to load export back-end `%s'"
  741. backend)))))
  742. (defcustom org-support-shift-select nil
  743. "Non-nil means make shift-cursor commands select text when possible.
  744. \\<org-mode-map>\
  745. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  746. start selecting a region, or enlarge regions started in this way.
  747. In Org mode, in special contexts, these same keys are used for
  748. other purposes, important enough to compete with shift selection.
  749. Org tries to balance these needs by supporting `shift-select-mode'
  750. outside these special contexts, under control of this variable.
  751. The default of this variable is nil, to avoid confusing behavior. Shifted
  752. cursor keys will then execute Org commands in the following contexts:
  753. - on a headline, changing TODO state (left/right) and priority (up/down)
  754. - on a time stamp, changing the time
  755. - in a plain list item, changing the bullet type
  756. - in a property definition line, switching between allowed values
  757. - in the BEGIN line of a clock table (changing the time block).
  758. Outside these contexts, the commands will throw an error.
  759. When this variable is t and the cursor is not in a special
  760. context, Org mode will support shift-selection for making and
  761. enlarging regions. To make this more effective, the bullet
  762. cycling will no longer happen anywhere in an item line, but only
  763. if the cursor is exactly on the bullet.
  764. If you set this variable to the symbol `always', then the keys
  765. will not be special in headlines, property lines, and item lines,
  766. to make shift selection work there as well. If this is what you
  767. want, you can use the following alternative commands:
  768. `\\[org-todo]' and `\\[org-priority]' \
  769. to change TODO state and priority,
  770. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  771. can be used to switch TODO sets,
  772. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  773. and properties can be edited by hand or in column view.
  774. However, when the cursor is on a timestamp, shift-cursor commands
  775. will still edit the time stamp - this is just too good to give up."
  776. :group 'org
  777. :type '(choice
  778. (const :tag "Never" nil)
  779. (const :tag "When outside special context" t)
  780. (const :tag "Everywhere except timestamps" always)))
  781. (defcustom org-loop-over-headlines-in-active-region nil
  782. "Shall some commands act upon headlines in the active region?
  783. When set to t, some commands will be performed in all headlines
  784. within the active region.
  785. When set to `start-level', some commands will be performed in all
  786. headlines within the active region, provided that these headlines
  787. are of the same level than the first one.
  788. When set to a string, those commands will be performed on the
  789. matching headlines within the active region. Such string must be
  790. a tags/property/todo match as it is used in the agenda tags view.
  791. The list of commands is: `org-schedule', `org-deadline',
  792. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  793. `org-archive-to-archive-sibling'. The archiving commands skip
  794. already archived entries."
  795. :type '(choice (const :tag "Don't loop" nil)
  796. (const :tag "All headlines in active region" t)
  797. (const :tag "In active region, headlines at the same level than the first one" start-level)
  798. (string :tag "Tags/Property/Todo matcher"))
  799. :version "24.1"
  800. :group 'org-todo
  801. :group 'org-archive)
  802. (defgroup org-startup nil
  803. "Options concerning startup of Org mode."
  804. :tag "Org Startup"
  805. :group 'org)
  806. (defcustom org-startup-folded t
  807. "Non-nil means entering Org mode will switch to OVERVIEW.
  808. This can also be configured on a per-file basis by adding one of
  809. the following lines anywhere in the buffer:
  810. #+STARTUP: fold (or `overview', this is equivalent)
  811. #+STARTUP: nofold (or `showall', this is equivalent)
  812. #+STARTUP: content
  813. #+STARTUP: showeverything
  814. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  815. to ignore this option when Org opens agenda files for the first
  816. time."
  817. :group 'org-startup
  818. :type '(choice
  819. (const :tag "nofold: show all" nil)
  820. (const :tag "fold: overview" t)
  821. (const :tag "content: all headlines" content)
  822. (const :tag "show everything, even drawers" showeverything)))
  823. (defcustom org-startup-truncated t
  824. "Non-nil means entering Org mode will set `truncate-lines'.
  825. This is useful since some lines containing links can be very long and
  826. uninteresting. Also tables look terrible when wrapped.
  827. The variable `org-startup-truncated' allows to configure
  828. truncation for Org mode different to the other modes that use the
  829. variable `truncate-lines' and as a shortcut instead of putting
  830. the variable `truncate-lines' into the `org-mode-hook'. If one
  831. wants to configure truncation for Org mode not statically but
  832. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  833. the variable `truncate-lines' has to be used because in such a
  834. case it is too late to set the variable `org-startup-truncated'."
  835. :group 'org-startup
  836. :type 'boolean)
  837. (defcustom org-startup-indented nil
  838. "Non-nil means turn on `org-indent-mode' on startup.
  839. This can also be configured on a per-file basis by adding one of
  840. the following lines anywhere in the buffer:
  841. #+STARTUP: indent
  842. #+STARTUP: noindent"
  843. :group 'org-structure
  844. :type '(choice
  845. (const :tag "Not" nil)
  846. (const :tag "Globally (slow on startup in large files)" t)))
  847. (defcustom org-use-sub-superscripts t
  848. "Non-nil means interpret \"_\" and \"^\" for display.
  849. If you want to control how Org exports those characters, see
  850. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  851. used to be an alias for `org-export-with-sub-superscripts' in
  852. Org <8.0, it is not anymore.
  853. When this option is turned on, you can use TeX-like syntax for
  854. sub- and superscripts within the buffer. Several characters after
  855. \"_\" or \"^\" will be considered as a single item - so grouping
  856. with {} is normally not needed. For example, the following things
  857. will be parsed as single sub- or superscripts:
  858. 10^24 or 10^tau several digits will be considered 1 item.
  859. 10^-12 or 10^-tau a leading sign with digits or a word
  860. x^2-y^3 will be read as x^2 - y^3, because items are
  861. terminated by almost any nonword/nondigit char.
  862. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  863. Still, ambiguity is possible. So when in doubt, use {} to enclose
  864. the sub/superscript. If you set this variable to the symbol `{}',
  865. the braces are *required* in order to trigger interpretations as
  866. sub/superscript. This can be helpful in documents that need \"_\"
  867. frequently in plain text."
  868. :group 'org-startup
  869. :version "24.4"
  870. :package-version '(Org . "8.0")
  871. :type '(choice
  872. (const :tag "Always interpret" t)
  873. (const :tag "Only with braces" {})
  874. (const :tag "Never interpret" nil)))
  875. (defcustom org-startup-with-beamer-mode nil
  876. "Non-nil means turn on `org-beamer-mode' on startup.
  877. This can also be configured on a per-file basis by adding one of
  878. the following lines anywhere in the buffer:
  879. #+STARTUP: beamer"
  880. :group 'org-startup
  881. :version "24.1"
  882. :type 'boolean)
  883. (defcustom org-startup-align-all-tables nil
  884. "Non-nil means align all tables when visiting a file.
  885. This is useful when the column width in tables is forced with <N> cookies
  886. in table fields. Such tables will look correct only after the first re-align.
  887. This can also be configured on a per-file basis by adding one of
  888. the following lines anywhere in the buffer:
  889. #+STARTUP: align
  890. #+STARTUP: noalign"
  891. :group 'org-startup
  892. :type 'boolean)
  893. (defcustom org-startup-with-inline-images nil
  894. "Non-nil means show inline images when loading a new Org file.
  895. This can also be configured on a per-file basis by adding one of
  896. the following lines anywhere in the buffer:
  897. #+STARTUP: inlineimages
  898. #+STARTUP: noinlineimages"
  899. :group 'org-startup
  900. :version "24.1"
  901. :type 'boolean)
  902. (defcustom org-startup-with-latex-preview nil
  903. "Non-nil means preview LaTeX fragments when loading a new Org file.
  904. This can also be configured on a per-file basis by adding one of
  905. the following lines anywhere in the buffer:
  906. #+STARTUP: latexpreview
  907. #+STARTUP: nolatexpreview"
  908. :group 'org-startup
  909. :version "24.4"
  910. :package-version '(Org . "8.0")
  911. :type 'boolean)
  912. (defcustom org-insert-mode-line-in-empty-file nil
  913. "Non-nil means insert the first line setting Org mode in empty files.
  914. When the function `org-mode' is called interactively in an empty file, this
  915. normally means that the file name does not automatically trigger Org mode.
  916. To ensure that the file will always be in Org mode in the future, a
  917. line enforcing Org mode will be inserted into the buffer, if this option
  918. has been set."
  919. :group 'org-startup
  920. :type 'boolean)
  921. (defcustom org-replace-disputed-keys nil
  922. "Non-nil means use alternative key bindings for some keys.
  923. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  924. These keys are also used by other packages like shift-selection-mode'
  925. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  926. If you want to use Org mode together with one of these other modes,
  927. or more generally if you would like to move some Org mode commands to
  928. other keys, set this variable and configure the keys with the variable
  929. `org-disputed-keys'.
  930. This option is only relevant at load-time of Org mode, and must be set
  931. *before* org.el is loaded. Changing it requires a restart of Emacs to
  932. become effective."
  933. :group 'org-startup
  934. :type 'boolean)
  935. (defcustom org-use-extra-keys nil
  936. "Non-nil means use extra key sequence definitions for certain commands.
  937. This happens automatically if `window-system' is nil. This
  938. variable lets you do the same manually. You must set it before
  939. loading Org."
  940. :group 'org-startup
  941. :type 'boolean)
  942. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  943. (defcustom org-disputed-keys
  944. '(([(shift up)] . [(meta p)])
  945. ([(shift down)] . [(meta n)])
  946. ([(shift left)] . [(meta -)])
  947. ([(shift right)] . [(meta +)])
  948. ([(control shift right)] . [(meta shift +)])
  949. ([(control shift left)] . [(meta shift -)]))
  950. "Keys for which Org mode and other modes compete.
  951. This is an alist, cars are the default keys, second element specifies
  952. the alternative to use when `org-replace-disputed-keys' is t.
  953. Keys can be specified in any syntax supported by `define-key'.
  954. The value of this option takes effect only at Org mode startup,
  955. therefore you'll have to restart Emacs to apply it after changing."
  956. :group 'org-startup
  957. :type 'alist)
  958. (defun org-key (key)
  959. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  960. Or return the original if not disputed."
  961. (when org-replace-disputed-keys
  962. (let* ((nkey (key-description key))
  963. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  964. org-disputed-keys)))
  965. (setq key (if x (cdr x) key))))
  966. key)
  967. (defun org-defkey (keymap key def)
  968. "Define a key, possibly translated, as returned by `org-key'."
  969. (define-key keymap (org-key key) def))
  970. (defcustom org-ellipsis nil
  971. "The ellipsis to use in the Org mode outline.
  972. When nil, just use the standard three dots.
  973. When a string, use that string instead.
  974. The change affects only Org mode (which will then use its own display table).
  975. Changing this requires executing `\\[org-mode]' in a buffer to become
  976. effective."
  977. :group 'org-startup
  978. :type '(choice (const :tag "Default" nil)
  979. (string :tag "String" :value "...#"))
  980. :safe #'string-or-null-p)
  981. (defvar org-display-table nil
  982. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  983. (defgroup org-keywords nil
  984. "Keywords in Org mode."
  985. :tag "Org Keywords"
  986. :group 'org)
  987. (defcustom org-closed-keep-when-no-todo nil
  988. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  989. :group 'org-todo
  990. :group 'org-keywords
  991. :version "24.4"
  992. :package-version '(Org . "8.0")
  993. :type 'boolean)
  994. (defgroup org-structure nil
  995. "Options concerning the general structure of Org files."
  996. :tag "Org Structure"
  997. :group 'org)
  998. (defgroup org-reveal-location nil
  999. "Options about how to make context of a location visible."
  1000. :tag "Org Reveal Location"
  1001. :group 'org-structure)
  1002. (defcustom org-show-context-detail '((agenda . local)
  1003. (bookmark-jump . lineage)
  1004. (isearch . lineage)
  1005. (default . ancestors))
  1006. "Alist between context and visibility span when revealing a location.
  1007. \\<org-mode-map>Some actions may move point into invisible
  1008. locations. As a consequence, Org always expose a neighborhood
  1009. around point. How much is shown depends on the initial action,
  1010. or context. Valid contexts are
  1011. agenda when exposing an entry from the agenda
  1012. org-goto when using the command `org-goto' (`\\[org-goto]')
  1013. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1014. tags-tree when constructing a sparse tree based on tags matches
  1015. link-search when exposing search matches associated with a link
  1016. mark-goto when exposing the jump goal of a mark
  1017. bookmark-jump when exposing a bookmark location
  1018. isearch when exiting from an incremental search
  1019. default default for all contexts not set explicitly
  1020. Allowed visibility spans are
  1021. minimal show current headline; if point is not on headline,
  1022. also show entry
  1023. local show current headline, entry and next headline
  1024. ancestors show current headline and its direct ancestors; if
  1025. point is not on headline, also show entry
  1026. lineage show current headline, its direct ancestors and all
  1027. their children; if point is not on headline, also show
  1028. entry and first child
  1029. tree show current headline, its direct ancestors and all
  1030. their children; if point is not on headline, also show
  1031. entry and all children
  1032. canonical show current headline, its direct ancestors along with
  1033. their entries and children; if point is not located on
  1034. the headline, also show current entry and all children
  1035. As special cases, a nil or t value means show all contexts in
  1036. `minimal' or `canonical' view, respectively.
  1037. Some views can make displayed information very compact, but also
  1038. make it harder to edit the location of the match. In such
  1039. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1040. more context."
  1041. :group 'org-reveal-location
  1042. :version "26.1"
  1043. :package-version '(Org . "9.0")
  1044. :type '(choice
  1045. (const :tag "Canonical" t)
  1046. (const :tag "Minimal" nil)
  1047. (repeat :greedy t :tag "Individual contexts"
  1048. (cons
  1049. (choice :tag "Context"
  1050. (const agenda)
  1051. (const org-goto)
  1052. (const occur-tree)
  1053. (const tags-tree)
  1054. (const link-search)
  1055. (const mark-goto)
  1056. (const bookmark-jump)
  1057. (const isearch)
  1058. (const default))
  1059. (choice :tag "Detail level"
  1060. (const minimal)
  1061. (const local)
  1062. (const ancestors)
  1063. (const lineage)
  1064. (const tree)
  1065. (const canonical))))))
  1066. (defcustom org-indirect-buffer-display 'other-window
  1067. "How should indirect tree buffers be displayed?
  1068. This applies to indirect buffers created with the commands
  1069. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1070. Valid values are:
  1071. current-window Display in the current window
  1072. other-window Just display in another window.
  1073. dedicated-frame Create one new frame, and re-use it each time.
  1074. new-frame Make a new frame each time. Note that in this case
  1075. previously-made indirect buffers are kept, and you need to
  1076. kill these buffers yourself."
  1077. :group 'org-structure
  1078. :group 'org-agenda-windows
  1079. :type '(choice
  1080. (const :tag "In current window" current-window)
  1081. (const :tag "In current frame, other window" other-window)
  1082. (const :tag "Each time a new frame" new-frame)
  1083. (const :tag "One dedicated frame" dedicated-frame)))
  1084. (defcustom org-use-speed-commands nil
  1085. "Non-nil means activate single letter commands at beginning of a headline.
  1086. This may also be a function to test for appropriate locations where speed
  1087. commands should be active.
  1088. For example, to activate speed commands when the point is on any
  1089. star at the beginning of the headline, you can do this:
  1090. (setq org-use-speed-commands
  1091. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1092. :group 'org-structure
  1093. :type '(choice
  1094. (const :tag "Never" nil)
  1095. (const :tag "At beginning of headline stars" t)
  1096. (function)))
  1097. (defcustom org-speed-commands-user nil
  1098. "Alist of additional speed commands.
  1099. This list will be checked before `org-speed-commands-default'
  1100. when the variable `org-use-speed-commands' is non-nil
  1101. and when the cursor is at the beginning of a headline.
  1102. The car if each entry is a string with a single letter, which must
  1103. be assigned to `self-insert-command' in the global map.
  1104. The cdr is either a command to be called interactively, a function
  1105. to be called, or a form to be evaluated.
  1106. An entry that is just a list with a single string will be interpreted
  1107. as a descriptive headline that will be added when listing the speed
  1108. commands in the Help buffer using the `?' speed command."
  1109. :group 'org-structure
  1110. :type '(repeat :value ("k" . ignore)
  1111. (choice :value ("k" . ignore)
  1112. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1113. (cons :tag "Letter and Command"
  1114. (string :tag "Command letter")
  1115. (choice
  1116. (function)
  1117. (sexp))))))
  1118. (defcustom org-bookmark-names-plist
  1119. '(:last-capture "org-capture-last-stored"
  1120. :last-refile "org-refile-last-stored"
  1121. :last-capture-marker "org-capture-last-stored-marker")
  1122. "Names for bookmarks automatically set by some Org commands.
  1123. This can provide strings as names for a number of bookmarks Org sets
  1124. automatically. The following keys are currently implemented:
  1125. :last-capture
  1126. :last-capture-marker
  1127. :last-refile
  1128. When a key does not show up in the property list, the corresponding bookmark
  1129. is not set."
  1130. :group 'org-structure
  1131. :type 'plist)
  1132. (defgroup org-cycle nil
  1133. "Options concerning visibility cycling in Org mode."
  1134. :tag "Org Cycle"
  1135. :group 'org-structure)
  1136. (defcustom org-cycle-skip-children-state-if-no-children t
  1137. "Non-nil means skip CHILDREN state in entries that don't have any."
  1138. :group 'org-cycle
  1139. :type 'boolean)
  1140. (defcustom org-cycle-max-level nil
  1141. "Maximum level which should still be subject to visibility cycling.
  1142. Levels higher than this will, for cycling, be treated as text, not a headline.
  1143. When `org-odd-levels-only' is set, a value of N in this variable actually
  1144. means 2N-1 stars as the limiting headline.
  1145. When nil, cycle all levels.
  1146. Note that the limiting level of cycling is also influenced by
  1147. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1148. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1149. than its value."
  1150. :group 'org-cycle
  1151. :type '(choice
  1152. (const :tag "No limit" nil)
  1153. (integer :tag "Maximum level")))
  1154. (defcustom org-hide-block-startup nil
  1155. "Non-nil means entering Org mode will fold all blocks.
  1156. This can also be set in on a per-file basis with
  1157. #+STARTUP: hideblocks
  1158. #+STARTUP: showblocks"
  1159. :group 'org-startup
  1160. :group 'org-cycle
  1161. :type 'boolean)
  1162. (defcustom org-cycle-global-at-bob nil
  1163. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1164. This makes it possible to do global cycling without having to use `S-TAB'
  1165. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1166. line of the buffer
  1167. must not be a headline -- it may be empty or some other text.
  1168. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1169. sure the cursor stays at the beginning of the buffer.
  1170. When this option is nil, don't do anything special at the beginning of
  1171. the buffer."
  1172. :group 'org-cycle
  1173. :type 'boolean)
  1174. (defcustom org-cycle-level-after-item/entry-creation t
  1175. "Non-nil means cycle entry level or item indentation in new empty entries.
  1176. When the cursor is at the end of an empty headline, i.e., with only stars
  1177. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1178. and then all possible ancestor states, before returning to the original state.
  1179. This makes data entry extremely fast: M-RET to create a new headline,
  1180. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1181. When the cursor is at the end of an empty plain list item, one TAB will
  1182. make it a subitem, two or more tabs will back up to make this an item
  1183. higher up in the item hierarchy."
  1184. :group 'org-cycle
  1185. :type 'boolean)
  1186. (defcustom org-cycle-emulate-tab t
  1187. "Where should `org-cycle' emulate TAB.
  1188. nil Never
  1189. white Only in completely white lines
  1190. whitestart Only at the beginning of lines, before the first non-white char
  1191. t Everywhere except in headlines
  1192. exc-hl-bol Everywhere except at the start of a headline
  1193. If TAB is used in a place where it does not emulate TAB, the current subtree
  1194. visibility is cycled."
  1195. :group 'org-cycle
  1196. :type '(choice (const :tag "Never" nil)
  1197. (const :tag "Only in completely white lines" white)
  1198. (const :tag "Before first char in a line" whitestart)
  1199. (const :tag "Everywhere except in headlines" t)
  1200. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1201. (defcustom org-cycle-separator-lines 2
  1202. "Number of empty lines needed to keep an empty line between collapsed trees.
  1203. If you leave an empty line between the end of a subtree and the following
  1204. headline, this empty line is hidden when the subtree is folded.
  1205. Org mode will leave (exactly) one empty line visible if the number of
  1206. empty lines is equal or larger to the number given in this variable.
  1207. So the default 2 means at least 2 empty lines after the end of a subtree
  1208. are needed to produce free space between a collapsed subtree and the
  1209. following headline.
  1210. If the number is negative, and the number of empty lines is at least -N,
  1211. all empty lines are shown.
  1212. Special case: when 0, never leave empty lines in collapsed view."
  1213. :group 'org-cycle
  1214. :type 'integer)
  1215. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1216. (defcustom org-pre-cycle-hook nil
  1217. "Hook that is run before visibility cycling is happening.
  1218. The function(s) in this hook must accept a single argument which indicates
  1219. the new state that will be set right after running this hook. The
  1220. argument is a symbol. Before a global state change, it can have the values
  1221. `overview', `content', or `all'. Before a local state change, it can have
  1222. the values `folded', `children', or `subtree'."
  1223. :group 'org-cycle
  1224. :type 'hook)
  1225. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1226. org-cycle-hide-drawers
  1227. org-cycle-show-empty-lines
  1228. org-optimize-window-after-visibility-change)
  1229. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1230. The function(s) in this hook must accept a single argument which indicates
  1231. the new state that was set by the most recent `org-cycle' command. The
  1232. argument is a symbol. After a global state change, it can have the values
  1233. `overview', `contents', or `all'. After a local state change, it can have
  1234. the values `folded', `children', or `subtree'."
  1235. :group 'org-cycle
  1236. :type 'hook
  1237. :version "26.1"
  1238. :package-version '(Org . "8.3"))
  1239. (defgroup org-edit-structure nil
  1240. "Options concerning structure editing in Org mode."
  1241. :tag "Org Edit Structure"
  1242. :group 'org-structure)
  1243. (defcustom org-odd-levels-only nil
  1244. "Non-nil means skip even levels and only use odd levels for the outline.
  1245. This has the effect that two stars are being added/taken away in
  1246. promotion/demotion commands. It also influences how levels are
  1247. handled by the exporters.
  1248. Changing it requires restart of `font-lock-mode' to become effective
  1249. for fontification also in regions already fontified.
  1250. You may also set this on a per-file basis by adding one of the following
  1251. lines to the buffer:
  1252. #+STARTUP: odd
  1253. #+STARTUP: oddeven"
  1254. :group 'org-edit-structure
  1255. :group 'org-appearance
  1256. :type 'boolean)
  1257. (defcustom org-adapt-indentation t
  1258. "Non-nil means adapt indentation to outline node level.
  1259. When this variable is set, Org assumes that you write outlines by
  1260. indenting text in each node to align with the headline (after the
  1261. stars). The following issues are influenced by this variable:
  1262. - The indentation is increased by one space in a demotion
  1263. command, and decreased by one in a promotion command. However,
  1264. in the latter case, if shifting some line in the entry body
  1265. would alter document structure (e.g., insert a new headline),
  1266. indentation is not changed at all.
  1267. - Property drawers and planning information is inserted indented
  1268. when this variable is set. When nil, they will not be indented.
  1269. - TAB indents a line relative to current level. The lines below
  1270. a headline will be indented when this variable is set.
  1271. Note that this is all about true indentation, by adding and
  1272. removing space characters. See also `org-indent.el' which does
  1273. level-dependent indentation in a virtual way, i.e. at display
  1274. time in Emacs."
  1275. :group 'org-edit-structure
  1276. :type 'boolean)
  1277. (defcustom org-special-ctrl-a/e nil
  1278. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1279. When t, `C-a' will bring back the cursor to the beginning of the
  1280. headline text, i.e. after the stars and after a possible TODO
  1281. keyword. In an item, this will be the position after bullet and
  1282. check-box, if any. When the cursor is already at that position,
  1283. another `C-a' will bring it to the beginning of the line.
  1284. `C-e' will jump to the end of the headline, ignoring the presence
  1285. of tags in the headline. A second `C-e' will then jump to the
  1286. true end of the line, after any tags. This also means that, when
  1287. this variable is non-nil, `C-e' also will never jump beyond the
  1288. end of the heading of a folded section, i.e. not after the
  1289. ellipses.
  1290. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1291. normally, going to the true line boundary first. Only a directly
  1292. following, identical keypress will bring the cursor to the
  1293. special positions.
  1294. This may also be a cons cell where the behavior for `C-a' and
  1295. `C-e' is set separately."
  1296. :group 'org-edit-structure
  1297. :type '(choice
  1298. (const :tag "off" nil)
  1299. (const :tag "on: after stars/bullet and before tags first" t)
  1300. (const :tag "reversed: true line boundary first" reversed)
  1301. (cons :tag "Set C-a and C-e separately"
  1302. (choice :tag "Special C-a"
  1303. (const :tag "off" nil)
  1304. (const :tag "on: after stars/bullet first" t)
  1305. (const :tag "reversed: before stars/bullet first" reversed))
  1306. (choice :tag "Special C-e"
  1307. (const :tag "off" nil)
  1308. (const :tag "on: before tags first" t)
  1309. (const :tag "reversed: after tags first" reversed)))))
  1310. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1311. (defcustom org-special-ctrl-k nil
  1312. "Non-nil means `C-k' will behave specially in headlines.
  1313. When nil, `C-k' will call the default `kill-line' command.
  1314. When t, the following will happen while the cursor is in the headline:
  1315. - When the cursor is at the beginning of a headline, kill the entire
  1316. line and possible the folded subtree below the line.
  1317. - When in the middle of the headline text, kill the headline up to the tags.
  1318. - When after the headline text, kill the tags."
  1319. :group 'org-edit-structure
  1320. :type 'boolean)
  1321. (defcustom org-ctrl-k-protect-subtree nil
  1322. "Non-nil means, do not delete a hidden subtree with C-k.
  1323. When set to the symbol `error', simply throw an error when C-k is
  1324. used to kill (part-of) a headline that has hidden text behind it.
  1325. Any other non-nil value will result in a query to the user, if it is
  1326. OK to kill that hidden subtree. When nil, kill without remorse."
  1327. :group 'org-edit-structure
  1328. :version "24.1"
  1329. :type '(choice
  1330. (const :tag "Do not protect hidden subtrees" nil)
  1331. (const :tag "Protect hidden subtrees with a security query" t)
  1332. (const :tag "Never kill a hidden subtree with C-k" error)))
  1333. (defcustom org-special-ctrl-o t
  1334. "Non-nil means, make `C-o' insert a row in tables."
  1335. :group 'org-edit-structure
  1336. :type 'boolean)
  1337. (defcustom org-catch-invisible-edits nil
  1338. "Check if in invisible region before inserting or deleting a character.
  1339. Valid values are:
  1340. nil Do not check, so just do invisible edits.
  1341. error Throw an error and do nothing.
  1342. show Make point visible, and do the requested edit.
  1343. show-and-error Make point visible, then throw an error and abort the edit.
  1344. smart Make point visible, and do insertion/deletion if it is
  1345. adjacent to visible text and the change feels predictable.
  1346. Never delete a previously invisible character or add in the
  1347. middle or right after an invisible region. Basically, this
  1348. allows insertion and backward-delete right before ellipses.
  1349. FIXME: maybe in this case we should not even show?"
  1350. :group 'org-edit-structure
  1351. :version "24.1"
  1352. :type '(choice
  1353. (const :tag "Do not check" nil)
  1354. (const :tag "Throw error when trying to edit" error)
  1355. (const :tag "Unhide, but do not do the edit" show-and-error)
  1356. (const :tag "Show invisible part and do the edit" show)
  1357. (const :tag "Be smart and do the right thing" smart)))
  1358. (defcustom org-yank-folded-subtrees t
  1359. "Non-nil means when yanking subtrees, fold them.
  1360. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1361. it starts with a heading and all other headings in it are either children
  1362. or siblings, then fold all the subtrees. However, do this only if no
  1363. text after the yank would be swallowed into a folded tree by this action."
  1364. :group 'org-edit-structure
  1365. :type 'boolean)
  1366. (defcustom org-yank-adjusted-subtrees nil
  1367. "Non-nil means when yanking subtrees, adjust the level.
  1368. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1369. this function for details."
  1370. :group 'org-edit-structure
  1371. :type 'boolean)
  1372. (defcustom org-M-RET-may-split-line '((default . t))
  1373. "Non-nil means M-RET will split the line at the cursor position.
  1374. When nil, it will go to the end of the line before making a
  1375. new line.
  1376. You may also set this option in a different way for different
  1377. contexts. Valid contexts are:
  1378. headline when creating a new headline
  1379. item when creating a new item
  1380. table in a table field
  1381. default the value to be used for all contexts not explicitly
  1382. customized"
  1383. :group 'org-structure
  1384. :group 'org-table
  1385. :type '(choice
  1386. (const :tag "Always" t)
  1387. (const :tag "Never" nil)
  1388. (repeat :greedy t :tag "Individual contexts"
  1389. (cons
  1390. (choice :tag "Context"
  1391. (const headline)
  1392. (const item)
  1393. (const table)
  1394. (const default))
  1395. (boolean)))))
  1396. (defcustom org-insert-heading-respect-content nil
  1397. "Non-nil means insert new headings after the current subtree.
  1398. \\<org-mode-map>
  1399. When nil, the new heading is created directly after the current line.
  1400. The commands `\\[org-insert-heading-respect-content]' and \
  1401. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1402. for the duration of the command."
  1403. :group 'org-structure
  1404. :type 'boolean)
  1405. (defcustom org-blank-before-new-entry '((heading . auto)
  1406. (plain-list-item . auto))
  1407. "Should `org-insert-heading' leave a blank line before new heading/item?
  1408. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1409. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1410. which case Org will look at the surrounding headings/items and try to
  1411. make an intelligent decision whether to insert a blank line or not."
  1412. :group 'org-edit-structure
  1413. :type '(list
  1414. (cons (const heading)
  1415. (choice (const :tag "Never" nil)
  1416. (const :tag "Always" t)
  1417. (const :tag "Auto" auto)))
  1418. (cons (const plain-list-item)
  1419. (choice (const :tag "Never" nil)
  1420. (const :tag "Always" t)
  1421. (const :tag "Auto" auto)))))
  1422. (defcustom org-insert-heading-hook nil
  1423. "Hook being run after inserting a new heading."
  1424. :group 'org-edit-structure
  1425. :type 'hook)
  1426. (defcustom org-enable-fixed-width-editor t
  1427. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1428. This currently only means they are never auto-wrapped.
  1429. When nil, such lines will be treated like ordinary lines."
  1430. :group 'org-edit-structure
  1431. :type 'boolean)
  1432. (defcustom org-goto-auto-isearch t
  1433. "Non-nil means typing characters in `org-goto' starts incremental search.
  1434. When nil, you can use these keybindings to navigate the buffer:
  1435. q Quit the org-goto interface
  1436. n Go to the next visible heading
  1437. p Go to the previous visible heading
  1438. f Go one heading forward on same level
  1439. b Go one heading backward on same level
  1440. u Go one heading up"
  1441. :group 'org-edit-structure
  1442. :type 'boolean)
  1443. (defgroup org-sparse-trees nil
  1444. "Options concerning sparse trees in Org mode."
  1445. :tag "Org Sparse Trees"
  1446. :group 'org-structure)
  1447. (defcustom org-highlight-sparse-tree-matches t
  1448. "Non-nil means highlight all matches that define a sparse tree.
  1449. The highlights will automatically disappear the next time the buffer is
  1450. changed by an edit command."
  1451. :group 'org-sparse-trees
  1452. :type 'boolean)
  1453. (defcustom org-remove-highlights-with-change t
  1454. "Non-nil means any change to the buffer will remove temporary highlights.
  1455. \\<org-mode-map>\
  1456. Such highlights are created by `org-occur' and `org-clock-display'.
  1457. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1458. to get rid of the highlights.
  1459. The highlights created by `org-toggle-latex-fragment' always need
  1460. `\\[org-toggle-latex-fragment]' to be removed."
  1461. :group 'org-sparse-trees
  1462. :group 'org-time
  1463. :type 'boolean)
  1464. (defcustom org-occur-case-fold-search t
  1465. "Non-nil means `org-occur' should be case-insensitive.
  1466. If set to `smart' the search will be case-insensitive only if it
  1467. doesn't specify any upper case character."
  1468. :group 'org-sparse-trees
  1469. :version "26.1"
  1470. :type '(choice
  1471. (const :tag "Case-sensitive" nil)
  1472. (const :tag "Case-insensitive" t)
  1473. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1474. (defcustom org-occur-hook '(org-first-headline-recenter)
  1475. "Hook that is run after `org-occur' has constructed a sparse tree.
  1476. This can be used to recenter the window to show as much of the structure
  1477. as possible."
  1478. :group 'org-sparse-trees
  1479. :type 'hook)
  1480. (defgroup org-imenu-and-speedbar nil
  1481. "Options concerning imenu and speedbar in Org mode."
  1482. :tag "Org Imenu and Speedbar"
  1483. :group 'org-structure)
  1484. (defcustom org-imenu-depth 2
  1485. "The maximum level for Imenu access to Org headlines.
  1486. This also applied for speedbar access."
  1487. :group 'org-imenu-and-speedbar
  1488. :type 'integer)
  1489. (defgroup org-table nil
  1490. "Options concerning tables in Org mode."
  1491. :tag "Org Table"
  1492. :group 'org)
  1493. (defcustom org-enable-table-editor 'optimized
  1494. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1495. When nil, such lines will be treated like ordinary lines.
  1496. When equal to the symbol `optimized', the table editor will be optimized to
  1497. do the following:
  1498. - Automatic overwrite mode in front of whitespace in table fields.
  1499. This makes the structure of the table stay in tact as long as the edited
  1500. field does not exceed the column width.
  1501. - Minimize the number of realigns. Normally, the table is aligned each time
  1502. TAB or RET are pressed to move to another field. With optimization this
  1503. happens only if changes to a field might have changed the column width.
  1504. Optimization requires replacing the functions `self-insert-command',
  1505. `delete-char', and `backward-delete-char' in Org buffers, with a
  1506. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1507. good at guessing when a re-align will be necessary, but you can always
  1508. force one with `\\[org-ctrl-c-ctrl-c]'.
  1509. If you would like to use the optimized version in Org mode, but the
  1510. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1511. This variable can be used to turn on and off the table editor during a session,
  1512. but in order to toggle optimization, a restart is required.
  1513. See also the variable `org-table-auto-blank-field'."
  1514. :group 'org-table
  1515. :type '(choice
  1516. (const :tag "off" nil)
  1517. (const :tag "on" t)
  1518. (const :tag "on, optimized" optimized)))
  1519. (defcustom org-self-insert-cluster-for-undo nil
  1520. "Non-nil means cluster self-insert commands for undo when possible.
  1521. If this is set, then, like in the Emacs command loop, 20 consecutive
  1522. characters will be undone together.
  1523. This is configurable, because there is some impact on typing performance."
  1524. :group 'org-table
  1525. :type 'boolean)
  1526. (defcustom org-table-tab-recognizes-table.el t
  1527. "Non-nil means TAB will automatically notice a table.el table.
  1528. When it sees such a table, it moves point into it and - if necessary -
  1529. calls `table-recognize-table'."
  1530. :group 'org-table-editing
  1531. :type 'boolean)
  1532. (defgroup org-link nil
  1533. "Options concerning links in Org mode."
  1534. :tag "Org Link"
  1535. :group 'org)
  1536. (defvar-local org-link-abbrev-alist-local nil
  1537. "Buffer-local version of `org-link-abbrev-alist', which see.
  1538. The value of this is taken from the #+LINK lines.")
  1539. (defcustom org-link-parameters
  1540. '(("doi" :follow org--open-doi-link)
  1541. ("elisp" :follow org--open-elisp-link)
  1542. ("file" :complete org-file-complete-link)
  1543. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1544. ("help" :follow org--open-help-link)
  1545. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1546. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1547. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1548. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1549. ("shell" :follow org--open-shell-link))
  1550. "An alist of properties that defines all the links in Org mode.
  1551. The key in each association is a string of the link type.
  1552. Subsequent optional elements make up a p-list of link properties.
  1553. :follow - A function that takes the link path as an argument.
  1554. :export - A function that takes the link path, description and
  1555. export-backend as arguments.
  1556. :store - A function responsible for storing the link. See the
  1557. function `org-store-link-functions'.
  1558. :complete - A function that inserts a link with completion. The
  1559. function takes one optional prefix arg.
  1560. :face - A face for the link, or a function that returns a face.
  1561. The function takes one argument which is the link path. The
  1562. default face is `org-link'.
  1563. :mouse-face - The mouse-face. The default is `highlight'.
  1564. :display - `full' will not fold the link in descriptive
  1565. display. Default is `org-link'.
  1566. :help-echo - A string or function that takes (window object position)
  1567. as arguments and returns a string.
  1568. :keymap - A keymap that is active on the link. The default is
  1569. `org-mouse-map'.
  1570. :htmlize-link - A function for the htmlize-link. Defaults
  1571. to (list :uri \"type:path\")
  1572. :activate-func - A function to run at the end of font-lock
  1573. activation. The function must accept (link-start link-end path bracketp)
  1574. as arguments."
  1575. :group 'org-link
  1576. :type '(alist :tag "Link display parameters"
  1577. :value-type plist)
  1578. :version "26.1"
  1579. :package-version '(Org . "9.1"))
  1580. (defun org-link-get-parameter (type key)
  1581. "Get TYPE link property for KEY.
  1582. TYPE is a string and KEY is a plist keyword."
  1583. (plist-get
  1584. (cdr (assoc type org-link-parameters))
  1585. key))
  1586. (defun org-link-set-parameters (type &rest parameters)
  1587. "Set link TYPE properties to PARAMETERS.
  1588. PARAMETERS should be :key val pairs."
  1589. (let ((data (assoc type org-link-parameters)))
  1590. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1591. (push (cons type parameters) org-link-parameters)
  1592. (org-make-link-regexps)
  1593. (org-element-update-syntax))))
  1594. (defun org-link-types ()
  1595. "Return a list of known link types."
  1596. (mapcar #'car org-link-parameters))
  1597. (defcustom org-link-abbrev-alist nil
  1598. "Alist of link abbreviations.
  1599. The car of each element is a string, to be replaced at the start of a link.
  1600. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1601. links in Org buffers can have an optional tag after a double colon, e.g.,
  1602. [[linkkey:tag][description]]
  1603. The `linkkey' must be a single word, starting with a letter, followed
  1604. by letters, numbers, `-' or `_'.
  1605. If REPLACE is a string, the tag will simply be appended to create the link.
  1606. If the string contains \"%s\", the tag will be inserted there. If the string
  1607. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1608. at that point (see the function `url-hexify-string'). If the string contains
  1609. the specifier \"%(my-function)\", then the custom function `my-function' will
  1610. be invoked: this function takes the tag as its only argument and must return
  1611. a string.
  1612. REPLACE may also be a function that will be called with the tag as the
  1613. only argument to create the link, which should be returned as a string.
  1614. See the manual for examples."
  1615. :group 'org-link
  1616. :type '(repeat
  1617. (cons
  1618. (string :tag "Protocol")
  1619. (choice
  1620. (string :tag "Format")
  1621. (function)))))
  1622. (defcustom org-descriptive-links t
  1623. "Non-nil means Org will display descriptive links.
  1624. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1625. \"Org Website\", hiding the link itself and just displaying its
  1626. description. When set to nil, Org will display the full links
  1627. literally.
  1628. You can interactively set the value of this variable by calling
  1629. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1630. :group 'org-link
  1631. :type 'boolean)
  1632. (defcustom org-link-file-path-type 'adaptive
  1633. "How the path name in file links should be stored.
  1634. Valid values are:
  1635. relative Relative to the current directory, i.e. the directory of the file
  1636. into which the link is being inserted.
  1637. absolute Absolute path, if possible with ~ for home directory.
  1638. noabbrev Absolute path, no abbreviation of home directory.
  1639. adaptive Use relative path for files in the current directory and sub-
  1640. directories of it. For other files, use an absolute path."
  1641. :group 'org-link
  1642. :type '(choice
  1643. (const relative)
  1644. (const absolute)
  1645. (const noabbrev)
  1646. (const adaptive)))
  1647. (defvaralias 'org-activate-links 'org-highlight-links)
  1648. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1649. "Types of links that should be highlighted in Org files.
  1650. This is a list of symbols, each one of them leading to the
  1651. highlighting of a certain link type.
  1652. You can still open links that are not highlighted.
  1653. In principle, it does not hurt to turn on highlighting for all
  1654. link types. There may be a small gain when turning off unused
  1655. link types. The types are:
  1656. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1657. angle Links in angular brackets that may contain whitespace like
  1658. <bbdb:Carsten Dominik>.
  1659. plain Plain links in normal text, no whitespace, like http://google.com.
  1660. radio Text that is matched by a radio target, see manual for details.
  1661. tag Tag settings in a headline (link to tag search).
  1662. date Time stamps (link to calendar).
  1663. footnote Footnote labels.
  1664. If you set this variable during an Emacs session, use `org-mode-restart'
  1665. in the Org buffer so that the change takes effect."
  1666. :group 'org-link
  1667. :group 'org-appearance
  1668. :type '(set :greedy t
  1669. (const :tag "Double bracket links" bracket)
  1670. (const :tag "Angular bracket links" angle)
  1671. (const :tag "Plain text links" plain)
  1672. (const :tag "Radio target matches" radio)
  1673. (const :tag "Tags" tag)
  1674. (const :tag "Timestamps" date)
  1675. (const :tag "Footnotes" footnote)))
  1676. (defcustom org-make-link-description-function nil
  1677. "Function to use for generating link descriptions from links.
  1678. When nil, the link location will be used. This function must take
  1679. two parameters: the first one is the link, the second one is the
  1680. description generated by `org-insert-link'. The function should
  1681. return the description to use."
  1682. :group 'org-link
  1683. :type '(choice (const nil) (function)))
  1684. (defgroup org-link-store nil
  1685. "Options concerning storing links in Org mode."
  1686. :tag "Org Store Link"
  1687. :group 'org-link)
  1688. (defcustom org-url-hexify-p t
  1689. "When non-nil, hexify URL when creating a link."
  1690. :type 'boolean
  1691. :version "24.3"
  1692. :group 'org-link-store)
  1693. (defcustom org-email-link-description-format "Email %c: %.30s"
  1694. "Format of the description part of a link to an email or usenet message.
  1695. The following %-escapes will be replaced by corresponding information:
  1696. %F full \"From\" field
  1697. %f name, taken from \"From\" field, address if no name
  1698. %T full \"To\" field
  1699. %t first name in \"To\" field, address if no name
  1700. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1701. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1702. %s subject
  1703. %d date
  1704. %m message-id.
  1705. You may use normal field width specification between the % and the letter.
  1706. This is for example useful to limit the length of the subject.
  1707. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1708. :group 'org-link-store
  1709. :type 'string)
  1710. (defcustom org-from-is-user-regexp
  1711. (let (r1 r2)
  1712. (when (and user-mail-address (not (string= user-mail-address "")))
  1713. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1714. (when (and user-full-name (not (string= user-full-name "")))
  1715. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1716. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1717. "Regexp matched against the \"From:\" header of an email or usenet message.
  1718. It should match if the message is from the user him/herself."
  1719. :group 'org-link-store
  1720. :type 'regexp)
  1721. (defcustom org-context-in-file-links t
  1722. "Non-nil means file links from `org-store-link' contain context.
  1723. \\<org-mode-map>
  1724. A search string will be added to the file name with :: as separator
  1725. and used to find the context when the link is activated by the command
  1726. `org-open-at-point'. When this option is t, the entire active region
  1727. will be placed in the search string of the file link. If set to a
  1728. positive integer, only the first n lines of context will be stored.
  1729. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1730. \\[org-store-link]')
  1731. negates this setting for the duration of the command."
  1732. :group 'org-link-store
  1733. :type '(choice boolean integer))
  1734. (defcustom org-keep-stored-link-after-insertion nil
  1735. "Non-nil means keep link in list for entire session.
  1736. \\<org-mode-map>
  1737. The command `org-store-link' adds a link pointing to the current
  1738. location to an internal list. These links accumulate during a session.
  1739. The command `org-insert-link' can be used to insert links into any
  1740. Org file (offering completion for all stored links).
  1741. When this option is nil, every link which has been inserted once using
  1742. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1743. unused
  1744. links more efficient."
  1745. :group 'org-link-store
  1746. :type 'boolean)
  1747. (defgroup org-link-follow nil
  1748. "Options concerning following links in Org mode."
  1749. :tag "Org Follow Link"
  1750. :group 'org-link)
  1751. (defcustom org-link-translation-function nil
  1752. "Function to translate links with different syntax to Org syntax.
  1753. This can be used to translate links created for example by the Planner
  1754. or emacs-wiki packages to Org syntax.
  1755. The function must accept two parameters, a TYPE containing the link
  1756. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1757. which is everything after the link protocol. It should return a cons
  1758. with possibly modified values of type and path.
  1759. Org contains a function for this, so if you set this variable to
  1760. `org-translate-link-from-planner', you should be able follow many
  1761. links created by planner."
  1762. :group 'org-link-follow
  1763. :type '(choice (const nil) (function)))
  1764. (defcustom org-follow-link-hook nil
  1765. "Hook that is run after a link has been followed."
  1766. :group 'org-link-follow
  1767. :type 'hook)
  1768. (defcustom org-tab-follows-link nil
  1769. "Non-nil means on links TAB will follow the link.
  1770. Needs to be set before org.el is loaded.
  1771. This really should not be used, it does not make sense, and the
  1772. implementation is bad."
  1773. :group 'org-link-follow
  1774. :type 'boolean)
  1775. (defcustom org-return-follows-link nil
  1776. "Non-nil means on links RET will follow the link.
  1777. In tables, the special behavior of RET has precedence."
  1778. :group 'org-link-follow
  1779. :type 'boolean)
  1780. (defcustom org-mouse-1-follows-link
  1781. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1782. "Non-nil means mouse-1 on a link will follow the link.
  1783. A longer mouse click will still set point. Needs to be set
  1784. before org.el is loaded."
  1785. :group 'org-link-follow
  1786. :version "24.4"
  1787. :package-version '(Org . "8.3")
  1788. :type '(choice
  1789. (const :tag "A double click follows the link" double)
  1790. (const :tag "Unconditionally follow the link with mouse-1" t)
  1791. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1792. (defcustom org-mark-ring-length 4
  1793. "Number of different positions to be recorded in the ring.
  1794. Changing this requires a restart of Emacs to work correctly."
  1795. :group 'org-link-follow
  1796. :type 'integer)
  1797. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1798. "Non-nil means internal fuzzy links can only match headlines.
  1799. When nil, the a fuzzy link may point to a target or a named
  1800. construct in the document. When set to the special value
  1801. `query-to-create', offer to create a new headline when none
  1802. matched.
  1803. Spaces and statistics cookies are ignored during heading searches."
  1804. :group 'org-link-follow
  1805. :version "24.1"
  1806. :type '(choice
  1807. (const :tag "Use fuzzy text search" nil)
  1808. (const :tag "Match only exact headline" t)
  1809. (const :tag "Match exact headline or query to create it"
  1810. query-to-create))
  1811. :safe #'symbolp)
  1812. (defcustom org-link-frame-setup
  1813. '((vm . vm-visit-folder-other-frame)
  1814. (vm-imap . vm-visit-imap-folder-other-frame)
  1815. (gnus . org-gnus-no-new-news)
  1816. (file . find-file-other-window)
  1817. (wl . wl-other-frame))
  1818. "Setup the frame configuration for following links.
  1819. When following a link with Emacs, it may often be useful to display
  1820. this link in another window or frame. This variable can be used to
  1821. set this up for the different types of links.
  1822. For VM, use any of
  1823. `vm-visit-folder'
  1824. `vm-visit-folder-other-window'
  1825. `vm-visit-folder-other-frame'
  1826. For Gnus, use any of
  1827. `gnus'
  1828. `gnus-other-frame'
  1829. `org-gnus-no-new-news'
  1830. For FILE, use any of
  1831. `find-file'
  1832. `find-file-other-window'
  1833. `find-file-other-frame'
  1834. For Wanderlust use any of
  1835. `wl'
  1836. `wl-other-frame'
  1837. For the calendar, use the variable `calendar-setup'.
  1838. For BBDB, it is currently only possible to display the matches in
  1839. another window."
  1840. :group 'org-link-follow
  1841. :type '(list
  1842. (cons (const vm)
  1843. (choice
  1844. (const vm-visit-folder)
  1845. (const vm-visit-folder-other-window)
  1846. (const vm-visit-folder-other-frame)))
  1847. (cons (const vm-imap)
  1848. (choice
  1849. (const vm-visit-imap-folder)
  1850. (const vm-visit-imap-folder-other-window)
  1851. (const vm-visit-imap-folder-other-frame)))
  1852. (cons (const gnus)
  1853. (choice
  1854. (const gnus)
  1855. (const gnus-other-frame)
  1856. (const org-gnus-no-new-news)))
  1857. (cons (const file)
  1858. (choice
  1859. (const find-file)
  1860. (const find-file-other-window)
  1861. (const find-file-other-frame)))
  1862. (cons (const wl)
  1863. (choice
  1864. (const wl)
  1865. (const wl-other-frame)))))
  1866. (defcustom org-display-internal-link-with-indirect-buffer nil
  1867. "Non-nil means use indirect buffer to display infile links.
  1868. Activating internal links (from one location in a file to another location
  1869. in the same file) normally just jumps to the location. When the link is
  1870. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1871. is displayed in
  1872. another window. When this option is set, the other window actually displays
  1873. an indirect buffer clone of the current buffer, to avoid any visibility
  1874. changes to the current buffer."
  1875. :group 'org-link-follow
  1876. :type 'boolean)
  1877. (defcustom org-open-non-existing-files nil
  1878. "Non-nil means `org-open-file' will open non-existing files.
  1879. When nil, an error will be generated.
  1880. This variable applies only to external applications because they
  1881. might choke on non-existing files. If the link is to a file that
  1882. will be opened in Emacs, the variable is ignored."
  1883. :group 'org-link-follow
  1884. :type 'boolean)
  1885. (defcustom org-open-directory-means-index-dot-org nil
  1886. "Non-nil means a link to a directory really means to index.org.
  1887. When nil, following a directory link will run dired or open a finder/explorer
  1888. window on that directory."
  1889. :group 'org-link-follow
  1890. :type 'boolean)
  1891. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1892. "Non-nil means ask for confirmation before executing shell links.
  1893. Shell links can be dangerous: just think about a link
  1894. [[shell:rm -rf ~/*][Google Search]]
  1895. This link would show up in your Org document as \"Google Search\",
  1896. but really it would remove your entire home directory.
  1897. Therefore we advise against setting this variable to nil.
  1898. Just change it to `y-or-n-p' if you want to confirm with a
  1899. single keystroke rather than having to type \"yes\"."
  1900. :group 'org-link-follow
  1901. :type '(choice
  1902. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1903. (const :tag "with y-or-n (faster)" y-or-n-p)
  1904. (const :tag "no confirmation (dangerous)" nil)))
  1905. (put 'org-confirm-shell-link-function
  1906. 'safe-local-variable
  1907. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1908. (defcustom org-confirm-shell-link-not-regexp ""
  1909. "A regexp to skip confirmation for shell links."
  1910. :group 'org-link-follow
  1911. :version "24.1"
  1912. :type 'regexp)
  1913. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1914. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1915. Elisp links can be dangerous: just think about a link
  1916. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1917. This link would show up in your Org document as \"Google Search\",
  1918. but really it would remove your entire home directory.
  1919. Therefore we advise against setting this variable to nil.
  1920. Just change it to `y-or-n-p' if you want to confirm with a
  1921. single keystroke rather than having to type \"yes\"."
  1922. :group 'org-link-follow
  1923. :type '(choice
  1924. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1925. (const :tag "with y-or-n (faster)" y-or-n-p)
  1926. (const :tag "no confirmation (dangerous)" nil)))
  1927. (put 'org-confirm-shell-link-function
  1928. 'safe-local-variable
  1929. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1930. (defcustom org-confirm-elisp-link-not-regexp ""
  1931. "A regexp to skip confirmation for Elisp links."
  1932. :group 'org-link-follow
  1933. :version "24.1"
  1934. :type 'regexp)
  1935. (defconst org-file-apps-defaults-gnu
  1936. '((remote . emacs)
  1937. (system . mailcap)
  1938. (t . mailcap))
  1939. "Default file applications on a UNIX or GNU/Linux system.
  1940. See `org-file-apps'.")
  1941. (defconst org-file-apps-defaults-macosx
  1942. '((remote . emacs)
  1943. (system . "open %s")
  1944. ("ps.gz" . "gv %s")
  1945. ("eps.gz" . "gv %s")
  1946. ("dvi" . "xdvi %s")
  1947. ("fig" . "xfig %s")
  1948. (t . "open %s"))
  1949. "Default file applications on a macOS system.
  1950. The system \"open\" is known as a default, but we use X11 applications
  1951. for some files for which the OS does not have a good default.
  1952. See `org-file-apps'.")
  1953. (defconst org-file-apps-defaults-windowsnt
  1954. (list '(remote . emacs)
  1955. (cons 'system (lambda (file _path)
  1956. (with-no-warnings (w32-shell-execute "open" file))))
  1957. (cons t (lambda (file _path)
  1958. (with-no-warnings (w32-shell-execute "open" file)))))
  1959. "Default file applications on a Windows NT system.
  1960. The system \"open\" is used for most files.
  1961. See `org-file-apps'.")
  1962. (defcustom org-file-apps
  1963. '((auto-mode . emacs)
  1964. ("\\.mm\\'" . default)
  1965. ("\\.x?html?\\'" . default)
  1966. ("\\.pdf\\'" . default))
  1967. "External applications for opening `file:path' items in a document.
  1968. \\<org-mode-map>\
  1969. Org mode uses system defaults for different file types, but
  1970. you can use this variable to set the application for a given file
  1971. extension. The entries in this list are cons cells where the car identifies
  1972. files and the cdr the corresponding command.
  1973. Possible values for the file identifier are:
  1974. \"string\" A string as a file identifier can be interpreted in different
  1975. ways, depending on its contents:
  1976. - Alphanumeric characters only:
  1977. Match links with this file extension.
  1978. Example: (\"pdf\" . \"evince %s\")
  1979. to open PDFs with evince.
  1980. - Regular expression: Match links where the
  1981. filename matches the regexp. If you want to
  1982. use groups here, use shy groups.
  1983. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1984. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1985. to open *.html and *.xhtml with firefox.
  1986. - Regular expression which contains (non-shy) groups:
  1987. Match links where the whole link, including \"::\", and
  1988. anything after that, matches the regexp.
  1989. In a custom command string, %1, %2, etc. are replaced with
  1990. the parts of the link that were matched by the groups.
  1991. For backwards compatibility, if a command string is given
  1992. that does not use any of the group matches, this case is
  1993. handled identically to the second one (i.e. match against
  1994. file name only).
  1995. In a custom function, you can access the group matches with
  1996. (match-string n link).
  1997. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1998. \"evince -p %1 %s\")
  1999. to open [[file:document.pdf::5]] with evince at page 5.
  2000. `directory' Matches a directory
  2001. `remote' Matches a remote file, accessible through tramp or efs.
  2002. Remote files most likely should be visited through Emacs
  2003. because external applications cannot handle such paths.
  2004. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2005. so all files Emacs knows how to handle. Using this with
  2006. command `emacs' will open most files in Emacs. Beware that this
  2007. will also open html files inside Emacs, unless you add
  2008. (\"html\" . default) to the list as well.
  2009. `system' The system command to open files, like `open' on Windows
  2010. and macOS, and mailcap under GNU/Linux. This is the command
  2011. that will be selected if you call `org-open-at-point' with a
  2012. double prefix argument (`\\[universal-argument] \
  2013. \\[universal-argument] \\[org-open-at-point]').
  2014. t Default for files not matched by any of the other options.
  2015. Possible values for the command are:
  2016. `emacs' The file will be visited by the current Emacs process.
  2017. `default' Use the default application for this file type, which is the
  2018. association for t in the list, most likely in the system-specific
  2019. part. This can be used to overrule an unwanted setting in the
  2020. system-specific variable.
  2021. `system' Use the system command for opening files, like \"open\".
  2022. This command is specified by the entry whose car is `system'.
  2023. Most likely, the system-specific version of this variable
  2024. does define this command, but you can overrule/replace it
  2025. here.
  2026. `mailcap' Use command specified in the mailcaps.
  2027. string A command to be executed by a shell; %s will be replaced
  2028. by the path to the file.
  2029. function A Lisp function, which will be called with two arguments:
  2030. the file path and the original link string, without the
  2031. \"file:\" prefix.
  2032. For more examples, see the system specific constants
  2033. `org-file-apps-defaults-macosx'
  2034. `org-file-apps-defaults-windowsnt'
  2035. `org-file-apps-defaults-gnu'."
  2036. :group 'org-link-follow
  2037. :type '(repeat
  2038. (cons (choice :value ""
  2039. (string :tag "Extension")
  2040. (const :tag "System command to open files" system)
  2041. (const :tag "Default for unrecognized files" t)
  2042. (const :tag "Remote file" remote)
  2043. (const :tag "Links to a directory" directory)
  2044. (const :tag "Any files that have Emacs modes"
  2045. auto-mode))
  2046. (choice :value ""
  2047. (const :tag "Visit with Emacs" emacs)
  2048. (const :tag "Use default" default)
  2049. (const :tag "Use the system command" system)
  2050. (string :tag "Command")
  2051. (function :tag "Function")))))
  2052. (defcustom org-doi-server-url "http://dx.doi.org/"
  2053. "The URL of the DOI server."
  2054. :type 'string
  2055. :version "24.3"
  2056. :group 'org-link-follow)
  2057. (defgroup org-refile nil
  2058. "Options concerning refiling entries in Org mode."
  2059. :tag "Org Refile"
  2060. :group 'org)
  2061. (defcustom org-directory "~/org"
  2062. "Directory with Org files.
  2063. This is just a default location to look for Org files. There is no need
  2064. at all to put your files into this directory. It is used in the
  2065. following situations:
  2066. 1. When a capture template specifies a target file that is not an
  2067. absolute path. The path will then be interpreted relative to
  2068. `org-directory'
  2069. 2. When the value of variable `org-agenda-files' is a single file, any
  2070. relative paths in this file will be taken as relative to
  2071. `org-directory'."
  2072. :group 'org-refile
  2073. :group 'org-capture
  2074. :type 'directory)
  2075. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2076. "Default target for storing notes.
  2077. Used as a fall back file for org-capture.el, for templates that
  2078. do not specify a target file."
  2079. :group 'org-refile
  2080. :group 'org-capture
  2081. :type 'file)
  2082. (defcustom org-goto-interface 'outline
  2083. "The default interface to be used for `org-goto'.
  2084. Allowed values are:
  2085. outline The interface shows an outline of the relevant file
  2086. and the correct heading is found by moving through
  2087. the outline or by searching with incremental search.
  2088. outline-path-completion Headlines in the current buffer are offered via
  2089. completion. This is the interface also used by
  2090. the refile command."
  2091. :group 'org-refile
  2092. :type '(choice
  2093. (const :tag "Outline" outline)
  2094. (const :tag "Outline-path-completion" outline-path-completion)))
  2095. (defcustom org-goto-max-level 5
  2096. "Maximum target level when running `org-goto' with refile interface."
  2097. :group 'org-refile
  2098. :type 'integer)
  2099. (defcustom org-reverse-note-order nil
  2100. "Non-nil means store new notes at the beginning of a file or entry.
  2101. When nil, new notes will be filed to the end of a file or entry.
  2102. This can also be a list with cons cells of regular expressions that
  2103. are matched against file names, and values."
  2104. :group 'org-capture
  2105. :group 'org-refile
  2106. :type '(choice
  2107. (const :tag "Reverse always" t)
  2108. (const :tag "Reverse never" nil)
  2109. (repeat :tag "By file name regexp"
  2110. (cons regexp boolean))))
  2111. (defcustom org-log-refile nil
  2112. "Information to record when a task is refiled.
  2113. Possible values are:
  2114. nil Don't add anything
  2115. time Add a time stamp to the task
  2116. note Prompt for a note and add it with template `org-log-note-headings'
  2117. This option can also be set with on a per-file-basis with
  2118. #+STARTUP: nologrefile
  2119. #+STARTUP: logrefile
  2120. #+STARTUP: lognoterefile
  2121. You can have local logging settings for a subtree by setting the LOGGING
  2122. property to one or more of these keywords.
  2123. When bulk-refiling from the agenda, the value `note' is forbidden and
  2124. will temporarily be changed to `time'."
  2125. :group 'org-refile
  2126. :group 'org-progress
  2127. :version "24.1"
  2128. :type '(choice
  2129. (const :tag "No logging" nil)
  2130. (const :tag "Record timestamp" time)
  2131. (const :tag "Record timestamp with note." note)))
  2132. (defcustom org-refile-targets nil
  2133. "Targets for refiling entries with `\\[org-refile]'.
  2134. This is a list of cons cells. Each cell contains:
  2135. - a specification of the files to be considered, either a list of files,
  2136. or a symbol whose function or variable value will be used to retrieve
  2137. a file name or a list of file names. If you use `org-agenda-files' for
  2138. that, all agenda files will be scanned for targets. Nil means consider
  2139. headings in the current buffer.
  2140. - A specification of how to find candidate refile targets. This may be
  2141. any of:
  2142. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2143. This tag has to be present in all target headlines, inheritance will
  2144. not be considered.
  2145. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2146. todo keyword.
  2147. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2148. headlines that are refiling targets.
  2149. - a cons cell (:level . N). Any headline of level N is considered a target.
  2150. Note that, when `org-odd-levels-only' is set, level corresponds to
  2151. order in hierarchy, not to the number of stars.
  2152. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2153. Note that, when `org-odd-levels-only' is set, level corresponds to
  2154. order in hierarchy, not to the number of stars.
  2155. Each element of this list generates a set of possible targets.
  2156. The union of these sets is presented (with completion) to
  2157. the user by `org-refile'.
  2158. You can set the variable `org-refile-target-verify-function' to a function
  2159. to verify each headline found by the simple criteria above.
  2160. When this variable is nil, all top-level headlines in the current buffer
  2161. are used, equivalent to the value `((nil . (:level . 1))'."
  2162. :group 'org-refile
  2163. :type '(repeat
  2164. (cons
  2165. (choice :value org-agenda-files
  2166. (const :tag "All agenda files" org-agenda-files)
  2167. (const :tag "Current buffer" nil)
  2168. (function) (variable) (file))
  2169. (choice :tag "Identify target headline by"
  2170. (cons :tag "Specific tag" (const :value :tag) (string))
  2171. (cons :tag "TODO keyword" (const :value :todo) (string))
  2172. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2173. (cons :tag "Level number" (const :value :level) (integer))
  2174. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2175. (defcustom org-refile-target-verify-function nil
  2176. "Function to verify if the headline at point should be a refile target.
  2177. The function will be called without arguments, with point at the
  2178. beginning of the headline. It should return t and leave point
  2179. where it is if the headline is a valid target for refiling.
  2180. If the target should not be selected, the function must return nil.
  2181. In addition to this, it may move point to a place from where the search
  2182. should be continued. For example, the function may decide that the entire
  2183. subtree of the current entry should be excluded and move point to the end
  2184. of the subtree."
  2185. :group 'org-refile
  2186. :type '(choice
  2187. (const nil)
  2188. (function)))
  2189. (defcustom org-refile-use-cache nil
  2190. "Non-nil means cache refile targets to speed up the process.
  2191. \\<org-mode-map>\
  2192. The cache for a particular file will be updated automatically when
  2193. the buffer has been killed, or when any of the marker used for flagging
  2194. refile targets no longer points at a live buffer.
  2195. If you have added new entries to a buffer that might themselves be targets,
  2196. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2197. if you find that easier, \
  2198. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2199. \\[org-refile]'."
  2200. :group 'org-refile
  2201. :version "24.1"
  2202. :type 'boolean)
  2203. (defcustom org-refile-use-outline-path nil
  2204. "Non-nil means provide refile targets as paths.
  2205. So a level 3 headline will be available as level1/level2/level3.
  2206. When the value is `file', also include the file name (without directory)
  2207. into the path. In this case, you can also stop the completion after
  2208. the file name, to get entries inserted as top level in the file.
  2209. When `full-file-path', include the full file path.
  2210. When `buffer-name', use the buffer name."
  2211. :group 'org-refile
  2212. :type '(choice
  2213. (const :tag "Not" nil)
  2214. (const :tag "Yes" t)
  2215. (const :tag "Start with file name" file)
  2216. (const :tag "Start with full file path" full-file-path)
  2217. (const :tag "Start with buffer name" buffer-name)))
  2218. (defcustom org-outline-path-complete-in-steps t
  2219. "Non-nil means complete the outline path in hierarchical steps.
  2220. When Org uses the refile interface to select an outline path (see
  2221. `org-refile-use-outline-path'), the completion of the path can be
  2222. done in a single go, or it can be done in steps down the headline
  2223. hierarchy. Going in steps is probably the best if you do not use
  2224. a special completion package like `ido' or `icicles'. However,
  2225. when using these packages, going in one step can be very fast,
  2226. while still showing the whole path to the entry."
  2227. :group 'org-refile
  2228. :type 'boolean)
  2229. (defcustom org-refile-allow-creating-parent-nodes nil
  2230. "Non-nil means allow the creation of new nodes as refile targets.
  2231. New nodes are then created by adding \"/new node name\" to the completion
  2232. of an existing node. When the value of this variable is `confirm',
  2233. new node creation must be confirmed by the user (recommended).
  2234. When nil, the completion must match an existing entry.
  2235. Note that, if the new heading is not seen by the criteria
  2236. listed in `org-refile-targets', multiple instances of the same
  2237. heading would be created by trying again to file under the new
  2238. heading."
  2239. :group 'org-refile
  2240. :type '(choice
  2241. (const :tag "Never" nil)
  2242. (const :tag "Always" t)
  2243. (const :tag "Prompt for confirmation" confirm)))
  2244. (defcustom org-refile-active-region-within-subtree nil
  2245. "Non-nil means also refile active region within a subtree.
  2246. By default `org-refile' doesn't allow refiling regions if they
  2247. don't contain a set of subtrees, but it might be convenient to
  2248. do so sometimes: in that case, the first line of the region is
  2249. converted to a headline before refiling."
  2250. :group 'org-refile
  2251. :version "24.1"
  2252. :type 'boolean)
  2253. (defgroup org-todo nil
  2254. "Options concerning TODO items in Org mode."
  2255. :tag "Org TODO"
  2256. :group 'org)
  2257. (defgroup org-progress nil
  2258. "Options concerning Progress logging in Org mode."
  2259. :tag "Org Progress"
  2260. :group 'org-time)
  2261. (defvar org-todo-interpretation-widgets
  2262. '((:tag "Sequence (cycling hits every state)" sequence)
  2263. (:tag "Type (cycling directly to DONE)" type))
  2264. "The available interpretation symbols for customizing `org-todo-keywords'.
  2265. Interested libraries should add to this list.")
  2266. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2267. "List of TODO entry keyword sequences and their interpretation.
  2268. \\<org-mode-map>This is a list of sequences.
  2269. Each sequence starts with a symbol, either `sequence' or `type',
  2270. indicating if the keywords should be interpreted as a sequence of
  2271. action steps, or as different types of TODO items. The first
  2272. keywords are states requiring action - these states will select a headline
  2273. for inclusion into the global TODO list Org produces. If one of the
  2274. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2275. signify that no further action is necessary. If \"|\" is not found,
  2276. the last keyword is treated as the only DONE state of the sequence.
  2277. The command `\\[org-todo]' cycles an entry through these states, and one
  2278. additional state where no keyword is present. For details about this
  2279. cycling, see the manual.
  2280. TODO keywords and interpretation can also be set on a per-file basis with
  2281. the special #+SEQ_TODO and #+TYP_TODO lines.
  2282. Each keyword can optionally specify a character for fast state selection
  2283. \(in combination with the variable `org-use-fast-todo-selection')
  2284. and specifiers for state change logging, using the same syntax that
  2285. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2286. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2287. indicates to record a time stamp each time this state is selected.
  2288. Each keyword may also specify if a timestamp or a note should be
  2289. recorded when entering or leaving the state, by adding additional
  2290. characters in the parenthesis after the keyword. This looks like this:
  2291. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2292. record only the time of the state change. With X and Y being either
  2293. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2294. Y when leaving the state if and only if the *target* state does not
  2295. define X. You may omit any of the fast-selection key or X or /Y,
  2296. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2297. For backward compatibility, this variable may also be just a list
  2298. of keywords. In this case the interpretation (sequence or type) will be
  2299. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2300. :group 'org-todo
  2301. :group 'org-keywords
  2302. :type '(choice
  2303. (repeat :tag "Old syntax, just keywords"
  2304. (string :tag "Keyword"))
  2305. (repeat :tag "New syntax"
  2306. (cons
  2307. (choice
  2308. :tag "Interpretation"
  2309. ;;Quick and dirty way to see
  2310. ;;`org-todo-interpretations'. This takes the
  2311. ;;place of item arguments
  2312. :convert-widget
  2313. (lambda (widget)
  2314. (widget-put widget
  2315. :args (mapcar
  2316. (lambda (x)
  2317. (widget-convert
  2318. (cons 'const x)))
  2319. org-todo-interpretation-widgets))
  2320. widget))
  2321. (repeat
  2322. (string :tag "Keyword"))))))
  2323. (defvar-local org-todo-keywords-1 nil
  2324. "All TODO and DONE keywords active in a buffer.")
  2325. (defvar org-todo-keywords-for-agenda nil)
  2326. (defvar org-done-keywords-for-agenda nil)
  2327. (defvar org-todo-keyword-alist-for-agenda nil)
  2328. (defvar org-tag-alist-for-agenda nil
  2329. "Alist of all tags from all agenda files.")
  2330. (defvar org-tag-groups-alist-for-agenda nil
  2331. "Alist of all groups tags from all current agenda files.")
  2332. (defvar-local org-tag-groups-alist nil)
  2333. (defvar org-agenda-contributing-files nil)
  2334. (defvar-local org-current-tag-alist nil
  2335. "Alist of all tag groups in current buffer.
  2336. This variable takes into consideration `org-tag-alist',
  2337. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2338. (defvar-local org-not-done-keywords nil)
  2339. (defvar-local org-done-keywords nil)
  2340. (defvar-local org-todo-heads nil)
  2341. (defvar-local org-todo-sets nil)
  2342. (defvar-local org-todo-log-states nil)
  2343. (defvar-local org-todo-kwd-alist nil)
  2344. (defvar-local org-todo-key-alist nil)
  2345. (defvar-local org-todo-key-trigger nil)
  2346. (defcustom org-todo-interpretation 'sequence
  2347. "Controls how TODO keywords are interpreted.
  2348. This variable is in principle obsolete and is only used for
  2349. backward compatibility, if the interpretation of todo keywords is
  2350. not given already in `org-todo-keywords'. See that variable for
  2351. more information."
  2352. :group 'org-todo
  2353. :group 'org-keywords
  2354. :type '(choice (const sequence)
  2355. (const type)))
  2356. (defcustom org-use-fast-todo-selection t
  2357. "\\<org-mode-map>\
  2358. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2359. This variable describes if and under what circumstances the cycling
  2360. mechanism for TODO keywords will be replaced by a single-key, direct
  2361. selection scheme.
  2362. When nil, fast selection is never used.
  2363. When the symbol `prefix', it will be used when `org-todo' is called
  2364. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2365. in an Org buffer, and
  2366. `\\[universal-argument] t' in an agenda buffer.
  2367. When t, fast selection is used by default. In this case, the prefix
  2368. argument forces cycling instead.
  2369. In all cases, the special interface is only used if access keys have
  2370. actually been assigned by the user, i.e. if keywords in the configuration
  2371. are followed by a letter in parenthesis, like TODO(t)."
  2372. :group 'org-todo
  2373. :type '(choice
  2374. (const :tag "Never" nil)
  2375. (const :tag "By default" t)
  2376. (const :tag "Only with C-u C-c C-t" prefix)))
  2377. (defcustom org-provide-todo-statistics t
  2378. "Non-nil means update todo statistics after insert and toggle.
  2379. ALL-HEADLINES means update todo statistics by including headlines
  2380. with no TODO keyword as well, counting them as not done.
  2381. A list of TODO keywords means the same, but skip keywords that are
  2382. not in this list.
  2383. When set to a list of two lists, the first list contains keywords
  2384. to consider as TODO keywords, the second list contains keywords
  2385. to consider as DONE keywords.
  2386. When this is set, todo statistics is updated in the parent of the
  2387. current entry each time a todo state is changed."
  2388. :group 'org-todo
  2389. :type '(choice
  2390. (const :tag "Yes, only for TODO entries" t)
  2391. (const :tag "Yes, including all entries" all-headlines)
  2392. (repeat :tag "Yes, for TODOs in this list"
  2393. (string :tag "TODO keyword"))
  2394. (list :tag "Yes, for TODOs and DONEs in these lists"
  2395. (repeat (string :tag "TODO keyword"))
  2396. (repeat (string :tag "DONE keyword")))
  2397. (other :tag "No TODO statistics" nil)))
  2398. (defcustom org-hierarchical-todo-statistics t
  2399. "Non-nil means TODO statistics covers just direct children.
  2400. When nil, all entries in the subtree are considered.
  2401. This has only an effect if `org-provide-todo-statistics' is set.
  2402. To set this to nil for only a single subtree, use a COOKIE_DATA
  2403. property and include the word \"recursive\" into the value."
  2404. :group 'org-todo
  2405. :type 'boolean)
  2406. (defcustom org-after-todo-state-change-hook nil
  2407. "Hook which is run after the state of a TODO item was changed.
  2408. The new state (a string with a TODO keyword, or nil) is available in the
  2409. Lisp variable `org-state'."
  2410. :group 'org-todo
  2411. :type 'hook)
  2412. (defvar org-blocker-hook nil
  2413. "Hook for functions that are allowed to block a state change.
  2414. Functions in this hook should not modify the buffer.
  2415. Each function gets as its single argument a property list,
  2416. see `org-trigger-hook' for more information about this list.
  2417. If any of the functions in this hook returns nil, the state change
  2418. is blocked.")
  2419. (defvar org-trigger-hook nil
  2420. "Hook for functions that are triggered by a state change.
  2421. Each function gets as its single argument a property list with at
  2422. least the following elements:
  2423. (:type type-of-change :position pos-at-entry-start
  2424. :from old-state :to new-state)
  2425. Depending on the type, more properties may be present.
  2426. This mechanism is currently implemented for:
  2427. TODO state changes
  2428. ------------------
  2429. :type todo-state-change
  2430. :from previous state (keyword as a string), or nil, or a symbol
  2431. `todo' or `done', to indicate the general type of state.
  2432. :to new state, like in :from")
  2433. (defcustom org-enforce-todo-dependencies nil
  2434. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2435. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2436. be blocked if any prior sibling is not yet done.
  2437. Finally, if the parent is blocked because of ordered siblings of its own,
  2438. the child will also be blocked."
  2439. :set (lambda (var val)
  2440. (set var val)
  2441. (if val
  2442. (add-hook 'org-blocker-hook
  2443. 'org-block-todo-from-children-or-siblings-or-parent)
  2444. (remove-hook 'org-blocker-hook
  2445. 'org-block-todo-from-children-or-siblings-or-parent)))
  2446. :group 'org-todo
  2447. :type 'boolean)
  2448. (defcustom org-enforce-todo-checkbox-dependencies nil
  2449. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2450. When this is nil, checkboxes have no influence on switching TODO states.
  2451. When non-nil, you first need to check off all check boxes before the TODO
  2452. entry can be switched to DONE.
  2453. This variable needs to be set before org.el is loaded, and you need to
  2454. restart Emacs after a change to make the change effective. The only way
  2455. to change is while Emacs is running is through the customize interface."
  2456. :set (lambda (var val)
  2457. (set var val)
  2458. (if val
  2459. (add-hook 'org-blocker-hook
  2460. 'org-block-todo-from-checkboxes)
  2461. (remove-hook 'org-blocker-hook
  2462. 'org-block-todo-from-checkboxes)))
  2463. :group 'org-todo
  2464. :type 'boolean)
  2465. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2466. "Non-nil means inserting a TODO heading is treated as state change.
  2467. So when the command `\\[org-insert-todo-heading]' is used, state change
  2468. logging will apply if appropriate. When nil, the new TODO item will
  2469. be inserted directly, and no logging will take place."
  2470. :group 'org-todo
  2471. :type 'boolean)
  2472. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2473. "Non-nil means switching TODO states with S-cursor counts as state change.
  2474. This is the default behavior. However, setting this to nil allows a
  2475. convenient way to select a TODO state and bypass any logging associated
  2476. with that."
  2477. :group 'org-todo
  2478. :type 'boolean)
  2479. (defcustom org-todo-state-tags-triggers nil
  2480. "Tag changes that should be triggered by TODO state changes.
  2481. This is a list. Each entry is
  2482. (state-change (tag . flag) .......)
  2483. State-change can be a string with a state, and empty string to indicate the
  2484. state that has no TODO keyword, or it can be one of the symbols `todo'
  2485. or `done', meaning any not-done or done state, respectively."
  2486. :group 'org-todo
  2487. :group 'org-tags
  2488. :type '(repeat
  2489. (cons (choice :tag "When changing to"
  2490. (const :tag "Not-done state" todo)
  2491. (const :tag "Done state" done)
  2492. (string :tag "State"))
  2493. (repeat
  2494. (cons :tag "Tag action"
  2495. (string :tag "Tag")
  2496. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2497. (defcustom org-log-done nil
  2498. "Information to record when a task moves to the DONE state.
  2499. Possible values are:
  2500. nil Don't add anything, just change the keyword
  2501. time Add a time stamp to the task
  2502. note Prompt for a note and add it with template `org-log-note-headings'
  2503. This option can also be set with on a per-file-basis with
  2504. #+STARTUP: nologdone
  2505. #+STARTUP: logdone
  2506. #+STARTUP: lognotedone
  2507. You can have local logging settings for a subtree by setting the LOGGING
  2508. property to one or more of these keywords."
  2509. :group 'org-todo
  2510. :group 'org-progress
  2511. :type '(choice
  2512. (const :tag "No logging" nil)
  2513. (const :tag "Record CLOSED timestamp" time)
  2514. (const :tag "Record CLOSED timestamp with note." note)))
  2515. ;; Normalize old uses of org-log-done.
  2516. (cond
  2517. ((eq org-log-done t) (setq org-log-done 'time))
  2518. ((and (listp org-log-done) (memq 'done org-log-done))
  2519. (setq org-log-done 'note)))
  2520. (defcustom org-log-reschedule nil
  2521. "Information to record when the scheduling date of a tasks is modified.
  2522. Possible values are:
  2523. nil Don't add anything, just change the date
  2524. time Add a time stamp to the task
  2525. note Prompt for a note and add it with template `org-log-note-headings'
  2526. This option can also be set with on a per-file-basis with
  2527. #+STARTUP: nologreschedule
  2528. #+STARTUP: logreschedule
  2529. #+STARTUP: lognotereschedule"
  2530. :group 'org-todo
  2531. :group 'org-progress
  2532. :type '(choice
  2533. (const :tag "No logging" nil)
  2534. (const :tag "Record timestamp" time)
  2535. (const :tag "Record timestamp with note." note)))
  2536. (defcustom org-log-redeadline nil
  2537. "Information to record when the deadline date of a tasks is modified.
  2538. Possible values are:
  2539. nil Don't add anything, just change the date
  2540. time Add a time stamp to the task
  2541. note Prompt for a note and add it with template `org-log-note-headings'
  2542. This option can also be set with on a per-file-basis with
  2543. #+STARTUP: nologredeadline
  2544. #+STARTUP: logredeadline
  2545. #+STARTUP: lognoteredeadline
  2546. You can have local logging settings for a subtree by setting the LOGGING
  2547. property to one or more of these keywords."
  2548. :group 'org-todo
  2549. :group 'org-progress
  2550. :type '(choice
  2551. (const :tag "No logging" nil)
  2552. (const :tag "Record timestamp" time)
  2553. (const :tag "Record timestamp with note." note)))
  2554. (defcustom org-log-note-clock-out nil
  2555. "Non-nil means record a note when clocking out of an item.
  2556. This can also be configured on a per-file basis by adding one of
  2557. the following lines anywhere in the buffer:
  2558. #+STARTUP: lognoteclock-out
  2559. #+STARTUP: nolognoteclock-out"
  2560. :group 'org-todo
  2561. :group 'org-progress
  2562. :type 'boolean)
  2563. (defcustom org-log-done-with-time t
  2564. "Non-nil means the CLOSED time stamp will contain date and time.
  2565. When nil, only the date will be recorded."
  2566. :group 'org-progress
  2567. :type 'boolean)
  2568. (defcustom org-log-note-headings
  2569. '((done . "CLOSING NOTE %t")
  2570. (state . "State %-12s from %-12S %t")
  2571. (note . "Note taken on %t")
  2572. (reschedule . "Rescheduled from %S on %t")
  2573. (delschedule . "Not scheduled, was %S on %t")
  2574. (redeadline . "New deadline from %S on %t")
  2575. (deldeadline . "Removed deadline, was %S on %t")
  2576. (refile . "Refiled on %t")
  2577. (clock-out . ""))
  2578. "Headings for notes added to entries.
  2579. The value is an alist, with the car being a symbol indicating the
  2580. note context, and the cdr is the heading to be used. The heading
  2581. may also be the empty string. The following placeholders can be
  2582. used:
  2583. %t a time stamp.
  2584. %T an active time stamp instead the default inactive one
  2585. %d a short-format time stamp.
  2586. %D an active short-format time stamp.
  2587. %s the new TODO state or time stamp (inactive), in double quotes.
  2588. %S the old TODO state or time stamp (inactive), in double quotes.
  2589. %u the user name.
  2590. %U full user name.
  2591. In fact, it is not a good idea to change the `state' entry,
  2592. because Agenda Log mode depends on the format of these entries."
  2593. :group 'org-todo
  2594. :group 'org-progress
  2595. :type '(list :greedy t
  2596. (cons (const :tag "Heading when closing an item" done) string)
  2597. (cons (const :tag
  2598. "Heading when changing todo state (todo sequence only)"
  2599. state) string)
  2600. (cons (const :tag "Heading when just taking a note" note) string)
  2601. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2602. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2603. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2604. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2605. (cons (const :tag "Heading when refiling" refile) string)
  2606. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2607. (unless (assq 'note org-log-note-headings)
  2608. (push '(note . "%t") org-log-note-headings))
  2609. (defcustom org-log-into-drawer nil
  2610. "Non-nil means insert state change notes and time stamps into a drawer.
  2611. When nil, state changes notes will be inserted after the headline and
  2612. any scheduling and clock lines, but not inside a drawer.
  2613. The value of this variable should be the name of the drawer to use.
  2614. LOGBOOK is proposed as the default drawer for this purpose, you can
  2615. also set this to a string to define the drawer of your choice.
  2616. A value of t is also allowed, representing \"LOGBOOK\".
  2617. A value of t or nil can also be set with on a per-file-basis with
  2618. #+STARTUP: logdrawer
  2619. #+STARTUP: nologdrawer
  2620. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2621. will be ignored.
  2622. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2623. a subtree.
  2624. Do not check directly this variable in a Lisp program. Call
  2625. function `org-log-into-drawer' instead."
  2626. :group 'org-todo
  2627. :group 'org-progress
  2628. :type '(choice
  2629. (const :tag "Not into a drawer" nil)
  2630. (const :tag "LOGBOOK" t)
  2631. (string :tag "Other")))
  2632. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2633. (defun org-log-into-drawer ()
  2634. "Name of the log drawer, as a string, or nil.
  2635. This is the value of `org-log-into-drawer'. However, if the
  2636. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2637. be used instead of the default value."
  2638. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2639. (cond ((equal p "nil") nil)
  2640. ((equal p "t") "LOGBOOK")
  2641. ((stringp p) p)
  2642. (p "LOGBOOK")
  2643. ((stringp org-log-into-drawer) org-log-into-drawer)
  2644. (org-log-into-drawer "LOGBOOK"))))
  2645. (defcustom org-log-state-notes-insert-after-drawers nil
  2646. "Non-nil means insert state change notes after any drawers in entry.
  2647. Only the drawers that *immediately* follow the headline and the
  2648. deadline/scheduled line are skipped.
  2649. When nil, insert notes right after the heading and perhaps the line
  2650. with deadline/scheduling if present.
  2651. This variable will have no effect if `org-log-into-drawer' is
  2652. set."
  2653. :group 'org-todo
  2654. :group 'org-progress
  2655. :type 'boolean)
  2656. (defcustom org-log-states-order-reversed t
  2657. "Non-nil means the latest state note will be directly after heading.
  2658. When nil, the state change notes will be ordered according to time.
  2659. This option can also be set with on a per-file-basis with
  2660. #+STARTUP: logstatesreversed
  2661. #+STARTUP: nologstatesreversed"
  2662. :group 'org-todo
  2663. :group 'org-progress
  2664. :type 'boolean)
  2665. (defcustom org-todo-repeat-to-state nil
  2666. "The TODO state to which a repeater should return the repeating task.
  2667. By default this is the first task in a TODO sequence, or the previous state
  2668. in a TODO_TYP set. But you can specify another task here.
  2669. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2670. :group 'org-todo
  2671. :version "24.1"
  2672. :type '(choice (const :tag "Head of sequence" nil)
  2673. (string :tag "Specific state")))
  2674. (defcustom org-log-repeat 'time
  2675. "Non-nil means record moving through the DONE state when triggering repeat.
  2676. An auto-repeating task is immediately switched back to TODO when
  2677. marked DONE. If you are not logging state changes (by adding \"@\"
  2678. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2679. record a closing note, there will be no record of the task moving
  2680. through DONE. This variable forces taking a note anyway.
  2681. nil Don't force a record
  2682. time Record a time stamp
  2683. note Prompt for a note and add it with template `org-log-note-headings'
  2684. This option can also be set with on a per-file-basis with
  2685. #+STARTUP: nologrepeat
  2686. #+STARTUP: logrepeat
  2687. #+STARTUP: lognoterepeat
  2688. You can have local logging settings for a subtree by setting the LOGGING
  2689. property to one or more of these keywords."
  2690. :group 'org-todo
  2691. :group 'org-progress
  2692. :type '(choice
  2693. (const :tag "Don't force a record" nil)
  2694. (const :tag "Force recording the DONE state" time)
  2695. (const :tag "Force recording a note with the DONE state" note)))
  2696. (defgroup org-priorities nil
  2697. "Priorities in Org mode."
  2698. :tag "Org Priorities"
  2699. :group 'org-todo)
  2700. (defcustom org-enable-priority-commands t
  2701. "Non-nil means priority commands are active.
  2702. When nil, these commands will be disabled, so that you never accidentally
  2703. set a priority."
  2704. :group 'org-priorities
  2705. :type 'boolean)
  2706. (defcustom org-highest-priority ?A
  2707. "The highest priority of TODO items. A character like ?A, ?B etc.
  2708. Must have a smaller ASCII number than `org-lowest-priority'."
  2709. :group 'org-priorities
  2710. :type 'character)
  2711. (defcustom org-lowest-priority ?C
  2712. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2713. Must have a larger ASCII number than `org-highest-priority'."
  2714. :group 'org-priorities
  2715. :type 'character)
  2716. (defcustom org-default-priority ?B
  2717. "The default priority of TODO items.
  2718. This is the priority an item gets if no explicit priority is given.
  2719. When starting to cycle on an empty priority the first step in the cycle
  2720. depends on `org-priority-start-cycle-with-default'. The resulting first
  2721. step priority must not exceed the range from `org-highest-priority' to
  2722. `org-lowest-priority' which means that `org-default-priority' has to be
  2723. in this range exclusive or inclusive the range boundaries. Else the
  2724. first step refuses to set the default and the second will fall back
  2725. to (depending on the command used) the highest or lowest priority."
  2726. :group 'org-priorities
  2727. :type 'character)
  2728. (defcustom org-priority-start-cycle-with-default t
  2729. "Non-nil means start with default priority when starting to cycle.
  2730. When this is nil, the first step in the cycle will be (depending on the
  2731. command used) one higher or lower than the default priority.
  2732. See also `org-default-priority'."
  2733. :group 'org-priorities
  2734. :type 'boolean)
  2735. (defcustom org-get-priority-function nil
  2736. "Function to extract the priority from a string.
  2737. The string is normally the headline. If this is nil Org computes the
  2738. priority from the priority cookie like [#A] in the headline. It returns
  2739. an integer, increasing by 1000 for each priority level.
  2740. The user can set a different function here, which should take a string
  2741. as an argument and return the numeric priority."
  2742. :group 'org-priorities
  2743. :version "24.1"
  2744. :type '(choice
  2745. (const nil)
  2746. (function)))
  2747. (defgroup org-time nil
  2748. "Options concerning time stamps and deadlines in Org mode."
  2749. :tag "Org Time"
  2750. :group 'org)
  2751. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2752. "Number of minutes to round time stamps to.
  2753. \\<org-mode-map>\
  2754. These are two values, the first applies when first creating a time stamp.
  2755. The second applies when changing it with the commands `S-up' and `S-down'.
  2756. When changing the time stamp, this means that it will change in steps
  2757. of N minutes, as given by the second value.
  2758. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2759. numbers should be factors of 60, so for example 5, 10, 15.
  2760. When this is larger than 1, you can still force an exact time stamp by using
  2761. a double prefix argument to a time stamp command like \
  2762. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2763. and by using a prefix arg to `S-up/down' to specify the exact number
  2764. of minutes to shift."
  2765. :group 'org-time
  2766. :get (lambda (var) ; Make sure both elements are there
  2767. (if (integerp (default-value var))
  2768. (list (default-value var) 5)
  2769. (default-value var)))
  2770. :type '(list
  2771. (integer :tag "when inserting times")
  2772. (integer :tag "when modifying times")))
  2773. ;; Normalize old customizations of this variable.
  2774. (when (integerp org-time-stamp-rounding-minutes)
  2775. (setq org-time-stamp-rounding-minutes
  2776. (list org-time-stamp-rounding-minutes
  2777. org-time-stamp-rounding-minutes)))
  2778. (defcustom org-display-custom-times nil
  2779. "Non-nil means overlay custom formats over all time stamps.
  2780. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2781. To turn this on on a per-file basis, insert anywhere in the file:
  2782. #+STARTUP: customtime"
  2783. :group 'org-time
  2784. :set 'set-default
  2785. :type 'sexp)
  2786. (make-variable-buffer-local 'org-display-custom-times)
  2787. (defcustom org-time-stamp-custom-formats
  2788. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2789. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2790. These are overlaid over the default ISO format if the variable
  2791. `org-display-custom-times' is set. Time like %H:%M should be at the
  2792. end of the second format. The custom formats are also honored by export
  2793. commands, if custom time display is turned on at the time of export."
  2794. :group 'org-time
  2795. :type 'sexp)
  2796. (defun org-time-stamp-format (&optional long inactive)
  2797. "Get the right format for a time string."
  2798. (let ((f (if long (cdr org-time-stamp-formats)
  2799. (car org-time-stamp-formats))))
  2800. (if inactive
  2801. (concat "[" (substring f 1 -1) "]")
  2802. f)))
  2803. (defcustom org-deadline-warning-days 14
  2804. "Number of days before expiration during which a deadline becomes active.
  2805. This variable governs the display in sparse trees and in the agenda.
  2806. When 0 or negative, it means use this number (the absolute value of it)
  2807. even if a deadline has a different individual lead time specified.
  2808. Custom commands can set this variable in the options section."
  2809. :group 'org-time
  2810. :group 'org-agenda-daily/weekly
  2811. :type 'integer)
  2812. (defcustom org-scheduled-delay-days 0
  2813. "Number of days before a scheduled item becomes active.
  2814. This variable governs the display in sparse trees and in the agenda.
  2815. The default value (i.e. 0) means: don't delay scheduled item.
  2816. When negative, it means use this number (the absolute value of it)
  2817. even if a scheduled item has a different individual delay time
  2818. specified.
  2819. Custom commands can set this variable in the options section."
  2820. :group 'org-time
  2821. :group 'org-agenda-daily/weekly
  2822. :version "24.4"
  2823. :package-version '(Org . "8.0")
  2824. :type 'integer)
  2825. (defcustom org-read-date-prefer-future t
  2826. "Non-nil means assume future for incomplete date input from user.
  2827. This affects the following situations:
  2828. 1. The user gives a month but not a year.
  2829. For example, if it is April and you enter \"feb 2\", this will be read
  2830. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2831. 2. The user gives a day, but no month.
  2832. For example, if today is the 15th, and you enter \"3\", Org will read
  2833. this as the third of *next* month. However, if you enter \"17\",
  2834. it will be considered as *this* month.
  2835. If you set this variable to the symbol `time', then also the following
  2836. will work:
  2837. 3. If the user gives a time.
  2838. If the time is before now, it will be interpreted as tomorrow.
  2839. Currently none of this works for ISO week specifications.
  2840. When this option is nil, the current day, month and year will always be
  2841. used as defaults.
  2842. See also `org-agenda-jump-prefer-future'."
  2843. :group 'org-time
  2844. :type '(choice
  2845. (const :tag "Never" nil)
  2846. (const :tag "Check month and day" t)
  2847. (const :tag "Check month, day, and time" time)))
  2848. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2849. "Should the agenda jump command prefer the future for incomplete dates?
  2850. The default is to do the same as configured in `org-read-date-prefer-future'.
  2851. But you can also set a deviating value here.
  2852. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2853. :group 'org-agenda
  2854. :group 'org-time
  2855. :version "24.1"
  2856. :type '(choice
  2857. (const :tag "Use org-read-date-prefer-future"
  2858. org-read-date-prefer-future)
  2859. (const :tag "Never" nil)
  2860. (const :tag "Always" t)))
  2861. (defcustom org-read-date-force-compatible-dates t
  2862. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2863. Depending on the system Emacs is running on, certain dates cannot
  2864. be represented with the type used internally to represent time.
  2865. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2866. correctly. Some systems allow for earlier dates, some for later,
  2867. some for both. One way to find out it to insert any date into an
  2868. Org buffer, putting the cursor on the year and hitting S-up and
  2869. S-down to test the range.
  2870. When this variable is set to t, the date/time prompt will not let
  2871. you specify dates outside the 1970-2037 range, so it is certain that
  2872. these dates will work in whatever version of Emacs you are
  2873. running, and also that you can move a file from one Emacs implementation
  2874. to another. WHenever Org is forcing the year for you, it will display
  2875. a message and beep.
  2876. When this variable is nil, Org will check if the date is
  2877. representable in the specific Emacs implementation you are using.
  2878. If not, it will force a year, usually the current year, and beep
  2879. to remind you. Currently this setting is not recommended because
  2880. the likelihood that you will open your Org files in an Emacs that
  2881. has limited date range is not negligible.
  2882. A workaround for this problem is to use diary sexp dates for time
  2883. stamps outside of this range."
  2884. :group 'org-time
  2885. :version "24.1"
  2886. :type 'boolean)
  2887. (defcustom org-read-date-display-live t
  2888. "Non-nil means display current interpretation of date prompt live.
  2889. This display will be in an overlay, in the minibuffer."
  2890. :group 'org-time
  2891. :type 'boolean)
  2892. (defcustom org-read-date-popup-calendar t
  2893. "Non-nil means pop up a calendar when prompting for a date.
  2894. In the calendar, the date can be selected with mouse-1. However, the
  2895. minibuffer will also be active, and you can simply enter the date as well.
  2896. When nil, only the minibuffer will be available."
  2897. :group 'org-time
  2898. :type 'boolean)
  2899. (defvaralias 'org-popup-calendar-for-date-prompt
  2900. 'org-read-date-popup-calendar)
  2901. (defcustom org-extend-today-until 0
  2902. "The hour when your day really ends. Must be an integer.
  2903. This has influence for the following applications:
  2904. - When switching the agenda to \"today\". It it is still earlier than
  2905. the time given here, the day recognized as TODAY is actually yesterday.
  2906. - When a date is read from the user and it is still before the time given
  2907. here, the current date and time will be assumed to be yesterday, 23:59.
  2908. Also, timestamps inserted in capture templates follow this rule.
  2909. IMPORTANT: This is a feature whose implementation is and likely will
  2910. remain incomplete. Really, it is only here because past midnight seems to
  2911. be the favorite working time of John Wiegley :-)"
  2912. :group 'org-time
  2913. :type 'integer)
  2914. (defcustom org-use-effective-time nil
  2915. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2916. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2917. \"effective time\" of any timestamps between midnight and 8am will be
  2918. 23:59 of the previous day."
  2919. :group 'org-time
  2920. :version "24.1"
  2921. :type 'boolean)
  2922. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2923. "When non-nil, use the last clock out time for `org-todo'.
  2924. Note that this option has precedence over the combined use of
  2925. `org-use-effective-time' and `org-extend-today-until'."
  2926. :group 'org-time
  2927. :version "24.4"
  2928. :package-version '(Org . "8.0")
  2929. :type 'boolean)
  2930. (defcustom org-edit-timestamp-down-means-later nil
  2931. "Non-nil means S-down will increase the time in a time stamp.
  2932. When nil, S-up will increase."
  2933. :group 'org-time
  2934. :type 'boolean)
  2935. (defcustom org-calendar-follow-timestamp-change t
  2936. "Non-nil means make the calendar window follow timestamp changes.
  2937. When a timestamp is modified and the calendar window is visible, it will be
  2938. moved to the new date."
  2939. :group 'org-time
  2940. :type 'boolean)
  2941. (defgroup org-tags nil
  2942. "Options concerning tags in Org mode."
  2943. :tag "Org Tags"
  2944. :group 'org)
  2945. (defcustom org-tag-alist nil
  2946. "Default tags available in Org files.
  2947. The value of this variable is an alist. Associations either:
  2948. (TAG)
  2949. (TAG . SELECT)
  2950. (SPECIAL)
  2951. where TAG is a tag as a string, SELECT is character, used to
  2952. select that tag through the fast tag selection interface, and
  2953. SPECIAL is one of the following keywords: `:startgroup',
  2954. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2955. `:newline'. These keywords are used to define a hierarchy of
  2956. tags. See manual for details.
  2957. When this variable is nil, Org mode bases tag input on what is
  2958. already in the buffer. The value can be overridden locally by
  2959. using a TAGS keyword, e.g.,
  2960. #+TAGS: tag1 tag2
  2961. See also `org-tag-persistent-alist' to sidestep this behavior."
  2962. :group 'org-tags
  2963. :type '(repeat
  2964. (choice
  2965. (cons (string :tag "Tag name")
  2966. (character :tag "Access char"))
  2967. (const :tag "Start radio group" (:startgroup))
  2968. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2969. (const :tag "Group tags delimiter" (:grouptags))
  2970. (const :tag "End radio group" (:endgroup))
  2971. (const :tag "End tag group, non distinct" (:endgrouptag))
  2972. (const :tag "New line" (:newline)))))
  2973. (defcustom org-tag-persistent-alist nil
  2974. "Tags always available in Org files.
  2975. The value of this variable is an alist. Associations either:
  2976. (TAG)
  2977. (TAG . SELECT)
  2978. (SPECIAL)
  2979. where TAG is a tag as a string, SELECT is a character, used to
  2980. select that tag through the fast tag selection interface, and
  2981. SPECIAL is one of the following keywords: `:startgroup',
  2982. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  2983. `:newline'. These keywords are used to define a hierarchy of
  2984. tags. See manual for details.
  2985. Unlike to `org-tag-alist', tags defined in this variable do not
  2986. depend on a local TAGS keyword. Instead, to disable these tags
  2987. on a per-file basis, insert anywhere in the file:
  2988. #+STARTUP: noptag"
  2989. :group 'org-tags
  2990. :type '(repeat
  2991. (choice
  2992. (cons (string :tag "Tag name")
  2993. (character :tag "Access char"))
  2994. (const :tag "Start radio group" (:startgroup))
  2995. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2996. (const :tag "Group tags delimiter" (:grouptags))
  2997. (const :tag "End radio group" (:endgroup))
  2998. (const :tag "End tag group, non distinct" (:endgrouptag))
  2999. (const :tag "New line" (:newline)))))
  3000. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3001. "If non-nil, always offer completion for all tags of all agenda files.
  3002. Instead of customizing this variable directly, you might want to
  3003. set it locally for capture buffers, because there no list of
  3004. tags in that file can be created dynamically (there are none).
  3005. (add-hook \\='org-capture-mode-hook
  3006. (lambda ()
  3007. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3008. :group 'org-tags
  3009. :version "24.1"
  3010. :type 'boolean)
  3011. (defvar org-file-tags nil
  3012. "List of tags that can be inherited by all entries in the file.
  3013. The tags will be inherited if the variable `org-use-tag-inheritance'
  3014. says they should be.
  3015. This variable is populated from #+FILETAGS lines.")
  3016. (defcustom org-use-fast-tag-selection 'auto
  3017. "Non-nil means use fast tag selection scheme.
  3018. This is a special interface to select and deselect tags with single keys.
  3019. When nil, fast selection is never used.
  3020. When the symbol `auto', fast selection is used if and only if selection
  3021. characters for tags have been configured, either through the variable
  3022. `org-tag-alist' or through a #+TAGS line in the buffer.
  3023. When t, fast selection is always used and selection keys are assigned
  3024. automatically if necessary."
  3025. :group 'org-tags
  3026. :type '(choice
  3027. (const :tag "Always" t)
  3028. (const :tag "Never" nil)
  3029. (const :tag "When selection characters are configured" auto)))
  3030. (defcustom org-fast-tag-selection-single-key nil
  3031. "Non-nil means fast tag selection exits after first change.
  3032. When nil, you have to press RET to exit it.
  3033. During fast tag selection, you can toggle this flag with `C-c'.
  3034. This variable can also have the value `expert'. In this case, the window
  3035. displaying the tags menu is not even shown, until you press C-c again."
  3036. :group 'org-tags
  3037. :type '(choice
  3038. (const :tag "No" nil)
  3039. (const :tag "Yes" t)
  3040. (const :tag "Expert" expert)))
  3041. (defvar org-fast-tag-selection-include-todo nil
  3042. "Non-nil means fast tags selection interface will also offer TODO states.
  3043. This is an undocumented feature, you should not rely on it.")
  3044. (defcustom org-tags-column -77
  3045. "The column to which tags should be indented in a headline.
  3046. If this number is positive, it specifies the column. If it is negative,
  3047. it means that the tags should be flushright to that column. For example,
  3048. -80 works well for a normal 80 character screen.
  3049. When 0, place tags directly after headline text, with only one space in
  3050. between."
  3051. :group 'org-tags
  3052. :type 'integer)
  3053. (defcustom org-auto-align-tags t
  3054. "Non-nil keeps tags aligned when modifying headlines.
  3055. Some operations (i.e. demoting) change the length of a headline and
  3056. therefore shift the tags around. With this option turned on, after
  3057. each such operation the tags are again aligned to `org-tags-column'."
  3058. :group 'org-tags
  3059. :type 'boolean)
  3060. (defcustom org-use-tag-inheritance t
  3061. "Non-nil means tags in levels apply also for sublevels.
  3062. When nil, only the tags directly given in a specific line apply there.
  3063. This may also be a list of tags that should be inherited, or a regexp that
  3064. matches tags that should be inherited. Additional control is possible
  3065. with the variable `org-tags-exclude-from-inheritance' which gives an
  3066. explicit list of tags to be excluded from inheritance, even if the value of
  3067. `org-use-tag-inheritance' would select it for inheritance.
  3068. If this option is t, a match early-on in a tree can lead to a large
  3069. number of matches in the subtree when constructing the agenda or creating
  3070. a sparse tree. If you only want to see the first match in a tree during
  3071. a search, check out the variable `org-tags-match-list-sublevels'."
  3072. :group 'org-tags
  3073. :type '(choice
  3074. (const :tag "Not" nil)
  3075. (const :tag "Always" t)
  3076. (repeat :tag "Specific tags" (string :tag "Tag"))
  3077. (regexp :tag "Tags matched by regexp")))
  3078. (defcustom org-tags-exclude-from-inheritance nil
  3079. "List of tags that should never be inherited.
  3080. This is a way to exclude a few tags from inheritance. For way to do
  3081. the opposite, to actively allow inheritance for selected tags,
  3082. see the variable `org-use-tag-inheritance'."
  3083. :group 'org-tags
  3084. :type '(repeat (string :tag "Tag")))
  3085. (defun org-tag-inherit-p (tag)
  3086. "Check if TAG is one that should be inherited."
  3087. (cond
  3088. ((member tag org-tags-exclude-from-inheritance) nil)
  3089. ((eq org-use-tag-inheritance t) t)
  3090. ((not org-use-tag-inheritance) nil)
  3091. ((stringp org-use-tag-inheritance)
  3092. (string-match org-use-tag-inheritance tag))
  3093. ((listp org-use-tag-inheritance)
  3094. (member tag org-use-tag-inheritance))
  3095. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3096. (defcustom org-tags-match-list-sublevels t
  3097. "Non-nil means list also sublevels of headlines matching a search.
  3098. This variable applies to tags/property searches, and also to stuck
  3099. projects because this search is based on a tags match as well.
  3100. When set to the symbol `indented', sublevels are indented with
  3101. leading dots.
  3102. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3103. the sublevels of a headline matching a tag search often also match
  3104. the same search. Listing all of them can create very long lists.
  3105. Setting this variable to nil causes subtrees of a match to be skipped.
  3106. This variable is semi-obsolete and probably should always be true. It
  3107. is better to limit inheritance to certain tags using the variables
  3108. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3109. :group 'org-tags
  3110. :type '(choice
  3111. (const :tag "No, don't list them" nil)
  3112. (const :tag "Yes, do list them" t)
  3113. (const :tag "List them, indented with leading dots" indented)))
  3114. (defcustom org-tags-sort-function nil
  3115. "When set, tags are sorted using this function as a comparator."
  3116. :group 'org-tags
  3117. :type '(choice
  3118. (const :tag "No sorting" nil)
  3119. (const :tag "Alphabetical" string<)
  3120. (const :tag "Reverse alphabetical" string>)
  3121. (function :tag "Custom function" nil)))
  3122. (defvar org-tags-history nil
  3123. "History of minibuffer reads for tags.")
  3124. (defvar org-last-tags-completion-table nil
  3125. "The last used completion table for tags.")
  3126. (defvar org-after-tags-change-hook nil
  3127. "Hook that is run after the tags in a line have changed.")
  3128. (defgroup org-properties nil
  3129. "Options concerning properties in Org mode."
  3130. :tag "Org Properties"
  3131. :group 'org)
  3132. (defcustom org-property-format "%-10s %s"
  3133. "How property key/value pairs should be formatted by `indent-line'.
  3134. When `indent-line' hits a property definition, it will format the line
  3135. according to this format, mainly to make sure that the values are
  3136. lined-up with respect to each other."
  3137. :group 'org-properties
  3138. :type 'string)
  3139. (defcustom org-properties-postprocess-alist nil
  3140. "Alist of properties and functions to adjust inserted values.
  3141. Elements of this alist must be of the form
  3142. ([string] [function])
  3143. where [string] must be a property name and [function] must be a
  3144. lambda expression: this lambda expression must take one argument,
  3145. the value to adjust, and return the new value as a string.
  3146. For example, this element will allow the property \"Remaining\"
  3147. to be updated wrt the relation between the \"Effort\" property
  3148. and the clock summary:
  3149. ((\"Remaining\" (lambda(value)
  3150. (let ((clocksum (org-clock-sum-current-item))
  3151. (effort (org-duration-to-minutes
  3152. (org-entry-get (point) \"Effort\"))))
  3153. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3154. :group 'org-properties
  3155. :version "24.1"
  3156. :type '(alist :key-type (string :tag "Property")
  3157. :value-type (function :tag "Function")))
  3158. (defcustom org-use-property-inheritance nil
  3159. "Non-nil means properties apply also for sublevels.
  3160. This setting is chiefly used during property searches. Turning it on can
  3161. cause significant overhead when doing a search, which is why it is not
  3162. on by default.
  3163. When nil, only the properties directly given in the current entry count.
  3164. When t, every property is inherited. The value may also be a list of
  3165. properties that should have inheritance, or a regular expression matching
  3166. properties that should be inherited.
  3167. However, note that some special properties use inheritance under special
  3168. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3169. and the properties ending in \"_ALL\" when they are used as descriptor
  3170. for valid values of a property.
  3171. Note for programmers:
  3172. When querying an entry with `org-entry-get', you can control if inheritance
  3173. should be used. By default, `org-entry-get' looks only at the local
  3174. properties. You can request inheritance by setting the inherit argument
  3175. to t (to force inheritance) or to `selective' (to respect the setting
  3176. in this variable)."
  3177. :group 'org-properties
  3178. :type '(choice
  3179. (const :tag "Not" nil)
  3180. (const :tag "Always" t)
  3181. (repeat :tag "Specific properties" (string :tag "Property"))
  3182. (regexp :tag "Properties matched by regexp")))
  3183. (defun org-property-inherit-p (property)
  3184. "Return a non-nil value if PROPERTY should be inherited."
  3185. (cond
  3186. ((eq org-use-property-inheritance t) t)
  3187. ((not org-use-property-inheritance) nil)
  3188. ((stringp org-use-property-inheritance)
  3189. (string-match org-use-property-inheritance property))
  3190. ((listp org-use-property-inheritance)
  3191. (member-ignore-case property org-use-property-inheritance))
  3192. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3193. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3194. "The default column format, if no other format has been defined.
  3195. This variable can be set on the per-file basis by inserting a line
  3196. #+COLUMNS: %25ITEM ....."
  3197. :group 'org-properties
  3198. :type 'string)
  3199. (defcustom org-columns-ellipses ".."
  3200. "The ellipses to be used when a field in column view is truncated.
  3201. When this is the empty string, as many characters as possible are shown,
  3202. but then there will be no visual indication that the field has been truncated.
  3203. When this is a string of length N, the last N characters of a truncated
  3204. field are replaced by this string. If the column is narrower than the
  3205. ellipses string, only part of the ellipses string will be shown."
  3206. :group 'org-properties
  3207. :type 'string)
  3208. (defconst org-global-properties-fixed
  3209. '(("VISIBILITY_ALL" . "folded children content all")
  3210. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3211. "List of property/value pairs that can be inherited by any entry.
  3212. These are fixed values, for the preset properties. The user variable
  3213. that can be used to add to this list is `org-global-properties'.
  3214. The entries in this list are cons cells where the car is a property
  3215. name and cdr is a string with the value. If the value represents
  3216. multiple items like an \"_ALL\" property, separate the items by
  3217. spaces.")
  3218. (defcustom org-global-properties nil
  3219. "List of property/value pairs that can be inherited by any entry.
  3220. This list will be combined with the constant `org-global-properties-fixed'.
  3221. The entries in this list are cons cells where the car is a property
  3222. name and cdr is a string with the value.
  3223. You can set buffer-local values for the same purpose in the variable
  3224. `org-file-properties' this by adding lines like
  3225. #+PROPERTY: NAME VALUE"
  3226. :group 'org-properties
  3227. :type '(repeat
  3228. (cons (string :tag "Property")
  3229. (string :tag "Value"))))
  3230. (defvar-local org-file-properties nil
  3231. "List of property/value pairs that can be inherited by any entry.
  3232. Valid for the current buffer.
  3233. This variable is populated from #+PROPERTY lines.")
  3234. (defgroup org-agenda nil
  3235. "Options concerning agenda views in Org mode."
  3236. :tag "Org Agenda"
  3237. :group 'org)
  3238. (defvar-local org-category nil
  3239. "Variable used by org files to set a category for agenda display.
  3240. Such files should use a file variable to set it, for example
  3241. # -*- mode: org; org-category: \"ELisp\"
  3242. or contain a special line
  3243. #+CATEGORY: ELisp
  3244. If the file does not specify a category, then file's base name
  3245. is used instead.")
  3246. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3247. (defcustom org-agenda-files nil
  3248. "The files to be used for agenda display.
  3249. If an entry is a directory, all files in that directory that are matched
  3250. by `org-agenda-file-regexp' will be part of the file list.
  3251. If the value of the variable is not a list but a single file name, then
  3252. the list of agenda files is actually stored and maintained in that file,
  3253. one agenda file per line. In this file paths can be given relative to
  3254. `org-directory'. Tilde expansion and environment variable substitution
  3255. are also made.
  3256. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3257. and removed with `\\[org-remove-file]'."
  3258. :group 'org-agenda
  3259. :type '(choice
  3260. (repeat :tag "List of files and directories" file)
  3261. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3262. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3263. "Regular expression to match files for `org-agenda-files'.
  3264. If any element in the list in that variable contains a directory instead
  3265. of a normal file, all files in that directory that are matched by this
  3266. regular expression will be included."
  3267. :group 'org-agenda
  3268. :type 'regexp)
  3269. (defcustom org-agenda-text-search-extra-files nil
  3270. "List of extra files to be searched by text search commands.
  3271. These files will be searched in addition to the agenda files by the
  3272. commands `org-search-view' (`\\[org-agenda] s') \
  3273. and `org-occur-in-agenda-files'.
  3274. Note that these files will only be searched for text search commands,
  3275. not for the other agenda views like todo lists, tag searches or the weekly
  3276. agenda. This variable is intended to list notes and possibly archive files
  3277. that should also be searched by these two commands.
  3278. In fact, if the first element in the list is the symbol `agenda-archives',
  3279. then all archive files of all agenda files will be added to the search
  3280. scope."
  3281. :group 'org-agenda
  3282. :type '(set :greedy t
  3283. (const :tag "Agenda Archives" agenda-archives)
  3284. (repeat :inline t (file))))
  3285. (defvaralias 'org-agenda-multi-occur-extra-files
  3286. 'org-agenda-text-search-extra-files)
  3287. (defcustom org-agenda-skip-unavailable-files nil
  3288. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3289. A nil value means to remove them, after a query, from the list."
  3290. :group 'org-agenda
  3291. :type 'boolean)
  3292. (defcustom org-calendar-to-agenda-key [?c]
  3293. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3294. The command `org-calendar-goto-agenda' will be bound to this key. The
  3295. default is the character `c' because then `c' can be used to switch back and
  3296. forth between agenda and calendar."
  3297. :group 'org-agenda
  3298. :type 'sexp)
  3299. (defcustom org-calendar-insert-diary-entry-key [?i]
  3300. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3301. This option is irrelevant until `org-agenda-diary-file' has been configured
  3302. to point to an Org file. When that is the case, the command
  3303. `org-agenda-diary-entry' will be bound to the key given here, by default
  3304. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3305. if you want to continue doing this, you need to change this to a different
  3306. key."
  3307. :group 'org-agenda
  3308. :type 'sexp)
  3309. (defcustom org-agenda-diary-file 'diary-file
  3310. "File to which to add new entries with the `i' key in agenda and calendar.
  3311. When this is the symbol `diary-file', the functionality in the Emacs
  3312. calendar will be used to add entries to the `diary-file'. But when this
  3313. points to a file, `org-agenda-diary-entry' will be used instead."
  3314. :group 'org-agenda
  3315. :type '(choice
  3316. (const :tag "The standard Emacs diary file" diary-file)
  3317. (file :tag "Special Org file diary entries")))
  3318. (eval-after-load "calendar"
  3319. '(progn
  3320. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3321. 'org-calendar-goto-agenda)
  3322. (add-hook 'calendar-mode-hook
  3323. (lambda ()
  3324. (unless (eq org-agenda-diary-file 'diary-file)
  3325. (define-key calendar-mode-map
  3326. org-calendar-insert-diary-entry-key
  3327. 'org-agenda-diary-entry))))))
  3328. (defgroup org-latex nil
  3329. "Options for embedding LaTeX code into Org mode."
  3330. :tag "Org LaTeX"
  3331. :group 'org)
  3332. (defcustom org-format-latex-options
  3333. '(:foreground default :background default :scale 1.0
  3334. :html-foreground "Black" :html-background "Transparent"
  3335. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3336. "Options for creating images from LaTeX fragments.
  3337. This is a property list with the following properties:
  3338. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3339. `default' means use the foreground of the default face.
  3340. `auto' means use the foreground from the text face.
  3341. :background the background color, or \"Transparent\".
  3342. `default' means use the background of the default face.
  3343. `auto' means use the background from the text face.
  3344. :scale a scaling factor for the size of the images, to get more pixels
  3345. :html-foreground, :html-background, :html-scale
  3346. the same numbers for HTML export.
  3347. :matchers a list indicating which matchers should be used to
  3348. find LaTeX fragments. Valid members of this list are:
  3349. \"begin\" find environments
  3350. \"$1\" find single characters surrounded by $.$
  3351. \"$\" find math expressions surrounded by $...$
  3352. \"$$\" find math expressions surrounded by $$....$$
  3353. \"\\(\" find math expressions surrounded by \\(...\\)
  3354. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3355. :group 'org-latex
  3356. :type 'plist)
  3357. (defcustom org-format-latex-signal-error t
  3358. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3359. When nil, just push out a message."
  3360. :group 'org-latex
  3361. :version "24.1"
  3362. :type 'boolean)
  3363. (defcustom org-latex-to-mathml-jar-file nil
  3364. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3365. Use this to specify additional executable file say a jar file.
  3366. When using MathToWeb as the converter, specify the full-path to
  3367. your mathtoweb.jar file."
  3368. :group 'org-latex
  3369. :version "24.1"
  3370. :type '(choice
  3371. (const :tag "None" nil)
  3372. (file :tag "JAR file" :must-match t)))
  3373. (defcustom org-latex-to-mathml-convert-command nil
  3374. "Command to convert LaTeX fragments to MathML.
  3375. Replace format-specifiers in the command as noted below and use
  3376. `shell-command' to convert LaTeX to MathML.
  3377. %j: Executable file in fully expanded form as specified by
  3378. `org-latex-to-mathml-jar-file'.
  3379. %I: Input LaTeX file in fully expanded form.
  3380. %i: The latex fragment to be converted.
  3381. %o: Output MathML file.
  3382. This command is used by `org-create-math-formula'.
  3383. When using MathToWeb as the converter, set this option to
  3384. \"java -jar %j -unicode -force -df %o %I\".
  3385. When using LaTeXML set this option to
  3386. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3387. :group 'org-latex
  3388. :version "24.1"
  3389. :type '(choice
  3390. (const :tag "None" nil)
  3391. (string :tag "\nShell command")))
  3392. (defcustom org-preview-latex-default-process 'dvipng
  3393. "The default process to convert LaTeX fragments to image files.
  3394. All available processes and theirs documents can be found in
  3395. `org-preview-latex-process-alist', which see."
  3396. :group 'org-latex
  3397. :version "26.1"
  3398. :package-version '(Org . "9.0")
  3399. :type 'symbol)
  3400. (defcustom org-preview-latex-process-alist
  3401. '((dvipng
  3402. :programs ("latex" "dvipng")
  3403. :description "dvi > png"
  3404. :message "you need to install the programs: latex and dvipng."
  3405. :image-input-type "dvi"
  3406. :image-output-type "png"
  3407. :image-size-adjust (1.0 . 1.0)
  3408. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3409. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3410. (dvisvgm
  3411. :programs ("latex" "dvisvgm")
  3412. :description "dvi > svg"
  3413. :message "you need to install the programs: latex and dvisvgm."
  3414. :use-xcolor t
  3415. :image-input-type "dvi"
  3416. :image-output-type "svg"
  3417. :image-size-adjust (1.7 . 1.5)
  3418. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3419. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3420. (imagemagick
  3421. :programs ("latex" "convert")
  3422. :description "pdf > png"
  3423. :message "you need to install the programs: latex and imagemagick."
  3424. :use-xcolor t
  3425. :image-input-type "pdf"
  3426. :image-output-type "png"
  3427. :image-size-adjust (1.0 . 1.0)
  3428. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3429. :image-converter
  3430. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3431. "Definitions of external processes for LaTeX previewing.
  3432. Org mode can use some external commands to generate TeX snippet's images for
  3433. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3434. `org-create-formula-image' how to call them.
  3435. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3436. PROPERTIES accepts the following attributes:
  3437. :programs list of strings, required programs.
  3438. :description string, describe the process.
  3439. :message string, message it when required programs cannot be found.
  3440. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3441. :image-output-type string, output file type of image converter (e.g., \"png\").
  3442. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3443. deal with background and foreground color of image.
  3444. Otherwise, dvipng style background and foregroud color
  3445. format are generated. You may then refer to them in
  3446. command options with \"%F\" and \"%B\".
  3447. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3448. image size showed in buffer and the cdr element is for
  3449. HTML file. This option is only useful for process
  3450. developers, users should use variable
  3451. `org-format-latex-options' instead.
  3452. :post-clean list of strings, files matched are to be cleaned up once
  3453. the image is generated. When nil, the files with \".dvi\",
  3454. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3455. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3456. be cleaned up.
  3457. :latex-header list of strings, the LaTeX header of the snippet file.
  3458. When nil, the fallback value is used instead, which is
  3459. controlled by `org-format-latex-header',
  3460. `org-latex-default-packages-alist' and
  3461. `org-latex-packages-alist', which see.
  3462. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3463. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3464. replaced with values defined below.
  3465. :image-converter list of image converter commands strings. Each of them is
  3466. given to the shell and supports any of the following
  3467. place-holders defined below.
  3468. Place-holders used by `:image-converter' and `:latex-compiler':
  3469. %f input file name
  3470. %b base name of input file
  3471. %o base directory of input file
  3472. %O absolute output file name
  3473. Place-holders only used by `:image-converter':
  3474. %F foreground of image
  3475. %B background of image
  3476. %D dpi, which is used to adjust image size by some processing commands.
  3477. %S the image size scale ratio, which is used to adjust image size by some
  3478. processing commands."
  3479. :group 'org-latex
  3480. :version "26.1"
  3481. :package-version '(Org . "9.0")
  3482. :type '(alist :tag "LaTeX to image backends"
  3483. :value-type (plist)))
  3484. (defcustom org-preview-latex-image-directory "ltximg/"
  3485. "Path to store latex preview images.
  3486. A relative path here creates many directories relative to the
  3487. processed org files paths. An absolute path puts all preview
  3488. images at the same place."
  3489. :group 'org-latex
  3490. :version "26.1"
  3491. :package-version '(Org . "9.0")
  3492. :type 'string)
  3493. (defun org-format-latex-mathml-available-p ()
  3494. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3495. (save-match-data
  3496. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3497. org-latex-to-mathml-convert-command)
  3498. (let ((executable (car (split-string
  3499. org-latex-to-mathml-convert-command))))
  3500. (when (executable-find executable)
  3501. (if (string-match
  3502. "%j" org-latex-to-mathml-convert-command)
  3503. (file-readable-p org-latex-to-mathml-jar-file)
  3504. t))))))
  3505. (defcustom org-format-latex-header "\\documentclass{article}
  3506. \\usepackage[usenames]{color}
  3507. \[PACKAGES]
  3508. \[DEFAULT-PACKAGES]
  3509. \\pagestyle{empty} % do not remove
  3510. % The settings below are copied from fullpage.sty
  3511. \\setlength{\\textwidth}{\\paperwidth}
  3512. \\addtolength{\\textwidth}{-3cm}
  3513. \\setlength{\\oddsidemargin}{1.5cm}
  3514. \\addtolength{\\oddsidemargin}{-2.54cm}
  3515. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3516. \\setlength{\\textheight}{\\paperheight}
  3517. \\addtolength{\\textheight}{-\\headheight}
  3518. \\addtolength{\\textheight}{-\\headsep}
  3519. \\addtolength{\\textheight}{-\\footskip}
  3520. \\addtolength{\\textheight}{-3cm}
  3521. \\setlength{\\topmargin}{1.5cm}
  3522. \\addtolength{\\topmargin}{-2.54cm}"
  3523. "The document header used for processing LaTeX fragments.
  3524. It is imperative that this header make sure that no page number
  3525. appears on the page. The package defined in the variables
  3526. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3527. will either replace the placeholder \"[PACKAGES]\" in this
  3528. header, or they will be appended."
  3529. :group 'org-latex
  3530. :type 'string)
  3531. (defun org-set-packages-alist (var val)
  3532. "Set the packages alist and make sure it has 3 elements per entry."
  3533. (set var (mapcar (lambda (x)
  3534. (if (and (consp x) (= (length x) 2))
  3535. (list (car x) (nth 1 x) t)
  3536. x))
  3537. val)))
  3538. (defun org-get-packages-alist (var)
  3539. "Get the packages alist and make sure it has 3 elements per entry."
  3540. (mapcar (lambda (x)
  3541. (if (and (consp x) (= (length x) 2))
  3542. (list (car x) (nth 1 x) t)
  3543. x))
  3544. (default-value var)))
  3545. (defcustom org-latex-default-packages-alist
  3546. '(("AUTO" "inputenc" t ("pdflatex"))
  3547. ("T1" "fontenc" t ("pdflatex"))
  3548. ("" "graphicx" t)
  3549. ("" "grffile" t)
  3550. ("" "longtable" nil)
  3551. ("" "wrapfig" nil)
  3552. ("" "rotating" nil)
  3553. ("normalem" "ulem" t)
  3554. ("" "amsmath" t)
  3555. ("" "textcomp" t)
  3556. ("" "amssymb" t)
  3557. ("" "capt-of" nil)
  3558. ("" "hyperref" nil))
  3559. "Alist of default packages to be inserted in the header.
  3560. Change this only if one of the packages here causes an
  3561. incompatibility with another package you are using.
  3562. The packages in this list are needed by one part or another of
  3563. Org mode to function properly:
  3564. - inputenc, fontenc: for basic font and character selection
  3565. - graphicx: for including images
  3566. - grffile: allow periods and spaces in graphics file names
  3567. - longtable: For multipage tables
  3568. - wrapfig: for figure placement
  3569. - rotating: for sideways figures and tables
  3570. - ulem: for underline and strike-through
  3571. - amsmath: for subscript and superscript and math environments
  3572. - textcomp, amssymb: for various symbols used
  3573. for interpreting the entities in `org-entities'. You can skip
  3574. some of these packages if you don't use any of their symbols.
  3575. - capt-of: for captions outside of floats
  3576. - hyperref: for cross references
  3577. Therefore you should not modify this variable unless you know
  3578. what you are doing. The one reason to change it anyway is that
  3579. you might be loading some other package that conflicts with one
  3580. of the default packages. Each element is either a cell or
  3581. a string.
  3582. A cell is of the format
  3583. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3584. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3585. when compiling LaTeX snippets into images for inclusion into
  3586. non-LaTeX output. COMPILERS is a list of compilers that should
  3587. include the package, see `org-latex-compiler'. If the document
  3588. compiler is not in the list, and the list is non-nil, the package
  3589. will not be inserted in the final document.
  3590. A string will be inserted as-is in the header of the document."
  3591. :group 'org-latex
  3592. :group 'org-export-latex
  3593. :set 'org-set-packages-alist
  3594. :get 'org-get-packages-alist
  3595. :version "26.1"
  3596. :package-version '(Org . "8.3")
  3597. :type '(repeat
  3598. (choice
  3599. (list :tag "options/package pair"
  3600. (string :tag "options")
  3601. (string :tag "package")
  3602. (boolean :tag "Snippet"))
  3603. (string :tag "A line of LaTeX"))))
  3604. (defcustom org-latex-packages-alist nil
  3605. "Alist of packages to be inserted in every LaTeX header.
  3606. These will be inserted after `org-latex-default-packages-alist'.
  3607. Each element is either a cell or a string.
  3608. A cell is of the format:
  3609. (\"options\" \"package\" SNIPPET-FLAG)
  3610. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3611. needed when turning LaTeX snippets into images for inclusion into
  3612. non-LaTeX output.
  3613. A string will be inserted as-is in the header of the document.
  3614. Make sure that you only list packages here which:
  3615. - you want in every file;
  3616. - do not conflict with the setup in `org-format-latex-header';
  3617. - do not conflict with the default packages in
  3618. `org-latex-default-packages-alist'."
  3619. :group 'org-latex
  3620. :group 'org-export-latex
  3621. :set 'org-set-packages-alist
  3622. :get 'org-get-packages-alist
  3623. :type '(repeat
  3624. (choice
  3625. (list :tag "options/package pair"
  3626. (string :tag "options")
  3627. (string :tag "package")
  3628. (boolean :tag "Snippet"))
  3629. (string :tag "A line of LaTeX"))))
  3630. (defgroup org-appearance nil
  3631. "Settings for Org mode appearance."
  3632. :tag "Org Appearance"
  3633. :group 'org)
  3634. (defcustom org-level-color-stars-only nil
  3635. "Non-nil means fontify only the stars in each headline.
  3636. When nil, the entire headline is fontified.
  3637. Changing it requires restart of `font-lock-mode' to become effective
  3638. also in regions already fontified."
  3639. :group 'org-appearance
  3640. :type 'boolean)
  3641. (defcustom org-hide-leading-stars nil
  3642. "Non-nil means hide the first N-1 stars in a headline.
  3643. This works by using the face `org-hide' for these stars. This
  3644. face is white for a light background, and black for a dark
  3645. background. You may have to customize the face `org-hide' to
  3646. make this work.
  3647. Changing it requires restart of `font-lock-mode' to become effective
  3648. also in regions already fontified.
  3649. You may also set this on a per-file basis by adding one of the following
  3650. lines to the buffer:
  3651. #+STARTUP: hidestars
  3652. #+STARTUP: showstars"
  3653. :group 'org-appearance
  3654. :type 'boolean)
  3655. (defcustom org-hidden-keywords nil
  3656. "List of symbols corresponding to keywords to be hidden the org buffer.
  3657. For example, a value \\='(title) for this list will make the document's title
  3658. appear in the buffer without the initial #+TITLE: keyword."
  3659. :group 'org-appearance
  3660. :version "24.1"
  3661. :type '(set (const :tag "#+AUTHOR" author)
  3662. (const :tag "#+DATE" date)
  3663. (const :tag "#+EMAIL" email)
  3664. (const :tag "#+TITLE" title)))
  3665. (defcustom org-custom-properties nil
  3666. "List of properties (as strings) with a special meaning.
  3667. The default use of these custom properties is to let the user
  3668. hide them with `org-toggle-custom-properties-visibility'."
  3669. :group 'org-properties
  3670. :group 'org-appearance
  3671. :version "24.3"
  3672. :type '(repeat (string :tag "Property Name")))
  3673. (defcustom org-fontify-done-headline nil
  3674. "Non-nil means change the face of a headline if it is marked DONE.
  3675. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3676. When this is non-nil, the headline after the keyword is set to the
  3677. `org-headline-done' as an additional indication."
  3678. :group 'org-appearance
  3679. :type 'boolean)
  3680. (defcustom org-fontify-emphasized-text t
  3681. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3682. Changing this variable requires a restart of Emacs to take effect."
  3683. :group 'org-appearance
  3684. :type 'boolean)
  3685. (defcustom org-fontify-whole-heading-line nil
  3686. "Non-nil means fontify the whole line for headings.
  3687. This is useful when setting a background color for the
  3688. org-level-* faces."
  3689. :group 'org-appearance
  3690. :type 'boolean)
  3691. (defcustom org-highlight-latex-and-related nil
  3692. "Non-nil means highlight LaTeX related syntax in the buffer.
  3693. When non nil, the value should be a list containing any of the
  3694. following symbols:
  3695. `latex' Highlight LaTeX snippets and environments.
  3696. `script' Highlight subscript and superscript.
  3697. `entities' Highlight entities."
  3698. :group 'org-appearance
  3699. :version "24.4"
  3700. :package-version '(Org . "8.0")
  3701. :type '(choice
  3702. (const :tag "No highlighting" nil)
  3703. (set :greedy t :tag "Highlight"
  3704. (const :tag "LaTeX snippets and environments" latex)
  3705. (const :tag "Subscript and superscript" script)
  3706. (const :tag "Entities" entities))))
  3707. (defcustom org-hide-emphasis-markers nil
  3708. "Non-nil mean font-lock should hide the emphasis marker characters."
  3709. :group 'org-appearance
  3710. :type 'boolean)
  3711. (defcustom org-hide-macro-markers nil
  3712. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3713. :group 'org-appearance
  3714. :type 'boolean)
  3715. (defcustom org-pretty-entities nil
  3716. "Non-nil means show entities as UTF8 characters.
  3717. When nil, the \\name form remains in the buffer."
  3718. :group 'org-appearance
  3719. :version "24.1"
  3720. :type 'boolean)
  3721. (defcustom org-pretty-entities-include-sub-superscripts t
  3722. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3723. :group 'org-appearance
  3724. :version "24.1"
  3725. :type 'boolean)
  3726. (defvar org-emph-re nil
  3727. "Regular expression for matching emphasis.
  3728. After a match, the match groups contain these elements:
  3729. 0 The match of the full regular expression, including the characters
  3730. before and after the proper match
  3731. 1 The character before the proper match, or empty at beginning of line
  3732. 2 The proper match, including the leading and trailing markers
  3733. 3 The leading marker like * or /, indicating the type of highlighting
  3734. 4 The text between the emphasis markers, not including the markers
  3735. 5 The character after the match, empty at the end of a line")
  3736. (defvar org-verbatim-re nil
  3737. "Regular expression for matching verbatim text.")
  3738. (defvar org-emphasis-regexp-components) ; defined just below
  3739. (defvar org-emphasis-alist) ; defined just below
  3740. (defun org-set-emph-re (var val)
  3741. "Set variable and compute the emphasis regular expression."
  3742. (set var val)
  3743. (when (and (boundp 'org-emphasis-alist)
  3744. (boundp 'org-emphasis-regexp-components)
  3745. org-emphasis-alist org-emphasis-regexp-components)
  3746. (pcase-let*
  3747. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3748. (body (if (<= nl 0) body
  3749. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3750. (template
  3751. (format (concat "\\([%s]\\|^\\)" ;before markers
  3752. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3753. "\\([%s]\\|$\\)") ;after markers
  3754. pre border border body border post)))
  3755. (setq org-emph-re (format template "*/_+"))
  3756. (setq org-verbatim-re (format template "=~")))))
  3757. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3758. ;; set this option proved cumbersome. See this message/thread:
  3759. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3760. (defvar org-emphasis-regexp-components
  3761. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3762. "Components used to build the regular expression for emphasis.
  3763. This is a list with five entries. Terminology: In an emphasis string
  3764. like \" *strong word* \", we call the initial space PREMATCH, the final
  3765. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3766. and \"trong wor\" is the body. The different components in this variable
  3767. specify what is allowed/forbidden in each part:
  3768. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3769. post Chars allowed as postmatch. End of line will be allowed too.
  3770. border The chars *forbidden* as border characters.
  3771. body-regexp A regexp like \".\" to match a body character. Don't use
  3772. non-shy groups here, and don't allow newline here.
  3773. newline The maximum number of newlines allowed in an emphasis exp.
  3774. You need to reload Org or to restart Emacs after customizing this.")
  3775. (defcustom org-emphasis-alist
  3776. '(("*" bold)
  3777. ("/" italic)
  3778. ("_" underline)
  3779. ("=" org-verbatim verbatim)
  3780. ("~" org-code verbatim)
  3781. ("+" (:strike-through t)))
  3782. "Alist of characters and faces to emphasize text.
  3783. Text starting and ending with a special character will be emphasized,
  3784. for example *bold*, _underlined_ and /italic/. This variable sets the
  3785. marker characters and the face to be used by font-lock for highlighting
  3786. in Org buffers.
  3787. You need to reload Org or to restart Emacs after customizing this."
  3788. :group 'org-appearance
  3789. :set 'org-set-emph-re
  3790. :version "24.4"
  3791. :package-version '(Org . "8.0")
  3792. :type '(repeat
  3793. (list
  3794. (string :tag "Marker character")
  3795. (choice
  3796. (face :tag "Font-lock-face")
  3797. (plist :tag "Face property list"))
  3798. (option (const verbatim)))))
  3799. (defvar org-protecting-blocks '("src" "example" "export")
  3800. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3801. This is needed for font-lock setup.")
  3802. ;;; Functions and variables from their packages
  3803. ;; Declared here to avoid compiler warnings
  3804. (defvar mark-active)
  3805. ;; Various packages
  3806. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3807. (declare-function calendar-forward-day "cal-move" (arg))
  3808. (declare-function calendar-goto-date "cal-move" (date))
  3809. (declare-function calendar-goto-today "cal-move" ())
  3810. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3811. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3812. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3813. (declare-function cdlatex-tab "ext:cdlatex" ())
  3814. (declare-function dired-get-filename
  3815. "dired"
  3816. (&optional localp no-error-if-not-filep))
  3817. (declare-function iswitchb-read-buffer
  3818. "iswitchb"
  3819. (prompt &optional
  3820. default require-match _predicate start matches-set))
  3821. (declare-function org-agenda-change-all-lines
  3822. "org-agenda"
  3823. (newhead hdmarker &optional fixface just-this))
  3824. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3825. "org-agenda"
  3826. (&optional end))
  3827. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3828. (declare-function org-agenda-format-item
  3829. "org-agenda"
  3830. (extra txt &optional level category tags dotime
  3831. remove-re habitp))
  3832. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3833. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3834. (declare-function org-agenda-save-markers-for-cut-and-paste
  3835. "org-agenda"
  3836. (beg end))
  3837. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3838. (declare-function org-agenda-skip "org-agenda" ())
  3839. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3840. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3841. (declare-function org-indent-mode "org-indent" (&optional arg))
  3842. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3843. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3844. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3845. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3846. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3847. (declare-function parse-time-string "parse-time" (string))
  3848. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3849. (defvar align-mode-rules-list)
  3850. (defvar calc-embedded-close-formula)
  3851. (defvar calc-embedded-open-formula)
  3852. (defvar calc-embedded-open-mode)
  3853. (defvar font-lock-unfontify-region-function)
  3854. (defvar iswitchb-temp-buflist)
  3855. (defvar org-agenda-tags-todo-honor-ignore-options)
  3856. (defvar remember-data-file)
  3857. (defvar texmathp-why)
  3858. ;;;###autoload
  3859. (defun turn-on-orgtbl ()
  3860. "Unconditionally turn on `orgtbl-mode'."
  3861. (require 'org-table)
  3862. (orgtbl-mode 1))
  3863. (defun org-at-table-p (&optional table-type)
  3864. "Non-nil if the cursor is inside an Org table.
  3865. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  3866. If `org-enable-table-editor' is nil, return nil unconditionally."
  3867. (and
  3868. org-enable-table-editor
  3869. (save-excursion
  3870. (beginning-of-line)
  3871. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  3872. (or (not (derived-mode-p 'org-mode))
  3873. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  3874. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  3875. (defun org-at-table.el-p ()
  3876. "Non-nil when point is at a table.el table."
  3877. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  3878. (let ((element (org-element-at-point)))
  3879. (and (eq (org-element-type element) 'table)
  3880. (eq (org-element-property :type element) 'table.el)))))
  3881. (defun org-at-table-hline-p ()
  3882. "Non-nil when point is inside a hline in a table.
  3883. Assume point is already in a table. If `org-enable-table-editor'
  3884. is nil, return nil unconditionally."
  3885. (and org-enable-table-editor
  3886. (save-excursion
  3887. (beginning-of-line)
  3888. (looking-at org-table-hline-regexp))))
  3889. (defun org-table-map-tables (function &optional quietly)
  3890. "Apply FUNCTION to the start of all tables in the buffer."
  3891. (org-with-wide-buffer
  3892. (goto-char (point-min))
  3893. (while (re-search-forward org-table-any-line-regexp nil t)
  3894. (unless quietly
  3895. (message "Mapping tables: %d%%"
  3896. (floor (* 100.0 (point)) (buffer-size))))
  3897. (beginning-of-line 1)
  3898. (when (and (looking-at org-table-line-regexp)
  3899. ;; Exclude tables in src/example/verbatim/clocktable blocks
  3900. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  3901. (save-excursion (funcall function))
  3902. (or (looking-at org-table-line-regexp)
  3903. (forward-char 1)))
  3904. (re-search-forward org-table-any-border-regexp nil 1)))
  3905. (unless quietly (message "Mapping tables: done")))
  3906. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3907. (declare-function org-clock-update-mode-line "org-clock" ())
  3908. (declare-function org-resolve-clocks "org-clock"
  3909. (&optional also-non-dangling-p prompt last-valid))
  3910. (defun org-at-TBLFM-p (&optional pos)
  3911. "Non-nil when point (or POS) is in #+TBLFM line."
  3912. (save-excursion
  3913. (goto-char (or pos (point)))
  3914. (beginning-of-line)
  3915. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  3916. (eq (org-element-type (org-element-at-point)) 'table))))
  3917. (defvar org-clock-start-time)
  3918. (defvar org-clock-marker (make-marker)
  3919. "Marker recording the last clock-in.")
  3920. (defvar org-clock-hd-marker (make-marker)
  3921. "Marker recording the last clock-in, but the headline position.")
  3922. (defvar org-clock-heading ""
  3923. "The heading of the current clock entry.")
  3924. (defun org-clock-is-active ()
  3925. "Return the buffer where the clock is currently running.
  3926. Return nil if no clock is running."
  3927. (marker-buffer org-clock-marker))
  3928. (defun org-check-running-clock ()
  3929. "Check if the current buffer contains the running clock.
  3930. If yes, offer to stop it and to save the buffer with the changes."
  3931. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3932. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3933. (buffer-name))))
  3934. (org-clock-out)
  3935. (when (y-or-n-p "Save changed buffer?")
  3936. (save-buffer))))
  3937. (defun org-clocktable-try-shift (dir n)
  3938. "Check if this line starts a clock table, if yes, shift the time block."
  3939. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3940. (org-clocktable-shift dir n)))
  3941. ;;;###autoload
  3942. (defun org-clock-persistence-insinuate ()
  3943. "Set up hooks for clock persistence."
  3944. (require 'org-clock)
  3945. (add-hook 'org-mode-hook 'org-clock-load)
  3946. (add-hook 'kill-emacs-hook 'org-clock-save))
  3947. (defgroup org-archive nil
  3948. "Options concerning archiving in Org mode."
  3949. :tag "Org Archive"
  3950. :group 'org-structure)
  3951. (defcustom org-archive-location "%s_archive::"
  3952. "The location where subtrees should be archived.
  3953. The value of this variable is a string, consisting of two parts,
  3954. separated by a double-colon. The first part is a filename and
  3955. the second part is a headline.
  3956. When the filename is omitted, archiving happens in the same file.
  3957. %s in the filename will be replaced by the current file
  3958. name (without the directory part). Archiving to a different file
  3959. is useful to keep archived entries from contributing to the
  3960. Org Agenda.
  3961. The archived entries will be filed as subtrees of the specified
  3962. headline. When the headline is omitted, the subtrees are simply
  3963. filed away at the end of the file, as top-level entries. Also in
  3964. the heading you can use %s to represent the file name, this can be
  3965. useful when using the same archive for a number of different files.
  3966. Here are a few examples:
  3967. \"%s_archive::\"
  3968. If the current file is Projects.org, archive in file
  3969. Projects.org_archive, as top-level trees. This is the default.
  3970. \"::* Archived Tasks\"
  3971. Archive in the current file, under the top-level headline
  3972. \"* Archived Tasks\".
  3973. \"~/org/archive.org::\"
  3974. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3975. \"~/org/archive.org::* From %s\"
  3976. Archive in file ~/org/archive.org (absolute path), under headlines
  3977. \"From FILENAME\" where file name is the current file name.
  3978. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3979. The \"datetree/\" string is special, signifying to archive
  3980. items to the datetree. Items are placed in either the CLOSED
  3981. date of the item, or the current date if there is no CLOSED date.
  3982. The heading will be a subentry to the current date. There doesn't
  3983. need to be a heading, but there always needs to be a slash after
  3984. datetree. For example, to store archived items directly in the
  3985. datetree, use \"~/org/datetree.org::datetree/\".
  3986. \"basement::** Finished Tasks\"
  3987. Archive in file ./basement (relative path), as level 3 trees
  3988. below the level 2 heading \"** Finished Tasks\".
  3989. You may set this option on a per-file basis by adding to the buffer a
  3990. line like
  3991. #+ARCHIVE: basement::** Finished Tasks
  3992. You may also define it locally for a subtree by setting an ARCHIVE property
  3993. in the entry. If such a property is found in an entry, or anywhere up
  3994. the hierarchy, it will be used."
  3995. :group 'org-archive
  3996. :type 'string)
  3997. (defcustom org-agenda-skip-archived-trees t
  3998. "Non-nil means the agenda will skip any items located in archived trees.
  3999. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4000. variable is no longer recommended, you should leave it at the value t.
  4001. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4002. :group 'org-archive
  4003. :group 'org-agenda-skip
  4004. :type 'boolean)
  4005. (defcustom org-columns-skip-archived-trees t
  4006. "Non-nil means ignore archived trees when creating column view."
  4007. :group 'org-archive
  4008. :group 'org-properties
  4009. :type 'boolean)
  4010. (defcustom org-cycle-open-archived-trees nil
  4011. "Non-nil means `org-cycle' will open archived trees.
  4012. An archived tree is a tree marked with the tag ARCHIVE.
  4013. When nil, archived trees will stay folded. You can still open them with
  4014. normal outline commands like `show-all', but not with the cycling commands."
  4015. :group 'org-archive
  4016. :group 'org-cycle
  4017. :type 'boolean)
  4018. (defcustom org-sparse-tree-open-archived-trees nil
  4019. "Non-nil means sparse tree construction shows matches in archived trees.
  4020. When nil, matches in these trees are highlighted, but the trees are kept in
  4021. collapsed state."
  4022. :group 'org-archive
  4023. :group 'org-sparse-trees
  4024. :type 'boolean)
  4025. (defcustom org-sparse-tree-default-date-type nil
  4026. "The default date type when building a sparse tree.
  4027. When this is nil, a date is a scheduled or a deadline timestamp.
  4028. Otherwise, these types are allowed:
  4029. all: all timestamps
  4030. active: only active timestamps (<...>)
  4031. inactive: only inactive timestamps ([...])
  4032. scheduled: only scheduled timestamps
  4033. deadline: only deadline timestamps"
  4034. :type '(choice (const :tag "Scheduled or deadline" nil)
  4035. (const :tag "All timestamps" all)
  4036. (const :tag "Only active timestamps" active)
  4037. (const :tag "Only inactive timestamps" inactive)
  4038. (const :tag "Only scheduled timestamps" scheduled)
  4039. (const :tag "Only deadline timestamps" deadline)
  4040. (const :tag "Only closed timestamps" closed))
  4041. :version "26.1"
  4042. :package-version '(Org . "8.3")
  4043. :group 'org-sparse-trees)
  4044. (defun org-cycle-hide-archived-subtrees (state)
  4045. "Re-hide all archived subtrees after a visibility state change."
  4046. (when (and (not org-cycle-open-archived-trees)
  4047. (not (memq state '(overview folded))))
  4048. (save-excursion
  4049. (let* ((globalp (memq state '(contents all)))
  4050. (beg (if globalp (point-min) (point)))
  4051. (end (if globalp (point-max) (org-end-of-subtree t))))
  4052. (org-hide-archived-subtrees beg end)
  4053. (goto-char beg)
  4054. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4055. (message "%s" (substitute-command-keys
  4056. "Subtree is archived and stays closed. Use \
  4057. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4058. (defun org-force-cycle-archived ()
  4059. "Cycle subtree even if it is archived."
  4060. (interactive)
  4061. (setq this-command 'org-cycle)
  4062. (let ((org-cycle-open-archived-trees t))
  4063. (call-interactively 'org-cycle)))
  4064. (defun org-hide-archived-subtrees (beg end)
  4065. "Re-hide all archived subtrees after a visibility state change."
  4066. (org-with-wide-buffer
  4067. (let ((case-fold-search nil)
  4068. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4069. (goto-char beg)
  4070. ;; Include headline point is currently on.
  4071. (beginning-of-line)
  4072. (while (and (< (point) end) (re-search-forward re end t))
  4073. (when (member org-archive-tag (org-get-tags))
  4074. (org-flag-subtree t)
  4075. (org-end-of-subtree t))))))
  4076. (declare-function outline-end-of-heading "outline" ())
  4077. (declare-function outline-flag-region "outline" (from to flag))
  4078. (defun org-flag-subtree (flag)
  4079. (save-excursion
  4080. (org-back-to-heading t)
  4081. (outline-end-of-heading)
  4082. (outline-flag-region (point)
  4083. (progn (org-end-of-subtree t) (point))
  4084. flag)))
  4085. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4086. ;; Declare Column View Code
  4087. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4088. (declare-function org-columns-compute "org-colview" (property))
  4089. ;; Declare ID code
  4090. (declare-function org-id-store-link "org-id")
  4091. (declare-function org-id-locations-load "org-id")
  4092. (declare-function org-id-locations-save "org-id")
  4093. (defvar org-id-track-globally)
  4094. ;;; Variables for pre-computed regular expressions, all buffer local
  4095. (defvar-local org-todo-regexp nil
  4096. "Matches any of the TODO state keywords.
  4097. Since TODO keywords are case-sensitive, `case-fold-search' is
  4098. expected to be bound to nil when matching against this regexp.")
  4099. (defvar-local org-not-done-regexp nil
  4100. "Matches any of the TODO state keywords except the last one.
  4101. Since TODO keywords are case-sensitive, `case-fold-search' is
  4102. expected to be bound to nil when matching against this regexp.")
  4103. (defvar-local org-not-done-heading-regexp nil
  4104. "Matches a TODO headline that is not done.
  4105. Since TODO keywords are case-sensitive, `case-fold-search' is
  4106. expected to be bound to nil when matching against this regexp.")
  4107. (defvar-local org-todo-line-regexp nil
  4108. "Matches a headline and puts TODO state into group 2 if present.
  4109. Since TODO keywords are case-sensitive, `case-fold-search' is
  4110. expected to be bound to nil when matching against this regexp.")
  4111. (defvar-local org-complex-heading-regexp nil
  4112. "Matches a headline and puts everything into groups:
  4113. group 1: Stars
  4114. group 2: The TODO keyword, maybe
  4115. group 3: Priority cookie
  4116. group 4: True headline
  4117. group 5: Tags
  4118. Since TODO keywords are case-sensitive, `case-fold-search' is
  4119. expected to be bound to nil when matching against this regexp.")
  4120. (defvar-local org-complex-heading-regexp-format nil
  4121. "Printf format to make regexp to match an exact headline.
  4122. This regexp will match the headline of any node which has the
  4123. exact headline text that is put into the format, but may have any
  4124. TODO state, priority and tags.")
  4125. (defvar-local org-todo-line-tags-regexp nil
  4126. "Matches a headline and puts TODO state into group 2 if present.
  4127. Also put tags into group 4 if tags are present.")
  4128. (defconst org-plain-time-of-day-regexp
  4129. (concat
  4130. "\\(\\<[012]?[0-9]"
  4131. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4132. "\\(--?"
  4133. "\\(\\<[012]?[0-9]"
  4134. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4135. "\\)?")
  4136. "Regular expression to match a plain time or time range.
  4137. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4138. groups carry important information:
  4139. 0 the full match
  4140. 1 the first time, range or not
  4141. 8 the second time, if it is a range.")
  4142. (defconst org-plain-time-extension-regexp
  4143. (concat
  4144. "\\(\\<[012]?[0-9]"
  4145. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4146. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4147. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4148. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4149. groups carry important information:
  4150. 0 the full match
  4151. 7 hours of duration
  4152. 9 minutes of duration")
  4153. (defconst org-stamp-time-of-day-regexp
  4154. (concat
  4155. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4156. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4157. "\\(--?"
  4158. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4159. "Regular expression to match a timestamp time or time range.
  4160. After a match, the following groups carry important information:
  4161. 0 the full match
  4162. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4163. 2 the first time, range or not
  4164. 4 the second time, if it is a range.")
  4165. (defconst org-startup-options
  4166. '(("fold" org-startup-folded t)
  4167. ("overview" org-startup-folded t)
  4168. ("nofold" org-startup-folded nil)
  4169. ("showall" org-startup-folded nil)
  4170. ("showeverything" org-startup-folded showeverything)
  4171. ("content" org-startup-folded content)
  4172. ("indent" org-startup-indented t)
  4173. ("noindent" org-startup-indented nil)
  4174. ("hidestars" org-hide-leading-stars t)
  4175. ("showstars" org-hide-leading-stars nil)
  4176. ("odd" org-odd-levels-only t)
  4177. ("oddeven" org-odd-levels-only nil)
  4178. ("align" org-startup-align-all-tables t)
  4179. ("noalign" org-startup-align-all-tables nil)
  4180. ("inlineimages" org-startup-with-inline-images t)
  4181. ("noinlineimages" org-startup-with-inline-images nil)
  4182. ("latexpreview" org-startup-with-latex-preview t)
  4183. ("nolatexpreview" org-startup-with-latex-preview nil)
  4184. ("customtime" org-display-custom-times t)
  4185. ("logdone" org-log-done time)
  4186. ("lognotedone" org-log-done note)
  4187. ("nologdone" org-log-done nil)
  4188. ("lognoteclock-out" org-log-note-clock-out t)
  4189. ("nolognoteclock-out" org-log-note-clock-out nil)
  4190. ("logrepeat" org-log-repeat state)
  4191. ("lognoterepeat" org-log-repeat note)
  4192. ("logdrawer" org-log-into-drawer t)
  4193. ("nologdrawer" org-log-into-drawer nil)
  4194. ("logstatesreversed" org-log-states-order-reversed t)
  4195. ("nologstatesreversed" org-log-states-order-reversed nil)
  4196. ("nologrepeat" org-log-repeat nil)
  4197. ("logreschedule" org-log-reschedule time)
  4198. ("lognotereschedule" org-log-reschedule note)
  4199. ("nologreschedule" org-log-reschedule nil)
  4200. ("logredeadline" org-log-redeadline time)
  4201. ("lognoteredeadline" org-log-redeadline note)
  4202. ("nologredeadline" org-log-redeadline nil)
  4203. ("logrefile" org-log-refile time)
  4204. ("lognoterefile" org-log-refile note)
  4205. ("nologrefile" org-log-refile nil)
  4206. ("fninline" org-footnote-define-inline t)
  4207. ("nofninline" org-footnote-define-inline nil)
  4208. ("fnlocal" org-footnote-section nil)
  4209. ("fnauto" org-footnote-auto-label t)
  4210. ("fnprompt" org-footnote-auto-label nil)
  4211. ("fnconfirm" org-footnote-auto-label confirm)
  4212. ("fnplain" org-footnote-auto-label plain)
  4213. ("fnadjust" org-footnote-auto-adjust t)
  4214. ("nofnadjust" org-footnote-auto-adjust nil)
  4215. ("constcgs" constants-unit-system cgs)
  4216. ("constSI" constants-unit-system SI)
  4217. ("noptag" org-tag-persistent-alist nil)
  4218. ("hideblocks" org-hide-block-startup t)
  4219. ("nohideblocks" org-hide-block-startup nil)
  4220. ("beamer" org-startup-with-beamer-mode t)
  4221. ("entitiespretty" org-pretty-entities t)
  4222. ("entitiesplain" org-pretty-entities nil))
  4223. "Variable associated with STARTUP options for org-mode.
  4224. Each element is a list of three items: the startup options (as written
  4225. in the #+STARTUP line), the corresponding variable, and the value to set
  4226. this variable to if the option is found. An optional forth element PUSH
  4227. means to push this value onto the list in the variable.")
  4228. (defcustom org-group-tags t
  4229. "When non-nil (the default), use group tags.
  4230. This can be turned on/off through `org-toggle-tags-groups'."
  4231. :group 'org-tags
  4232. :group 'org-startup
  4233. :type 'boolean)
  4234. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4235. (defun org-toggle-tags-groups ()
  4236. "Toggle support for group tags.
  4237. Support for group tags is controlled by the option
  4238. `org-group-tags', which is non-nil by default."
  4239. (interactive)
  4240. (setq org-group-tags (not org-group-tags))
  4241. (cond ((and (derived-mode-p 'org-agenda-mode)
  4242. org-group-tags)
  4243. (org-agenda-redo))
  4244. ((derived-mode-p 'org-mode)
  4245. (let ((org-inhibit-startup t)) (org-mode))))
  4246. (message "Groups tags support has been turned %s"
  4247. (if org-group-tags "on" "off")))
  4248. (defun org-set-regexps-and-options (&optional tags-only)
  4249. "Precompute regular expressions used in the current buffer.
  4250. When optional argument TAGS-ONLY is non-nil, only compute tags
  4251. related expressions."
  4252. (when (derived-mode-p 'org-mode)
  4253. (let ((alist (org--setup-collect-keywords
  4254. (org-make-options-regexp
  4255. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4256. (and (not tags-only)
  4257. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4258. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4259. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4260. ;; Startup options. Get this early since it does change
  4261. ;; behavior for other options (e.g., tags).
  4262. (let ((startup (cdr (assq 'startup alist))))
  4263. (dolist (option startup)
  4264. (let ((entry (assoc-string option org-startup-options t)))
  4265. (when entry
  4266. (let ((var (nth 1 entry))
  4267. (val (nth 2 entry)))
  4268. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4269. (unless (listp (symbol-value var))
  4270. (set (make-local-variable var) nil))
  4271. (add-to-list var val)))))))
  4272. (setq-local org-file-tags
  4273. (mapcar #'org-add-prop-inherited
  4274. (cdr (assq 'filetags alist))))
  4275. (setq org-current-tag-alist
  4276. (append org-tag-persistent-alist
  4277. (let ((tags (cdr (assq 'tags alist))))
  4278. (if tags (org-tag-string-to-alist tags)
  4279. org-tag-alist))))
  4280. (setq org-tag-groups-alist
  4281. (org-tag-alist-to-groups org-current-tag-alist))
  4282. (unless tags-only
  4283. ;; File properties.
  4284. (setq-local org-file-properties (cdr (assq 'property alist)))
  4285. ;; Archive location.
  4286. (let ((archive (cdr (assq 'archive alist))))
  4287. (when archive (setq-local org-archive-location archive)))
  4288. ;; Category.
  4289. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4290. (when cat
  4291. (setq-local org-category (intern cat))
  4292. (setq-local org-file-properties
  4293. (org--update-property-plist
  4294. "CATEGORY" cat org-file-properties))))
  4295. ;; Columns.
  4296. (let ((column (cdr (assq 'columns alist))))
  4297. (when column (setq-local org-columns-default-format column)))
  4298. ;; Constants.
  4299. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4300. ;; Link abbreviations.
  4301. (let ((links (cdr (assq 'link alist))))
  4302. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4303. ;; Priorities.
  4304. (let ((priorities (cdr (assq 'priorities alist))))
  4305. (when priorities
  4306. (setq-local org-highest-priority (nth 0 priorities))
  4307. (setq-local org-lowest-priority (nth 1 priorities))
  4308. (setq-local org-default-priority (nth 2 priorities))))
  4309. ;; Scripts.
  4310. (let ((scripts (assq 'scripts alist)))
  4311. (when scripts
  4312. (setq-local org-use-sub-superscripts (cdr scripts))))
  4313. ;; TODO keywords.
  4314. (setq-local org-todo-kwd-alist nil)
  4315. (setq-local org-todo-key-alist nil)
  4316. (setq-local org-todo-key-trigger nil)
  4317. (setq-local org-todo-keywords-1 nil)
  4318. (setq-local org-done-keywords nil)
  4319. (setq-local org-todo-heads nil)
  4320. (setq-local org-todo-sets nil)
  4321. (setq-local org-todo-log-states nil)
  4322. (let ((todo-sequences
  4323. (or (nreverse (cdr (assq 'todo alist)))
  4324. (let ((d (default-value 'org-todo-keywords)))
  4325. (if (not (stringp (car d))) d
  4326. ;; XXX: Backward compatibility code.
  4327. (list (cons org-todo-interpretation d)))))))
  4328. (dolist (sequence todo-sequences)
  4329. (let* ((sequence (or (run-hook-with-args-until-success
  4330. 'org-todo-setup-filter-hook sequence)
  4331. sequence))
  4332. (sequence-type (car sequence))
  4333. (keywords (cdr sequence))
  4334. (sep (member "|" keywords))
  4335. names alist)
  4336. (dolist (k (remove "|" keywords))
  4337. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4338. k)
  4339. (error "Invalid TODO keyword %s" k))
  4340. (let ((name (match-string 1 k))
  4341. (key (match-string 2 k))
  4342. (log (org-extract-log-state-settings k)))
  4343. (push name names)
  4344. (push (cons name (and key (string-to-char key))) alist)
  4345. (when log (push log org-todo-log-states))))
  4346. (let* ((names (nreverse names))
  4347. (done (if sep (org-remove-keyword-keys (cdr sep))
  4348. (last names)))
  4349. (head (car names))
  4350. (tail (list sequence-type head (car done) (org-last done))))
  4351. (add-to-list 'org-todo-heads head 'append)
  4352. (push names org-todo-sets)
  4353. (setq org-done-keywords (append org-done-keywords done nil))
  4354. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4355. (setq org-todo-key-alist
  4356. (append org-todo-key-alist
  4357. (and alist
  4358. (append '((:startgroup))
  4359. (nreverse alist)
  4360. '((:endgroup))))))
  4361. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4362. (setq org-todo-sets (nreverse org-todo-sets)
  4363. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4364. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4365. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4366. ;; Compute the regular expressions and other local variables.
  4367. ;; Using `org-outline-regexp-bol' would complicate them much,
  4368. ;; because of the fixed white space at the end of that string.
  4369. (unless org-done-keywords
  4370. (setq org-done-keywords
  4371. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4372. (setq org-not-done-keywords
  4373. (org-delete-all org-done-keywords
  4374. (copy-sequence org-todo-keywords-1))
  4375. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4376. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4377. org-not-done-heading-regexp
  4378. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4379. org-todo-line-regexp
  4380. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4381. org-complex-heading-regexp
  4382. (concat "^\\(\\*+\\)"
  4383. "\\(?: +" org-todo-regexp "\\)?"
  4384. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4385. "\\(?: +\\(.*?\\)\\)??"
  4386. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4387. "[ \t]*$")
  4388. org-complex-heading-regexp-format
  4389. (concat "^\\(\\*+\\)"
  4390. "\\(?: +" org-todo-regexp "\\)?"
  4391. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4392. "\\(?: +"
  4393. ;; Stats cookies can be stuck to body.
  4394. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4395. "\\(%s\\)"
  4396. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4397. "\\)"
  4398. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4399. "[ \t]*$")
  4400. org-todo-line-tags-regexp
  4401. (concat "^\\(\\*+\\)"
  4402. "\\(?: +" org-todo-regexp "\\)?"
  4403. "\\(?: +\\(.*?\\)\\)??"
  4404. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4405. "[ \t]*$"))
  4406. (org-compute-latex-and-related-regexp)))))
  4407. (defun org--setup-collect-keywords (regexp &optional files alist)
  4408. "Return setup keywords values as an alist.
  4409. REGEXP matches a subset of setup keywords. FILES is a list of
  4410. file names already visited. It is used to avoid circular setup
  4411. files. ALIST, when non-nil, is the alist computed so far.
  4412. Return value contains the following keys: `archive', `category',
  4413. `columns', `constants', `filetags', `link', `priorities',
  4414. `property', `scripts', `startup', `tags' and `todo'."
  4415. (org-with-wide-buffer
  4416. (goto-char (point-min))
  4417. (let ((case-fold-search t))
  4418. (while (re-search-forward regexp nil t)
  4419. (let ((element (org-element-at-point)))
  4420. (when (eq (org-element-type element) 'keyword)
  4421. (let ((key (org-element-property :key element))
  4422. (value (org-element-property :value element)))
  4423. (cond
  4424. ((equal key "ARCHIVE")
  4425. (when (org-string-nw-p value)
  4426. (push (cons 'archive value) alist)))
  4427. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4428. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4429. ((equal key "CONSTANTS")
  4430. (let* ((constants (assq 'constants alist))
  4431. (store (cdr constants)))
  4432. (dolist (pair (org-split-string value))
  4433. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4434. pair)
  4435. (let* ((name (match-string 1 pair))
  4436. (value (match-string 2 pair))
  4437. (old (assoc name store)))
  4438. (if old (setcdr old value)
  4439. (push (cons name value) store)))))
  4440. (if constants (setcdr constants store)
  4441. (push (cons 'constants store) alist))))
  4442. ((equal key "FILETAGS")
  4443. (when (org-string-nw-p value)
  4444. (let ((old (assq 'filetags alist))
  4445. (new (apply #'nconc
  4446. (mapcar (lambda (x) (org-split-string x ":"))
  4447. (org-split-string value)))))
  4448. (if old (setcdr old (append new (cdr old)))
  4449. (push (cons 'filetags new) alist)))))
  4450. ((equal key "LINK")
  4451. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4452. (let ((links (assq 'link alist))
  4453. (pair (cons (match-string-no-properties 1 value)
  4454. (match-string-no-properties 2 value))))
  4455. (if links (push pair (cdr links))
  4456. (push (list 'link pair) alist)))))
  4457. ((equal key "OPTIONS")
  4458. (when (and (org-string-nw-p value)
  4459. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4460. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4461. ((equal key "PRIORITIES")
  4462. (push (cons 'priorities
  4463. (let ((prio (org-split-string value)))
  4464. (if (< (length prio) 3) '(?A ?C ?B)
  4465. (mapcar #'string-to-char prio))))
  4466. alist))
  4467. ((equal key "PROPERTY")
  4468. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4469. (let* ((property (assq 'property alist))
  4470. (value (org--update-property-plist
  4471. (match-string-no-properties 1 value)
  4472. (match-string-no-properties 2 value)
  4473. (cdr property))))
  4474. (if property (setcdr property value)
  4475. (push (cons 'property value) alist)))))
  4476. ((equal key "STARTUP")
  4477. (let ((startup (assq 'startup alist)))
  4478. (if startup
  4479. (setcdr startup
  4480. (append (cdr startup) (org-split-string value)))
  4481. (push (cons 'startup (org-split-string value)) alist))))
  4482. ((equal key "TAGS")
  4483. (let ((tag-cell (assq 'tags alist)))
  4484. (if tag-cell
  4485. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4486. (push (cons 'tags value) alist))))
  4487. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4488. (let ((todo (assq 'todo alist))
  4489. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4490. (org-split-string value))))
  4491. (if todo (push value (cdr todo))
  4492. (push (list 'todo value) alist))))
  4493. ((equal key "SETUPFILE")
  4494. (unless buffer-read-only ; Do not check in Gnus messages.
  4495. (let ((f (and (org-string-nw-p value)
  4496. (expand-file-name
  4497. (org-unbracket-string "\"" "\"" value)))))
  4498. (when (and f (file-readable-p f) (not (member f files)))
  4499. (with-temp-buffer
  4500. (setq default-directory (file-name-directory f))
  4501. (insert-file-contents f)
  4502. (setq alist
  4503. ;; Fake Org mode to benefit from cache
  4504. ;; without recurring needlessly.
  4505. (let ((major-mode 'org-mode))
  4506. (org--setup-collect-keywords
  4507. regexp (cons f files) alist)))))))))))))))
  4508. alist)
  4509. (defun org-tag-string-to-alist (s)
  4510. "Return tag alist associated to string S.
  4511. S is a value for TAGS keyword or produced with
  4512. `org-tag-alist-to-string'. Return value is an alist suitable for
  4513. `org-tag-alist' or `org-tag-persistent-alist'."
  4514. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4515. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4516. "\\|{.+?}\\)" ; regular expression
  4517. "\\(?:(\\(.\\))\\)?\\'"))
  4518. alist group-flag)
  4519. (dolist (tokens lines (cdr (nreverse alist)))
  4520. (push '(:newline) alist)
  4521. (while tokens
  4522. (let ((token (pop tokens)))
  4523. (pcase token
  4524. ("{"
  4525. (push '(:startgroup) alist)
  4526. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4527. ("}"
  4528. (push '(:endgroup) alist)
  4529. (setq group-flag nil))
  4530. ("["
  4531. (push '(:startgrouptag) alist)
  4532. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4533. ("]"
  4534. (push '(:endgrouptag) alist)
  4535. (setq group-flag nil))
  4536. (":"
  4537. (push '(:grouptags) alist))
  4538. ((guard (string-match tag-re token))
  4539. (let ((tag (match-string 1 token))
  4540. (key (and (match-beginning 2)
  4541. (string-to-char (match-string 2 token)))))
  4542. ;; Push all tags in groups, no matter if they already
  4543. ;; appear somewhere else in the list.
  4544. (when (or group-flag (not (assoc tag alist)))
  4545. (push (cons tag key) alist))))))))))
  4546. (defun org-tag-alist-to-string (alist &optional skip-key)
  4547. "Return tag string associated to ALIST.
  4548. ALIST is an alist, as defined in `org-tag-alist' or
  4549. `org-tag-persistent-alist', or produced with
  4550. `org-tag-string-to-alist'.
  4551. Return value is a string suitable as a value for \"TAGS\"
  4552. keyword.
  4553. When optional argument SKIP-KEY is non-nil, skip selection keys
  4554. next to tags."
  4555. (mapconcat (lambda (token)
  4556. (pcase token
  4557. (`(:startgroup) "{")
  4558. (`(:endgroup) "}")
  4559. (`(:startgrouptag) "[")
  4560. (`(:endgrouptag) "]")
  4561. (`(:grouptags) ":")
  4562. (`(:newline) "\\n")
  4563. ((and
  4564. (guard (not skip-key))
  4565. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4566. (format "%s(%c)" tag key))
  4567. (`(,(and tag (pred stringp)) . ,_) tag)
  4568. (_ (user-error "Invalid tag token: %S" token))))
  4569. alist
  4570. " "))
  4571. (defun org-tag-alist-to-groups (alist)
  4572. "Return group alist from tag ALIST.
  4573. ALIST is an alist, as defined in `org-tag-alist' or
  4574. `org-tag-persistent-alist', or produced with
  4575. `org-tag-string-to-alist'. Return value is an alist following
  4576. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4577. a string, summarizing TAGS, as a list of strings."
  4578. (let (groups group-status current-group)
  4579. (dolist (token alist (nreverse groups))
  4580. (pcase token
  4581. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4582. (`(,(or :endgroup :endgrouptag))
  4583. (when (eq group-status 'append)
  4584. (push (nreverse current-group) groups))
  4585. (setq group-status nil))
  4586. (`(:grouptags) (setq group-status 'append))
  4587. ((and `(,tag . ,_) (guard group-status))
  4588. (if (eq group-status 'append) (push tag current-group)
  4589. (setq current-group (list tag))))
  4590. (_ nil)))))
  4591. (defun org-file-contents (file &optional noerror)
  4592. "Return the contents of FILE, as a string."
  4593. (if (and file (file-readable-p file))
  4594. (with-temp-buffer
  4595. (insert-file-contents file)
  4596. (buffer-string))
  4597. (funcall (if noerror 'message 'error)
  4598. "Cannot read file \"%s\"%s"
  4599. file
  4600. (let ((from (buffer-file-name (buffer-base-buffer))))
  4601. (if from (concat " (referenced in file \"" from "\")") "")))))
  4602. (defun org-extract-log-state-settings (x)
  4603. "Extract the log state setting from a TODO keyword string.
  4604. This will extract info from a string like \"WAIT(w@/!)\"."
  4605. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4606. (let ((kw (match-string 1 x))
  4607. (log1 (and (match-end 3) (match-string 3 x)))
  4608. (log2 (and (match-end 4) (match-string 4 x))))
  4609. (and (or log1 log2)
  4610. (list kw
  4611. (and log1 (if (equal log1 "!") 'time 'note))
  4612. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4613. (defun org-remove-keyword-keys (list)
  4614. "Remove a pair of parenthesis at the end of each string in LIST."
  4615. (mapcar (lambda (x)
  4616. (if (string-match "(.*)$" x)
  4617. (substring x 0 (match-beginning 0))
  4618. x))
  4619. list))
  4620. (defun org-assign-fast-keys (alist)
  4621. "Assign fast keys to a keyword-key alist.
  4622. Respect keys that are already there."
  4623. (let (new e (alt ?0))
  4624. (while (setq e (pop alist))
  4625. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4626. (cdr e)) ;; Key already assigned.
  4627. (push e new)
  4628. (let ((clist (string-to-list (downcase (car e))))
  4629. (used (append new alist)))
  4630. (when (= (car clist) ?@)
  4631. (pop clist))
  4632. (while (and clist (rassoc (car clist) used))
  4633. (pop clist))
  4634. (unless clist
  4635. (while (rassoc alt used)
  4636. (cl-incf alt)))
  4637. (push (cons (car e) (or (car clist) alt)) new))))
  4638. (nreverse new)))
  4639. ;;; Some variables used in various places
  4640. (defvar org-window-configuration nil
  4641. "Used in various places to store a window configuration.")
  4642. (defvar org-selected-window nil
  4643. "Used in various places to store a window configuration.")
  4644. (defvar org-finish-function nil
  4645. "Function to be called when `C-c C-c' is used.
  4646. This is for getting out of special buffers like capture.")
  4647. (defvar org-last-state)
  4648. ;; Defined somewhere in this file, but used before definition.
  4649. (defvar org-entities) ;; defined in org-entities.el
  4650. (defvar org-struct-menu)
  4651. (defvar org-org-menu)
  4652. (defvar org-tbl-menu)
  4653. ;;;; Define the Org mode
  4654. ;; We use a before-change function to check if a table might need
  4655. ;; an update.
  4656. (defvar org-table-may-need-update t
  4657. "Indicates that a table might need an update.
  4658. This variable is set by `org-before-change-function'.
  4659. `org-table-align' sets it back to nil.")
  4660. (defun org-before-change-function (_beg _end)
  4661. "Every change indicates that a table might need an update."
  4662. (setq org-table-may-need-update t))
  4663. (defvar org-mode-map)
  4664. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4665. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4666. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4667. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4668. (defvar org-table-buffer-is-an nil)
  4669. (defvar bidi-paragraph-direction)
  4670. (defvar buffer-face-mode-face)
  4671. (require 'outline)
  4672. ;; Other stuff we need.
  4673. (require 'time-date)
  4674. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4675. (require 'easymenu)
  4676. (autoload 'easy-menu-add "easymenu")
  4677. (require 'overlay)
  4678. ;; (require 'org-macs) moved higher up in the file before it is first used
  4679. (require 'org-entities)
  4680. ;; (require 'org-compat) moved higher up in the file before it is first used
  4681. (require 'org-faces)
  4682. (require 'org-list)
  4683. (require 'org-pcomplete)
  4684. (require 'org-src)
  4685. (require 'org-footnote)
  4686. (require 'org-macro)
  4687. ;; babel
  4688. (require 'ob)
  4689. ;;;###autoload
  4690. (define-derived-mode org-mode outline-mode "Org"
  4691. "Outline-based notes management and organizer, alias
  4692. \"Carsten's outline-mode for keeping track of everything.\"
  4693. Org mode develops organizational tasks around a NOTES file which
  4694. contains information about projects as plain text. Org mode is
  4695. implemented on top of Outline mode, which is ideal to keep the content
  4696. of large files well structured. It supports ToDo items, deadlines and
  4697. time stamps, which magically appear in the diary listing of the Emacs
  4698. calendar. Tables are easily created with a built-in table editor.
  4699. Plain text URL-like links connect to websites, emails (VM), Usenet
  4700. messages (Gnus), BBDB entries, and any files related to the project.
  4701. For printing and sharing of notes, an Org file (or a part of it)
  4702. can be exported as a structured ASCII or HTML file.
  4703. The following commands are available:
  4704. \\{org-mode-map}"
  4705. ;; Get rid of Outline menus, they are not needed
  4706. ;; Need to do this here because define-derived-mode sets up
  4707. ;; the keymap so late. Still, it is a waste to call this each time
  4708. ;; we switch another buffer into Org mode.
  4709. (define-key org-mode-map [menu-bar headings] 'undefined)
  4710. (define-key org-mode-map [menu-bar hide] 'undefined)
  4711. (define-key org-mode-map [menu-bar show] 'undefined)
  4712. (org-load-modules-maybe)
  4713. (org-install-agenda-files-menu)
  4714. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4715. (add-to-invisibility-spec '(org-cwidth))
  4716. (add-to-invisibility-spec '(org-hide-block . t))
  4717. (setq-local outline-regexp org-outline-regexp)
  4718. (setq-local outline-level 'org-outline-level)
  4719. (setq bidi-paragraph-direction 'left-to-right)
  4720. (when (and org-ellipsis
  4721. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4722. (fboundp 'make-glyph-code))
  4723. (unless org-display-table
  4724. (setq org-display-table (make-display-table)))
  4725. (set-display-table-slot
  4726. org-display-table 4
  4727. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4728. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4729. (setq buffer-display-table org-display-table))
  4730. (org-set-regexps-and-options)
  4731. (org-set-font-lock-defaults)
  4732. (when (and org-tag-faces (not org-tags-special-faces-re))
  4733. ;; tag faces set outside customize.... force initialization.
  4734. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4735. ;; Calc embedded
  4736. (setq-local calc-embedded-open-mode "# ")
  4737. ;; Modify a few syntax entries
  4738. (modify-syntax-entry ?@ "w")
  4739. (modify-syntax-entry ?\" "\"")
  4740. (modify-syntax-entry ?\\ "_")
  4741. (modify-syntax-entry ?~ "_")
  4742. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4743. ;; Activate before-change-function
  4744. (setq-local org-table-may-need-update t)
  4745. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4746. ;; Check for running clock before killing a buffer
  4747. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4748. ;; Initialize macros templates.
  4749. (org-macro-initialize-templates)
  4750. ;; Initialize radio targets.
  4751. (org-update-radio-target-regexp)
  4752. ;; Indentation.
  4753. (setq-local indent-line-function 'org-indent-line)
  4754. (setq-local indent-region-function 'org-indent-region)
  4755. ;; Filling and auto-filling.
  4756. (org-setup-filling)
  4757. ;; Comments.
  4758. (org-setup-comments-handling)
  4759. ;; Initialize cache.
  4760. (org-element-cache-reset)
  4761. ;; Beginning/end of defun
  4762. (setq-local beginning-of-defun-function 'org-backward-element)
  4763. (setq-local end-of-defun-function
  4764. (lambda ()
  4765. (if (not (org-at-heading-p))
  4766. (org-forward-element)
  4767. (org-forward-element)
  4768. (forward-char -1))))
  4769. ;; Next error for sparse trees
  4770. (setq-local next-error-function 'org-occur-next-match)
  4771. ;; Make sure dependence stuff works reliably, even for users who set it
  4772. ;; too late :-(
  4773. (if org-enforce-todo-dependencies
  4774. (add-hook 'org-blocker-hook
  4775. 'org-block-todo-from-children-or-siblings-or-parent)
  4776. (remove-hook 'org-blocker-hook
  4777. 'org-block-todo-from-children-or-siblings-or-parent))
  4778. (if org-enforce-todo-checkbox-dependencies
  4779. (add-hook 'org-blocker-hook
  4780. 'org-block-todo-from-checkboxes)
  4781. (remove-hook 'org-blocker-hook
  4782. 'org-block-todo-from-checkboxes))
  4783. ;; Align options lines
  4784. (setq-local
  4785. align-mode-rules-list
  4786. '((org-in-buffer-settings
  4787. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4788. (modes . '(org-mode)))))
  4789. ;; Imenu
  4790. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4791. ;; Make isearch reveal context
  4792. (setq-local outline-isearch-open-invisible-function
  4793. (lambda (&rest _) (org-show-context 'isearch)))
  4794. ;; Setup the pcomplete hooks
  4795. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4796. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4797. (setq-local pcomplete-default-completion-function 'ignore)
  4798. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4799. (setq-local pcomplete-termination-string "")
  4800. (setq-local buffer-face-mode-face 'org-default)
  4801. ;; If empty file that did not turn on Org mode automatically, make
  4802. ;; it to.
  4803. (when (and org-insert-mode-line-in-empty-file
  4804. (called-interactively-p 'any)
  4805. (= (point-min) (point-max)))
  4806. (insert "# -*- mode: org -*-\n\n"))
  4807. (unless org-inhibit-startup
  4808. (org-unmodified
  4809. (when org-startup-with-beamer-mode (org-beamer-mode))
  4810. (when org-startup-align-all-tables
  4811. (org-table-map-tables #'org-table-align t))
  4812. (when org-startup-with-inline-images (org-display-inline-images))
  4813. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4814. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4815. (when org-startup-truncated (setq truncate-lines t))
  4816. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4817. (org-refresh-effort-properties)))
  4818. ;; Try to set `org-hide' face correctly.
  4819. (let ((foreground (org-find-invisible-foreground)))
  4820. (when foreground
  4821. (set-face-foreground 'org-hide foreground))))
  4822. ;; Update `customize-package-emacs-version-alist'
  4823. (add-to-list 'customize-package-emacs-version-alist
  4824. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4825. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4826. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4827. ("9.0" . "26.1")))
  4828. (defvar org-mode-transpose-word-syntax-table
  4829. (let ((st (make-syntax-table text-mode-syntax-table)))
  4830. (dolist (c org-emphasis-alist st)
  4831. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4832. (when (fboundp 'abbrev-table-put)
  4833. (abbrev-table-put org-mode-abbrev-table
  4834. :parents (list text-mode-abbrev-table)))
  4835. (defun org-find-invisible-foreground ()
  4836. (let ((candidates (remove
  4837. "unspecified-bg"
  4838. (nconc
  4839. (list (face-background 'default)
  4840. (face-background 'org-default))
  4841. (mapcar
  4842. (lambda (alist)
  4843. (when (boundp alist)
  4844. (cdr (assq 'background-color (symbol-value alist)))))
  4845. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4846. (list (face-foreground 'org-hide))))))
  4847. (car (remove nil candidates))))
  4848. (defun org-current-time (&optional rounding-minutes past)
  4849. "Current time, possibly rounded to ROUNDING-MINUTES.
  4850. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4851. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4852. the rounding returns a past time."
  4853. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4854. (car org-time-stamp-rounding-minutes)))
  4855. (time (decode-time)) res)
  4856. (if (< r 1)
  4857. (current-time)
  4858. (setq res
  4859. (apply 'encode-time
  4860. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4861. (nthcdr 2 time))))
  4862. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4863. (seconds-to-time (- (float-time res) (* r 60)))
  4864. res))))
  4865. (defun org-today ()
  4866. "Return today date, considering `org-extend-today-until'."
  4867. (time-to-days
  4868. (time-subtract (current-time)
  4869. (list 0 (* 3600 org-extend-today-until) 0))))
  4870. ;;;; Font-Lock stuff, including the activators
  4871. (defvar org-mouse-map (make-sparse-keymap))
  4872. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4873. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4874. (when org-mouse-1-follows-link
  4875. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  4876. (when org-tab-follows-link
  4877. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  4878. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  4879. (require 'font-lock)
  4880. (defconst org-non-link-chars "]\t\n\r<>")
  4881. (defvar org-link-types-re nil
  4882. "Matches a link that has a url-like prefix like \"http:\"")
  4883. (defvar org-link-re-with-space nil
  4884. "Matches a link with spaces, optional angular brackets around it.")
  4885. (defvar org-link-re-with-space2 nil
  4886. "Matches a link with spaces, optional angular brackets around it.")
  4887. (defvar org-link-re-with-space3 nil
  4888. "Matches a link with spaces, only for internal part in bracket links.")
  4889. (defvar org-angle-link-re nil
  4890. "Matches link with angular brackets, spaces are allowed.")
  4891. (defvar org-plain-link-re nil
  4892. "Matches plain link, without spaces.")
  4893. (defvar org-bracket-link-regexp nil
  4894. "Matches a link in double brackets.")
  4895. (defvar org-bracket-link-analytic-regexp nil
  4896. "Regular expression used to analyze links.
  4897. Here is what the match groups contain after a match:
  4898. 1: http:
  4899. 2: http
  4900. 3: path
  4901. 4: [desc]
  4902. 5: desc")
  4903. (defvar org-bracket-link-analytic-regexp++ nil
  4904. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  4905. (defvar org-any-link-re nil
  4906. "Regular expression matching any link.")
  4907. (defconst org-match-sexp-depth 3
  4908. "Number of stacked braces for sub/superscript matching.")
  4909. (defun org-create-multibrace-regexp (left right n)
  4910. "Create a regular expression which will match a balanced sexp.
  4911. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4912. as single character strings.
  4913. The regexp returned will match the entire expression including the
  4914. delimiters. It will also define a single group which contains the
  4915. match except for the outermost delimiters. The maximum depth of
  4916. stacked delimiters is N. Escaping delimiters is not possible."
  4917. (let* ((nothing (concat "[^" left right "]*?"))
  4918. (or "\\|")
  4919. (re nothing)
  4920. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4921. (while (> n 1)
  4922. (setq n (1- n)
  4923. re (concat re or next)
  4924. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4925. (concat left "\\(" re "\\)" right)))
  4926. (defconst org-match-substring-regexp
  4927. (concat
  4928. "\\(\\S-\\)\\([_^]\\)\\("
  4929. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4930. "\\|"
  4931. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4932. "\\|"
  4933. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4934. "The regular expression matching a sub- or superscript.")
  4935. (defconst org-match-substring-with-braces-regexp
  4936. (concat
  4937. "\\(\\S-\\)\\([_^]\\)"
  4938. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4939. "The regular expression matching a sub- or superscript, forcing braces.")
  4940. (defun org-make-link-regexps ()
  4941. "Update the link regular expressions.
  4942. This should be called after the variable `org-link-parameters' has changed."
  4943. (let ((types-re (regexp-opt (org-link-types) t)))
  4944. (setq org-link-types-re
  4945. (concat "\\`" types-re ":")
  4946. org-link-re-with-space
  4947. (concat "<?" types-re ":"
  4948. "\\([^" org-non-link-chars " ]"
  4949. "[^" org-non-link-chars "]*"
  4950. "[^" org-non-link-chars " ]\\)>?")
  4951. org-link-re-with-space2
  4952. (concat "<?" types-re ":"
  4953. "\\([^" org-non-link-chars " ]"
  4954. "[^\t\n\r]*"
  4955. "[^" org-non-link-chars " ]\\)>?")
  4956. org-link-re-with-space3
  4957. (concat "<?" types-re ":"
  4958. "\\([^" org-non-link-chars " ]"
  4959. "[^\t\n\r]*\\)")
  4960. org-angle-link-re
  4961. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  4962. types-re)
  4963. org-plain-link-re
  4964. (concat
  4965. "\\<" types-re ":"
  4966. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  4967. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  4968. org-bracket-link-regexp
  4969. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  4970. org-bracket-link-analytic-regexp
  4971. (concat
  4972. "\\[\\["
  4973. "\\(" types-re ":\\)?"
  4974. "\\([^]]+\\)"
  4975. "\\]"
  4976. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4977. "\\]")
  4978. org-bracket-link-analytic-regexp++
  4979. (concat
  4980. "\\[\\["
  4981. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  4982. "\\([^]]+\\)"
  4983. "\\]"
  4984. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  4985. "\\]")
  4986. org-any-link-re
  4987. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  4988. org-angle-link-re "\\)\\|\\("
  4989. org-plain-link-re "\\)"))))
  4990. (org-make-link-regexps)
  4991. (defvar org-emph-face nil)
  4992. (defun org-do-emphasis-faces (limit)
  4993. "Run through the buffer and emphasize strings."
  4994. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4995. (car org-emphasis-regexp-components))))
  4996. (catch :exit
  4997. (while (re-search-forward quick-re limit t)
  4998. (let* ((marker (match-string 2))
  4999. (verbatim? (member marker '("~" "="))))
  5000. (when (save-excursion
  5001. (goto-char (match-beginning 0))
  5002. ;; Do not match headline stars. Do not consider
  5003. ;; stars of a headline as closing marker for bold
  5004. ;; markup either.
  5005. (and (not (looking-at-p org-outline-regexp-bol))
  5006. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  5007. (not (string-match-p
  5008. (concat org-outline-regexp-bol "\\'")
  5009. (match-string 0)))))
  5010. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
  5011. (font-lock-prepend-text-property
  5012. (match-beginning 2) (match-end 2) 'face face)
  5013. (when verbatim?
  5014. (org-remove-flyspell-overlays-in
  5015. (match-beginning 0) (match-end 0)))
  5016. (add-text-properties (match-beginning 2) (match-end 2)
  5017. '(font-lock-multiline t org-emphasis t))
  5018. (when org-hide-emphasis-markers
  5019. (add-text-properties (match-end 4) (match-beginning 5)
  5020. '(invisible org-link))
  5021. (add-text-properties (match-beginning 3) (match-end 3)
  5022. '(invisible org-link)))
  5023. (throw :exit t))))))))
  5024. (defun org-emphasize (&optional char)
  5025. "Insert or change an emphasis, i.e. a font like bold or italic.
  5026. If there is an active region, change that region to a new emphasis.
  5027. If there is no region, just insert the marker characters and position
  5028. the cursor between them.
  5029. CHAR should be the marker character. If it is a space, it means to
  5030. remove the emphasis of the selected region.
  5031. If CHAR is not given (for example in an interactive call) it will be
  5032. prompted for."
  5033. (interactive)
  5034. (let ((erc org-emphasis-regexp-components)
  5035. (string "") beg end move s)
  5036. (if (org-region-active-p)
  5037. (setq beg (region-beginning)
  5038. end (region-end)
  5039. string (buffer-substring beg end))
  5040. (setq move t))
  5041. (unless char
  5042. (message "Emphasis marker or tag: [%s]"
  5043. (mapconcat #'car org-emphasis-alist ""))
  5044. (setq char (read-char-exclusive)))
  5045. (if (equal char ?\s)
  5046. (setq s ""
  5047. move nil)
  5048. (unless (assoc (char-to-string char) org-emphasis-alist)
  5049. (user-error "No such emphasis marker: \"%c\"" char))
  5050. (setq s (char-to-string char)))
  5051. (while (and (> (length string) 1)
  5052. (equal (substring string 0 1) (substring string -1))
  5053. (assoc (substring string 0 1) org-emphasis-alist))
  5054. (setq string (substring string 1 -1)))
  5055. (setq string (concat s string s))
  5056. (when beg (delete-region beg end))
  5057. (unless (or (bolp)
  5058. (string-match (concat "[" (nth 0 erc) "\n]")
  5059. (char-to-string (char-before (point)))))
  5060. (insert " "))
  5061. (unless (or (eobp)
  5062. (string-match (concat "[" (nth 1 erc) "\n]")
  5063. (char-to-string (char-after (point)))))
  5064. (insert " ") (backward-char 1))
  5065. (insert string)
  5066. (and move (backward-char 1))))
  5067. (defconst org-nonsticky-props
  5068. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5069. (defsubst org-rear-nonsticky-at (pos)
  5070. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5071. (defun org-activate-links (limit)
  5072. "Add link properties to links.
  5073. This includes angle, plain, and bracket links."
  5074. (catch :exit
  5075. (while (re-search-forward org-any-link-re limit t)
  5076. (let* ((start (match-beginning 0))
  5077. (end (match-end 0))
  5078. (type (cond ((eq ?< (char-after start)) 'angle)
  5079. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5080. (t 'plain))))
  5081. (when (and (memq type org-highlight-links)
  5082. ;; Do not confuse plain links with tags.
  5083. (not (and (eq type 'plain)
  5084. (let ((face (get-text-property
  5085. (max (1- start) (point-min)) 'face)))
  5086. (if (consp face) (memq 'org-tag face)
  5087. (eq 'org-tag face))))))
  5088. (let* ((link (pcase type ;extract URL part
  5089. (`plain (match-string-no-properties 0))
  5090. (`angle (buffer-substring-no-properties
  5091. (1+ start) (1- end)))
  5092. (_ (match-string-no-properties 2))))
  5093. (path (save-match-data
  5094. (and (string-match ":" link) ;remove type
  5095. (substring link (match-end 0)))))
  5096. (properties ;for link's visible part
  5097. (list
  5098. 'face (pcase (org-link-get-parameter type :face)
  5099. ((and (pred functionp) face) (funcall face path))
  5100. ((and (pred facep) face) face)
  5101. ((and (pred consp) face) face) ;anonymous
  5102. (_ 'org-link))
  5103. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5104. 'highlight)
  5105. 'keymap (or (org-link-get-parameter type :keymap)
  5106. org-mouse-map)
  5107. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5108. ((and (pred stringp) echo) echo)
  5109. ((and (pred functionp) echo) echo)
  5110. (_ (concat "LINK: "
  5111. (save-match-data
  5112. (org-link-unescape
  5113. (org-link-expand-abbrev link))))))
  5114. 'htmlize-link (pcase (org-link-get-parameter type
  5115. :htmlize-link)
  5116. ((and (pred functionp) f) (funcall f))
  5117. (_ `(:uri ,link)))
  5118. 'font-lock-multiline t)))
  5119. (org-remove-flyspell-overlays-in start end)
  5120. (org-rear-nonsticky-at end)
  5121. (if (not (eq 'bracket type))
  5122. (add-text-properties start end properties)
  5123. ;; Handle invisible parts in bracket links.
  5124. (remove-text-properties start end '(invisible nil))
  5125. (let ((hidden
  5126. (append `(invisible
  5127. ,(or (org-link-get-parameter type :display)
  5128. 'org-link))
  5129. properties))
  5130. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5131. (visible-end (or (match-end 4) (match-end 2))))
  5132. (add-text-properties start visible-start hidden)
  5133. (add-text-properties visible-start visible-end properties)
  5134. (add-text-properties visible-end end hidden)
  5135. (org-rear-nonsticky-at visible-start)
  5136. (org-rear-nonsticky-at visible-end)))
  5137. (let ((f (org-link-get-parameter type :activate-func)))
  5138. (when (functionp f)
  5139. (funcall f start end path (eq type 'bracket))))
  5140. (throw :exit t))))) ;signal success
  5141. nil))
  5142. (defun org-activate-code (limit)
  5143. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5144. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5145. (remove-text-properties (match-beginning 0) (match-end 0)
  5146. '(display t invisible t intangible t))
  5147. t))
  5148. (defcustom org-src-fontify-natively t
  5149. "When non-nil, fontify code in code blocks.
  5150. See also the `org-block' face."
  5151. :type 'boolean
  5152. :version "24.4"
  5153. :package-version '(Org . "8.3")
  5154. :group 'org-appearance
  5155. :group 'org-babel)
  5156. (defcustom org-allow-promoting-top-level-subtree nil
  5157. "When non-nil, allow promoting a top level subtree.
  5158. The leading star of the top level headline will be replaced
  5159. by a #."
  5160. :type 'boolean
  5161. :version "24.1"
  5162. :group 'org-appearance)
  5163. (defun org-fontify-meta-lines-and-blocks (limit)
  5164. (condition-case nil
  5165. (org-fontify-meta-lines-and-blocks-1 limit)
  5166. (error (message "org-mode fontification error in %S at %d"
  5167. (current-buffer)
  5168. (line-number-at-pos)))))
  5169. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5170. "Fontify #+ lines and blocks."
  5171. (let ((case-fold-search t))
  5172. (when (re-search-forward
  5173. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5174. limit t)
  5175. (let ((beg (match-beginning 0))
  5176. (block-start (match-end 0))
  5177. (block-end nil)
  5178. (lang (match-string 7))
  5179. (beg1 (line-beginning-position 2))
  5180. (dc1 (downcase (match-string 2)))
  5181. (dc3 (downcase (match-string 3)))
  5182. end end1 quoting block-type)
  5183. (cond
  5184. ((and (match-end 4) (equal dc3 "+begin"))
  5185. ;; Truly a block
  5186. (setq block-type (downcase (match-string 5))
  5187. quoting (member block-type org-protecting-blocks))
  5188. (when (re-search-forward
  5189. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5190. nil t) ;; on purpose, we look further than LIMIT
  5191. (setq end (min (point-max) (match-end 0))
  5192. end1 (min (point-max) (1- (match-beginning 0))))
  5193. (setq block-end (match-beginning 0))
  5194. (when quoting
  5195. (org-remove-flyspell-overlays-in beg1 end1)
  5196. (remove-text-properties beg end
  5197. '(display t invisible t intangible t)))
  5198. (add-text-properties
  5199. beg end '(font-lock-fontified t font-lock-multiline t))
  5200. (add-text-properties beg beg1 '(face org-meta-line))
  5201. (org-remove-flyspell-overlays-in beg beg1)
  5202. (add-text-properties ; For end_src
  5203. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5204. (org-remove-flyspell-overlays-in end1 end)
  5205. (cond
  5206. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5207. (org-src-font-lock-fontify-block lang block-start block-end)
  5208. (add-text-properties beg1 block-end '(src-block t)))
  5209. (quoting
  5210. (add-text-properties beg1 (min (point-max) (1+ end1))
  5211. (list 'face
  5212. (list :inherit
  5213. (let ((face-name
  5214. (intern (format "org-block-%s" lang))))
  5215. (append (and (facep face-name) (list face-name))
  5216. '(org-block))))))) ; end of source block
  5217. ((not org-fontify-quote-and-verse-blocks))
  5218. ((string= block-type "quote")
  5219. (add-face-text-property
  5220. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5221. ((string= block-type "verse")
  5222. (add-face-text-property
  5223. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5224. (add-text-properties beg beg1 '(face org-block-begin-line))
  5225. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5226. '(face org-block-end-line))
  5227. t))
  5228. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5229. (org-remove-flyspell-overlays-in
  5230. (match-beginning 0)
  5231. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5232. (add-text-properties
  5233. beg (match-end 3)
  5234. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5235. '(font-lock-fontified t invisible t)
  5236. '(font-lock-fontified t face org-document-info-keyword)))
  5237. (add-text-properties
  5238. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5239. (if (string-equal dc1 "+title:")
  5240. '(font-lock-fontified t face org-document-title)
  5241. '(font-lock-fontified t face org-document-info))))
  5242. ((string-prefix-p "+caption" dc1)
  5243. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5244. (remove-text-properties (match-beginning 0) (match-end 0)
  5245. '(display t invisible t intangible t))
  5246. ;; Handle short captions.
  5247. (save-excursion
  5248. (beginning-of-line)
  5249. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5250. (add-text-properties (line-beginning-position) (match-end 1)
  5251. '(font-lock-fontified t face org-meta-line))
  5252. (add-text-properties (match-end 0) (line-end-position)
  5253. '(font-lock-fontified t face org-block))
  5254. t)
  5255. ((member dc3 '(" " ""))
  5256. (org-remove-flyspell-overlays-in beg (match-end 0))
  5257. (add-text-properties
  5258. beg (match-end 0)
  5259. '(font-lock-fontified t face font-lock-comment-face)))
  5260. (t ;; just any other in-buffer setting, but not indented
  5261. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5262. (remove-text-properties (match-beginning 0) (match-end 0)
  5263. '(display t invisible t intangible t))
  5264. (add-text-properties beg (match-end 0)
  5265. '(font-lock-fontified t face org-meta-line))
  5266. t))))))
  5267. (defun org-fontify-drawers (limit)
  5268. "Fontify drawers."
  5269. (when (re-search-forward org-drawer-regexp limit t)
  5270. (add-text-properties
  5271. (match-beginning 0) (match-end 0)
  5272. '(font-lock-fontified t face org-special-keyword))
  5273. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5274. t))
  5275. (defun org-fontify-macros (limit)
  5276. "Fontify macros."
  5277. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5278. (add-text-properties
  5279. (match-beginning 0) (match-end 0)
  5280. '(font-lock-fontified t face org-macro))
  5281. (when org-hide-macro-markers
  5282. (add-text-properties (match-end 2) (match-beginning 2)
  5283. '(invisible t))
  5284. (add-text-properties (match-beginning 1) (match-end 1)
  5285. '(invisible t)))
  5286. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5287. t))
  5288. (defun org-activate-footnote-links (limit)
  5289. "Add text properties for footnotes."
  5290. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5291. (when fn
  5292. (let* ((beg (nth 1 fn))
  5293. (end (nth 2 fn))
  5294. (label (car fn))
  5295. (referencep (/= (line-beginning-position) beg)))
  5296. (when (and referencep (nth 3 fn))
  5297. (save-excursion
  5298. (goto-char beg)
  5299. (search-forward (or label "fn:"))
  5300. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5301. (add-text-properties beg end
  5302. (list 'mouse-face 'highlight
  5303. 'keymap org-mouse-map
  5304. 'help-echo
  5305. (if referencep "Footnote reference"
  5306. "Footnote definition")
  5307. 'font-lock-fontified t
  5308. 'font-lock-multiline t
  5309. 'face 'org-footnote))))))
  5310. (defun org-activate-dates (limit)
  5311. "Add text properties for dates."
  5312. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5313. (not (equal (char-before (match-beginning 0)) 91)))
  5314. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5315. (add-text-properties (match-beginning 0) (match-end 0)
  5316. (list 'mouse-face 'highlight
  5317. 'keymap org-mouse-map))
  5318. (org-rear-nonsticky-at (match-end 0))
  5319. (when org-display-custom-times
  5320. (if (match-end 3)
  5321. (org-display-custom-time (match-beginning 3) (match-end 3))
  5322. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5323. t))
  5324. (defvar-local org-target-link-regexp nil
  5325. "Regular expression matching radio targets in plain text.")
  5326. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5327. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5328. border border border))
  5329. "Regular expression matching a link target.")
  5330. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5331. "Regular expression matching a radio target.")
  5332. (defconst org-any-target-regexp
  5333. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5334. "Regular expression matching any target.")
  5335. (defun org-activate-target-links (limit)
  5336. "Add text properties for target matches."
  5337. (when org-target-link-regexp
  5338. (let ((case-fold-search t))
  5339. (when (re-search-forward org-target-link-regexp limit t)
  5340. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5341. (add-text-properties (match-beginning 1) (match-end 1)
  5342. (list 'mouse-face 'highlight
  5343. 'keymap org-mouse-map
  5344. 'help-echo "Radio target link"
  5345. 'org-linked-text t))
  5346. (org-rear-nonsticky-at (match-end 1))
  5347. t))))
  5348. (defun org-update-radio-target-regexp ()
  5349. "Find all radio targets in this file and update the regular expression.
  5350. Also refresh fontification if needed."
  5351. (interactive)
  5352. (let ((old-regexp org-target-link-regexp)
  5353. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5354. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5355. (targets
  5356. (org-with-wide-buffer
  5357. (goto-char (point-min))
  5358. (let (rtn)
  5359. (while (re-search-forward org-radio-target-regexp nil t)
  5360. ;; Make sure point is really within the object.
  5361. (backward-char)
  5362. (let ((obj (org-element-context)))
  5363. (when (eq (org-element-type obj) 'radio-target)
  5364. (cl-pushnew (org-element-property :value obj) rtn
  5365. :test #'equal))))
  5366. rtn))))
  5367. (setq org-target-link-regexp
  5368. (and targets
  5369. (concat before-re
  5370. (mapconcat
  5371. (lambda (x)
  5372. (replace-regexp-in-string
  5373. " +" "\\s-+" (regexp-quote x) t t))
  5374. targets
  5375. "\\|")
  5376. after-re)))
  5377. (unless (equal old-regexp org-target-link-regexp)
  5378. ;; Clean-up cache.
  5379. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5380. ((not org-target-link-regexp) old-regexp)
  5381. (t
  5382. (concat before-re
  5383. (mapconcat
  5384. (lambda (re)
  5385. (substring re (length before-re)
  5386. (- (length after-re))))
  5387. (list old-regexp org-target-link-regexp)
  5388. "\\|")
  5389. after-re)))))
  5390. (org-with-wide-buffer
  5391. (goto-char (point-min))
  5392. (while (re-search-forward regexp nil t)
  5393. (org-element-cache-refresh (match-beginning 1)))))
  5394. ;; Re fontify buffer.
  5395. (when (memq 'radio org-highlight-links)
  5396. (org-restart-font-lock)))))
  5397. (defun org-hide-wide-columns (limit)
  5398. (let (s e)
  5399. (setq s (text-property-any (point) (or limit (point-max))
  5400. 'org-cwidth t))
  5401. (when s
  5402. (setq e (next-single-property-change s 'org-cwidth))
  5403. (add-text-properties s e '(invisible org-cwidth))
  5404. (goto-char e)
  5405. t)))
  5406. (defvar org-latex-and-related-regexp nil
  5407. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5408. (defun org-compute-latex-and-related-regexp ()
  5409. "Compute regular expression for LaTeX, entities and sub/superscript.
  5410. Result depends on variable `org-highlight-latex-and-related'."
  5411. (setq-local
  5412. org-latex-and-related-regexp
  5413. (let* ((re-sub
  5414. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5415. ((eq org-use-sub-superscripts '{})
  5416. (list org-match-substring-with-braces-regexp))
  5417. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5418. (re-latex
  5419. (when (memq 'latex org-highlight-latex-and-related)
  5420. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5421. (delq nil
  5422. (mapcar (lambda (x)
  5423. (and (member (car x) matchers) (nth 1 x)))
  5424. org-latex-regexps)))))
  5425. (re-entities
  5426. (when (memq 'entities org-highlight-latex-and-related)
  5427. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5428. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5429. (defun org-do-latex-and-related (limit)
  5430. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5431. LIMIT bounds the search for syntax to highlight. Stop at first
  5432. highlighted object, if any. Return t if some highlighting was
  5433. done, nil otherwise."
  5434. (when (org-string-nw-p org-latex-and-related-regexp)
  5435. (catch 'found
  5436. (while (re-search-forward org-latex-and-related-regexp limit t)
  5437. (unless
  5438. (cl-some
  5439. (lambda (f)
  5440. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5441. (save-excursion
  5442. (goto-char (1+ (match-beginning 0)))
  5443. (face-at-point nil t)))
  5444. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5445. '(?_ ?^))
  5446. 1
  5447. 0)))
  5448. (font-lock-prepend-text-property
  5449. (+ offset (match-beginning 0)) (match-end 0)
  5450. 'face 'org-latex-and-related)
  5451. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5452. '(font-lock-multiline t)))
  5453. (throw 'found t)))
  5454. nil)))
  5455. (defun org-restart-font-lock ()
  5456. "Restart `font-lock-mode', to force refontification."
  5457. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5458. (font-lock-mode -1)
  5459. (font-lock-mode 1)))
  5460. (defun org-activate-tags (limit)
  5461. (when (re-search-forward
  5462. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5463. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5464. (add-text-properties (match-beginning 1) (match-end 1)
  5465. (list 'mouse-face 'highlight
  5466. 'keymap org-mouse-map))
  5467. (org-rear-nonsticky-at (match-end 1))
  5468. t))
  5469. (defun org-outline-level ()
  5470. "Compute the outline level of the heading at point.
  5471. If this is called at a normal headline, the level is the number
  5472. of stars. Use `org-reduced-level' to remove the effect of
  5473. `org-odd-levels'. Unlike to `org-current-level', this function
  5474. takes into consideration inlinetasks."
  5475. (org-with-wide-buffer
  5476. (end-of-line)
  5477. (if (re-search-backward org-outline-regexp-bol nil t)
  5478. (1- (- (match-end 0) (match-beginning 0)))
  5479. 0)))
  5480. (defvar org-font-lock-keywords nil)
  5481. (defsubst org-re-property (property &optional literal allow-null value)
  5482. "Return a regexp matching a PROPERTY line.
  5483. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5484. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5485. non-nil, match properties even without a value.
  5486. Match group 3 is set to the value when it exists. If there is no
  5487. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5488. With optional argument VALUE, match only property lines with
  5489. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5490. unless LITERAL is non-nil."
  5491. (concat
  5492. "^\\(?4:[ \t]*\\)"
  5493. (format "\\(?1::\\(?2:%s\\):\\)"
  5494. (if literal property (regexp-quote property)))
  5495. (cond (value
  5496. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5497. (if literal value (regexp-quote value))))
  5498. (allow-null
  5499. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5500. (t
  5501. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5502. (defconst org-property-re
  5503. (org-re-property "\\S-+" 'literal t)
  5504. "Regular expression matching a property line.
  5505. There are four matching groups:
  5506. 1: :PROPKEY: including the leading and trailing colon,
  5507. 2: PROPKEY without the leading and trailing colon,
  5508. 3: PROPVAL without leading or trailing spaces,
  5509. 4: the indentation of the current line,
  5510. 5: trailing whitespace.")
  5511. (defvar org-font-lock-hook nil
  5512. "Functions to be called for special font lock stuff.")
  5513. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5514. (defvar org-font-lock-set-keywords-hook nil
  5515. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5516. This is called after `org-font-lock-extra-keywords' is defined, but before
  5517. it is installed to be used by font lock. This can be useful if something
  5518. needs to be inserted at a specific position in the font-lock sequence.")
  5519. (defun org-font-lock-hook (limit)
  5520. "Run `org-font-lock-hook' within LIMIT."
  5521. (run-hook-with-args 'org-font-lock-hook limit))
  5522. (defun org-set-font-lock-defaults ()
  5523. "Set font lock defaults for the current buffer."
  5524. (let* ((em org-fontify-emphasized-text)
  5525. (lk org-highlight-links)
  5526. (org-font-lock-extra-keywords
  5527. (list
  5528. ;; Call the hook
  5529. '(org-font-lock-hook)
  5530. ;; Headlines
  5531. `(,(if org-fontify-whole-heading-line
  5532. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5533. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5534. (1 (org-get-level-face 1))
  5535. (2 (org-get-level-face 2))
  5536. (3 (org-get-level-face 3)))
  5537. ;; Table lines
  5538. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5539. (1 'org-table t))
  5540. ;; Table internals
  5541. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5542. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5543. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5544. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5545. ;; Drawers
  5546. '(org-fontify-drawers)
  5547. ;; Properties
  5548. (list org-property-re
  5549. '(1 'org-special-keyword t)
  5550. '(3 'org-property-value t))
  5551. ;; Link related fontification.
  5552. '(org-activate-links)
  5553. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5554. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5555. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5556. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5557. ;; Targets.
  5558. (list org-any-target-regexp '(0 'org-target t))
  5559. ;; Diary sexps.
  5560. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5561. ;; Macro
  5562. '(org-fontify-macros)
  5563. '(org-hide-wide-columns (0 nil append))
  5564. ;; TODO keyword
  5565. (list (format org-heading-keyword-regexp-format
  5566. org-todo-regexp)
  5567. '(2 (org-get-todo-face 2) t))
  5568. ;; DONE
  5569. (if org-fontify-done-headline
  5570. (list (format org-heading-keyword-regexp-format
  5571. (concat
  5572. "\\(?:"
  5573. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5574. "\\)"))
  5575. '(2 'org-headline-done t))
  5576. nil)
  5577. ;; Priorities
  5578. '(org-font-lock-add-priority-faces)
  5579. ;; Tags
  5580. '(org-font-lock-add-tag-faces)
  5581. ;; Tags groups
  5582. (when (and org-group-tags org-tag-groups-alist)
  5583. (list (concat org-outline-regexp-bol ".+\\(:"
  5584. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5585. ":\\).*$")
  5586. '(1 'org-tag-group prepend)))
  5587. ;; Special keywords
  5588. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5589. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5590. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5591. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5592. ;; Emphasis
  5593. (when em '(org-do-emphasis-faces))
  5594. ;; Checkboxes
  5595. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5596. 1 'org-checkbox prepend)
  5597. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5598. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5599. (0 (org-get-checkbox-statistics-face) t)))
  5600. ;; Description list items
  5601. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5602. 1 'org-list-dt prepend)
  5603. ;; ARCHIVEd headings
  5604. (list (concat
  5605. org-outline-regexp-bol
  5606. "\\(.*:" org-archive-tag ":.*\\)")
  5607. '(1 'org-archived prepend))
  5608. ;; Specials
  5609. '(org-do-latex-and-related)
  5610. '(org-fontify-entities)
  5611. '(org-raise-scripts)
  5612. ;; Code
  5613. '(org-activate-code (1 'org-code t))
  5614. ;; COMMENT
  5615. (list (format
  5616. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5617. org-todo-regexp
  5618. org-comment-string)
  5619. '(9 'org-special-keyword t))
  5620. ;; Blocks and meta lines
  5621. '(org-fontify-meta-lines-and-blocks))))
  5622. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5623. (run-hooks 'org-font-lock-set-keywords-hook)
  5624. ;; Now set the full font-lock-keywords
  5625. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5626. (setq-local font-lock-defaults
  5627. '(org-font-lock-keywords t nil nil backward-paragraph))
  5628. (kill-local-variable 'font-lock-keywords)
  5629. nil))
  5630. (defun org-toggle-pretty-entities ()
  5631. "Toggle the composition display of entities as UTF8 characters."
  5632. (interactive)
  5633. (setq-local org-pretty-entities (not org-pretty-entities))
  5634. (org-restart-font-lock)
  5635. (if org-pretty-entities
  5636. (message "Entities are now displayed as UTF8 characters")
  5637. (save-restriction
  5638. (widen)
  5639. (decompose-region (point-min) (point-max))
  5640. (message "Entities are now displayed as plain text"))))
  5641. (defvar-local org-custom-properties-overlays nil
  5642. "List of overlays used for custom properties.")
  5643. (defun org-toggle-custom-properties-visibility ()
  5644. "Display or hide properties in `org-custom-properties'."
  5645. (interactive)
  5646. (if org-custom-properties-overlays
  5647. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5648. (setq org-custom-properties-overlays nil))
  5649. (when org-custom-properties
  5650. (org-with-wide-buffer
  5651. (goto-char (point-min))
  5652. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5653. (while (re-search-forward regexp nil t)
  5654. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5655. (when (and end (< (point) end))
  5656. ;; Hide first custom property in current drawer.
  5657. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5658. (overlay-put o 'invisible t)
  5659. (overlay-put o 'org-custom-property t)
  5660. (push o org-custom-properties-overlays))
  5661. ;; Hide additional custom properties in the same drawer.
  5662. (while (re-search-forward regexp end t)
  5663. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5664. (overlay-put o 'invisible t)
  5665. (overlay-put o 'org-custom-property t)
  5666. (push o org-custom-properties-overlays)))))
  5667. ;; Each entry is limited to a single property drawer.
  5668. (outline-next-heading)))))))
  5669. (defun org-fontify-entities (limit)
  5670. "Find an entity to fontify."
  5671. (let (ee)
  5672. (when org-pretty-entities
  5673. (catch 'match
  5674. ;; "\_ "-family is left out on purpose. Only the first one,
  5675. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5676. ;; confusing when adding a second white space character.
  5677. (while (re-search-forward
  5678. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5679. limit t)
  5680. (when (and (not (org-at-comment-p))
  5681. (setq ee (org-entity-get (match-string 1)))
  5682. (= (length (nth 6 ee)) 1))
  5683. (let* ((end (if (equal (match-string 2) "{}")
  5684. (match-end 2)
  5685. (match-end 1))))
  5686. (add-text-properties
  5687. (match-beginning 0) end
  5688. (list 'font-lock-fontified t))
  5689. (compose-region (match-beginning 0) end
  5690. (nth 6 ee) nil)
  5691. (backward-char 1)
  5692. (throw 'match t))))
  5693. nil))))
  5694. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5695. "Fontify string S like in Org mode."
  5696. (with-temp-buffer
  5697. (insert s)
  5698. (let ((org-odd-levels-only odd-levels))
  5699. (org-mode)
  5700. (org-font-lock-ensure)
  5701. (buffer-string))))
  5702. (defvar org-m nil)
  5703. (defvar org-l nil)
  5704. (defvar org-f nil)
  5705. (defun org-get-level-face (n)
  5706. "Get the right face for match N in font-lock matching of headlines."
  5707. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5708. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5709. (if org-cycle-level-faces
  5710. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5711. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5712. (cond
  5713. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5714. ((eq n 2) org-f)
  5715. (t (unless org-level-color-stars-only org-f))))
  5716. (defun org-face-from-face-or-color (context inherit face-or-color)
  5717. "Create a face list that inherits INHERIT, but sets the foreground color.
  5718. When FACE-OR-COLOR is not a string, just return it."
  5719. (if (stringp face-or-color)
  5720. (list :inherit inherit
  5721. (cdr (assoc context org-faces-easy-properties))
  5722. face-or-color)
  5723. face-or-color))
  5724. (defun org-get-todo-face (kwd)
  5725. "Get the right face for a TODO keyword KWD.
  5726. If KWD is a number, get the corresponding match group."
  5727. (when (numberp kwd) (setq kwd (match-string kwd)))
  5728. (or (org-face-from-face-or-color
  5729. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5730. (and (member kwd org-done-keywords) 'org-done)
  5731. 'org-todo))
  5732. (defun org-get-priority-face (priority)
  5733. "Get the right face for PRIORITY.
  5734. PRIORITY is a character."
  5735. (or (org-face-from-face-or-color
  5736. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5737. 'org-priority))
  5738. (defun org-get-tag-face (tag)
  5739. "Get the right face for TAG.
  5740. If TAG is a number, get the corresponding match group."
  5741. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5742. (or (org-face-from-face-or-color
  5743. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5744. 'org-tag)))
  5745. (defun org-font-lock-add-priority-faces (limit)
  5746. "Add the special priority faces."
  5747. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5748. (add-text-properties
  5749. (match-beginning 1) (match-end 1)
  5750. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5751. 'font-lock-fontified t))))
  5752. (defun org-font-lock-add-tag-faces (limit)
  5753. "Add the special tag faces."
  5754. (when (and org-tag-faces org-tags-special-faces-re)
  5755. (while (re-search-forward org-tags-special-faces-re limit t)
  5756. (add-text-properties (match-beginning 1) (match-end 1)
  5757. (list 'face (org-get-tag-face 1)
  5758. 'font-lock-fontified t))
  5759. (backward-char 1))))
  5760. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5761. "Remove fontification and activation overlays from links."
  5762. (font-lock-default-unfontify-region beg end)
  5763. (let* ((buffer-undo-list t)
  5764. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5765. (inhibit-modification-hooks t)
  5766. deactivate-mark buffer-file-name buffer-file-truename)
  5767. (decompose-region beg end)
  5768. (remove-text-properties beg end
  5769. '(mouse-face t keymap t org-linked-text t
  5770. invisible t intangible t
  5771. org-emphasis t))
  5772. (org-remove-font-lock-display-properties beg end)))
  5773. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5774. ((raise 0.3) (height 0.7))
  5775. ((raise -0.5))
  5776. ((raise 0.5)))
  5777. "Display properties for showing superscripts and subscripts.")
  5778. (defun org-remove-font-lock-display-properties (beg end)
  5779. "Remove specific display properties that have been added by font lock.
  5780. The will remove the raise properties that are used to show superscripts
  5781. and subscripts."
  5782. (let (next prop)
  5783. (while (< beg end)
  5784. (setq next (next-single-property-change beg 'display nil end)
  5785. prop (get-text-property beg 'display))
  5786. (when (member prop org-script-display)
  5787. (put-text-property beg next 'display nil))
  5788. (setq beg next))))
  5789. (defun org-raise-scripts (limit)
  5790. "Add raise properties to sub/superscripts."
  5791. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5792. (re-search-forward
  5793. (if (eq org-use-sub-superscripts t)
  5794. org-match-substring-regexp
  5795. org-match-substring-with-braces-regexp)
  5796. limit t))
  5797. (let* ((pos (point)) table-p comment-p
  5798. (mpos (match-beginning 3))
  5799. (emph-p (get-text-property mpos 'org-emphasis))
  5800. (link-p (get-text-property mpos 'mouse-face))
  5801. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5802. (goto-char (point-at-bol))
  5803. (setq table-p (looking-at-p org-table-dataline-regexp)
  5804. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5805. (goto-char pos)
  5806. ;; Handle a_b^c
  5807. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5808. (unless (or comment-p emph-p link-p keyw-p)
  5809. (put-text-property (match-beginning 3) (match-end 0)
  5810. 'display
  5811. (if (equal (char-after (match-beginning 2)) ?^)
  5812. (nth (if table-p 3 1) org-script-display)
  5813. (nth (if table-p 2 0) org-script-display)))
  5814. (add-text-properties (match-beginning 2) (match-end 2)
  5815. (list 'invisible t
  5816. 'org-dwidth t 'org-dwidth-n 1))
  5817. (if (and (eq (char-after (match-beginning 3)) ?{)
  5818. (eq (char-before (match-end 3)) ?}))
  5819. (progn
  5820. (add-text-properties
  5821. (match-beginning 3) (1+ (match-beginning 3))
  5822. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5823. (add-text-properties
  5824. (1- (match-end 3)) (match-end 3)
  5825. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5826. t)))
  5827. ;;;; Visibility cycling, including org-goto and indirect buffer
  5828. ;;; Cycling
  5829. (defvar-local org-cycle-global-status nil)
  5830. (put 'org-cycle-global-status 'org-state t)
  5831. (defvar-local org-cycle-subtree-status nil)
  5832. (put 'org-cycle-subtree-status 'org-state t)
  5833. (defvar org-inlinetask-min-level)
  5834. (defun org-unlogged-message (&rest args)
  5835. "Display a message, but avoid logging it in the *Messages* buffer."
  5836. (let ((message-log-max nil))
  5837. (apply 'message args)))
  5838. ;;;###autoload
  5839. (defun org-cycle (&optional arg)
  5840. "TAB-action and visibility cycling for Org mode.
  5841. This is the command invoked in Org mode by the `TAB' key. Its main
  5842. purpose is outline visibility cycling, but it also invokes other actions
  5843. in special contexts.
  5844. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5845. the entire
  5846. buffer through 3 states (global cycling)
  5847. 1. OVERVIEW: Show only top-level headlines.
  5848. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5849. 3. SHOW ALL: Show everything.
  5850. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5851. switch to the startup visibility,
  5852. determined by the variable `org-startup-folded', and by any VISIBILITY
  5853. properties in the buffer.
  5854. With a `\\[universal-argument] \\[universal-argument] \
  5855. \\[universal-argument]' prefix argument, show the entire buffer, including
  5856. any drawers.
  5857. When inside a table, re-align the table and move to the next field.
  5858. When point is at the beginning of a headline, rotate the subtree started
  5859. by this line through 3 different states (local cycling)
  5860. 1. FOLDED: Only the main headline is shown.
  5861. 2. CHILDREN: The main headline and the direct children are shown.
  5862. From this state, you can move to one of the children
  5863. and zoom in further.
  5864. 3. SUBTREE: Show the entire subtree, including body text.
  5865. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5866. When point is at the beginning of an empty headline and the variable
  5867. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5868. of the headline by demoting and promoting it to likely levels. This
  5869. speeds up creation document structure by pressing `TAB' once or several
  5870. times right after creating a new headline.
  5871. When there is a numeric prefix, go up to a heading with level ARG, do
  5872. a `show-subtree' and return to the previous cursor position. If ARG
  5873. is negative, go up that many levels.
  5874. When point is not at the beginning of a headline, execute the global
  5875. binding for `TAB', which is re-indenting the line. See the option
  5876. `org-cycle-emulate-tab' for details.
  5877. As a special case, if point is at the beginning of the buffer and there is
  5878. no headline in line 1, this function will act as if called with prefix arg
  5879. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  5880. prefix arg, but only
  5881. if the variable `org-cycle-global-at-bob' is t."
  5882. (interactive "P")
  5883. (org-load-modules-maybe)
  5884. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5885. (and org-cycle-level-after-item/entry-creation
  5886. (or (org-cycle-level)
  5887. (org-cycle-item-indentation))))
  5888. (let* ((limit-level
  5889. (or org-cycle-max-level
  5890. (and (boundp 'org-inlinetask-min-level)
  5891. org-inlinetask-min-level
  5892. (1- org-inlinetask-min-level))))
  5893. (nstars (and limit-level
  5894. (if org-odd-levels-only
  5895. (and limit-level (1- (* limit-level 2)))
  5896. limit-level)))
  5897. (org-outline-regexp
  5898. (if (not (derived-mode-p 'org-mode))
  5899. outline-regexp
  5900. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  5901. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  5902. (not (looking-at org-outline-regexp))))
  5903. (org-cycle-hook
  5904. (if bob-special
  5905. (delq 'org-optimize-window-after-visibility-change
  5906. (copy-sequence org-cycle-hook))
  5907. org-cycle-hook))
  5908. (pos (point)))
  5909. (cond
  5910. ((equal arg '(16))
  5911. (setq last-command 'dummy)
  5912. (org-set-startup-visibility)
  5913. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5914. ((equal arg '(64))
  5915. (outline-show-all)
  5916. (org-unlogged-message "Entire buffer visible, including drawers"))
  5917. ((equal arg '(4)) (org-cycle-internal-global))
  5918. ;; Try hiding block at point.
  5919. ((org-hide-block-toggle-maybe))
  5920. ;; Try cdlatex TAB completion
  5921. ((org-try-cdlatex-tab))
  5922. ;; Table: enter it or move to the next field.
  5923. ((org-at-table-p 'any)
  5924. (if (org-at-table.el-p)
  5925. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  5926. Use `\\[org-edit-special]' to edit table.el tables"))
  5927. (if arg (org-table-edit-field t)
  5928. (org-table-justify-field-maybe)
  5929. (call-interactively 'org-table-next-field))))
  5930. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  5931. ;; Global cycling: delegate to `org-cycle-internal-global'.
  5932. (bob-special (org-cycle-internal-global))
  5933. ;; Drawers: delegate to `org-flag-drawer'.
  5934. ((save-excursion
  5935. (beginning-of-line 1)
  5936. (looking-at org-drawer-regexp))
  5937. (org-flag-drawer ; toggle block visibility
  5938. (not (get-char-property (match-end 0) 'invisible))))
  5939. ;; Show-subtree, ARG levels up from here.
  5940. ((integerp arg)
  5941. (save-excursion
  5942. (org-back-to-heading)
  5943. (outline-up-heading (if (< arg 0) (- arg)
  5944. (- (funcall outline-level) arg)))
  5945. (org-show-subtree)))
  5946. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5947. ((and (featurep 'org-inlinetask)
  5948. (org-inlinetask-at-task-p)
  5949. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5950. (org-inlinetask-toggle-visibility))
  5951. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5952. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  5953. (save-excursion (move-beginning-of-line 1)
  5954. (looking-at org-outline-regexp)))
  5955. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5956. (org-cycle-internal-local))
  5957. ;; From there: TAB emulation and template completion.
  5958. (buffer-read-only (org-back-to-heading))
  5959. ((run-hook-with-args-until-success
  5960. 'org-tab-after-check-for-cycling-hook))
  5961. ((org-try-structure-completion))
  5962. ((run-hook-with-args-until-success
  5963. 'org-tab-before-tab-emulation-hook))
  5964. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5965. (or (not (bolp))
  5966. (not (looking-at org-outline-regexp))))
  5967. (call-interactively (global-key-binding "\t")))
  5968. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  5969. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5970. (or (and (eq org-cycle-emulate-tab 'white)
  5971. (= (match-end 0) (point-at-eol)))
  5972. (and (eq org-cycle-emulate-tab 'whitestart)
  5973. (>= (match-end 0) pos))))
  5974. t
  5975. (eq org-cycle-emulate-tab t))
  5976. (call-interactively (global-key-binding "\t")))
  5977. (t (save-excursion
  5978. (org-back-to-heading)
  5979. (org-cycle)))))))
  5980. (defun org-cycle-internal-global ()
  5981. "Do the global cycling action."
  5982. ;; Hack to avoid display of messages for .org attachments in Gnus
  5983. (let ((ga (string-match "\\*fontification" (buffer-name))))
  5984. (cond
  5985. ((and (eq last-command this-command)
  5986. (eq org-cycle-global-status 'overview))
  5987. ;; We just created the overview - now do table of contents
  5988. ;; This can be slow in very large buffers, so indicate action
  5989. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5990. (unless ga (org-unlogged-message "CONTENTS..."))
  5991. (org-content)
  5992. (unless ga (org-unlogged-message "CONTENTS...done"))
  5993. (setq org-cycle-global-status 'contents)
  5994. (run-hook-with-args 'org-cycle-hook 'contents))
  5995. ((and (eq last-command this-command)
  5996. (eq org-cycle-global-status 'contents))
  5997. ;; We just showed the table of contents - now show everything
  5998. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5999. (outline-show-all)
  6000. (unless ga (org-unlogged-message "SHOW ALL"))
  6001. (setq org-cycle-global-status 'all)
  6002. (run-hook-with-args 'org-cycle-hook 'all))
  6003. (t
  6004. ;; Default action: go to overview
  6005. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6006. (org-overview)
  6007. (unless ga (org-unlogged-message "OVERVIEW"))
  6008. (setq org-cycle-global-status 'overview)
  6009. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6010. (defvar org-called-with-limited-levels nil
  6011. "Non-nil when `org-with-limited-levels' is currently active.")
  6012. (defun org-cycle-internal-local ()
  6013. "Do the local cycling action."
  6014. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6015. ;; First, determine end of headline (EOH), end of subtree or item
  6016. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6017. (save-excursion
  6018. (if (org-at-item-p)
  6019. (progn
  6020. (beginning-of-line)
  6021. (setq struct (org-list-struct))
  6022. (setq eoh (point-at-eol))
  6023. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6024. (setq has-children (org-list-has-child-p (point) struct)))
  6025. (org-back-to-heading)
  6026. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6027. (setq eos (save-excursion (org-end-of-subtree t t)
  6028. (when (bolp) (backward-char)) (point)))
  6029. (setq has-children
  6030. (or (save-excursion
  6031. (let ((level (funcall outline-level)))
  6032. (outline-next-heading)
  6033. (and (org-at-heading-p t)
  6034. (> (funcall outline-level) level))))
  6035. (save-excursion
  6036. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6037. ;; Determine end invisible part of buffer (EOL)
  6038. (beginning-of-line 2)
  6039. (while (and (not (eobp)) ;This is like `next-line'.
  6040. (get-char-property (1- (point)) 'invisible))
  6041. (goto-char (next-single-char-property-change (point) 'invisible))
  6042. (and (eolp) (beginning-of-line 2)))
  6043. (setq eol (point)))
  6044. ;; Find out what to do next and set `this-command'
  6045. (cond
  6046. ((= eos eoh)
  6047. ;; Nothing is hidden behind this heading
  6048. (unless (org-before-first-heading-p)
  6049. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6050. (org-unlogged-message "EMPTY ENTRY")
  6051. (setq org-cycle-subtree-status nil)
  6052. (save-excursion
  6053. (goto-char eos)
  6054. (outline-next-heading)
  6055. (when (outline-invisible-p) (org-flag-heading nil))))
  6056. ((and (or (>= eol eos)
  6057. (not (string-match "\\S-" (buffer-substring eol eos))))
  6058. (or has-children
  6059. (not (setq children-skipped
  6060. org-cycle-skip-children-state-if-no-children))))
  6061. ;; Entire subtree is hidden in one line: children view
  6062. (unless (org-before-first-heading-p)
  6063. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6064. (if (org-at-item-p)
  6065. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6066. (org-show-entry)
  6067. (org-with-limited-levels (org-show-children))
  6068. ;; FIXME: This slows down the func way too much.
  6069. ;; How keep drawers hidden in subtree anyway?
  6070. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6071. ;; (org-cycle-hide-drawers 'subtree))
  6072. ;; Fold every list in subtree to top-level items.
  6073. (when (eq org-cycle-include-plain-lists 'integrate)
  6074. (save-excursion
  6075. (org-back-to-heading)
  6076. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6077. (beginning-of-line 1)
  6078. (let* ((struct (org-list-struct))
  6079. (prevs (org-list-prevs-alist struct))
  6080. (end (org-list-get-bottom-point struct)))
  6081. (dolist (e (org-list-get-all-items (point) struct prevs))
  6082. (org-list-set-item-visibility e struct 'folded))
  6083. (goto-char (if (< end eos) end eos)))))))
  6084. (org-unlogged-message "CHILDREN")
  6085. (save-excursion
  6086. (goto-char eos)
  6087. (outline-next-heading)
  6088. (when (outline-invisible-p) (org-flag-heading nil)))
  6089. (setq org-cycle-subtree-status 'children)
  6090. (unless (org-before-first-heading-p)
  6091. (run-hook-with-args 'org-cycle-hook 'children)))
  6092. ((or children-skipped
  6093. (and (eq last-command this-command)
  6094. (eq org-cycle-subtree-status 'children)))
  6095. ;; We just showed the children, or no children are there,
  6096. ;; now show everything.
  6097. (unless (org-before-first-heading-p)
  6098. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6099. (outline-flag-region eoh eos nil)
  6100. (org-unlogged-message
  6101. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6102. (setq org-cycle-subtree-status 'subtree)
  6103. (unless (org-before-first-heading-p)
  6104. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6105. (t
  6106. ;; Default action: hide the subtree.
  6107. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6108. (outline-flag-region eoh eos t)
  6109. (org-unlogged-message "FOLDED")
  6110. (setq org-cycle-subtree-status 'folded)
  6111. (unless (org-before-first-heading-p)
  6112. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6113. ;;;###autoload
  6114. (defun org-global-cycle (&optional arg)
  6115. "Cycle the global visibility. For details see `org-cycle'.
  6116. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6117. With a numeric prefix, show all headlines up to that level."
  6118. (interactive "P")
  6119. (let ((org-cycle-include-plain-lists
  6120. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6121. (cond
  6122. ((integerp arg)
  6123. (outline-show-all)
  6124. (outline-hide-sublevels arg)
  6125. (setq org-cycle-global-status 'contents))
  6126. ((equal arg '(4))
  6127. (org-set-startup-visibility)
  6128. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6129. (t
  6130. (org-cycle '(4))))))
  6131. (defun org-set-startup-visibility ()
  6132. "Set the visibility required by startup options and properties."
  6133. (cond
  6134. ((eq org-startup-folded t)
  6135. (org-overview))
  6136. ((eq org-startup-folded 'content)
  6137. (org-content))
  6138. ((or (eq org-startup-folded 'showeverything)
  6139. (eq org-startup-folded nil))
  6140. (outline-show-all)))
  6141. (unless (eq org-startup-folded 'showeverything)
  6142. (when org-hide-block-startup (org-hide-block-all))
  6143. (org-set-visibility-according-to-property 'no-cleanup)
  6144. (org-cycle-hide-archived-subtrees 'all)
  6145. (org-cycle-hide-drawers 'all)
  6146. (org-cycle-show-empty-lines t)))
  6147. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6148. "Switch subtree visibilities according to :VISIBILITY: property."
  6149. (interactive)
  6150. (org-with-wide-buffer
  6151. (goto-char (point-min))
  6152. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6153. (if (not (org-at-property-p)) (outline-next-heading)
  6154. (let ((state (match-string 3)))
  6155. (save-excursion
  6156. (org-back-to-heading t)
  6157. (outline-hide-subtree)
  6158. (org-reveal)
  6159. (cond
  6160. ((equal state "folded")
  6161. (outline-hide-subtree))
  6162. ((equal state "children")
  6163. (org-show-hidden-entry)
  6164. (org-show-children))
  6165. ((equal state "content")
  6166. (save-excursion
  6167. (save-restriction
  6168. (org-narrow-to-subtree)
  6169. (org-content))))
  6170. ((member state '("all" "showall"))
  6171. (outline-show-subtree)))))))
  6172. (unless no-cleanup
  6173. (org-cycle-hide-archived-subtrees 'all)
  6174. (org-cycle-hide-drawers 'all)
  6175. (org-cycle-show-empty-lines 'all))))
  6176. ;; This function uses outline-regexp instead of the more fundamental
  6177. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6178. ;; buffers, where outline-regexp is needed.
  6179. (defun org-overview ()
  6180. "Switch to overview mode, showing only top-level headlines.
  6181. This shows all headlines with a level equal or greater than the level
  6182. of the first headline in the buffer. This is important, because if the
  6183. first headline is not level one, then (hide-sublevels 1) gives confusing
  6184. results."
  6185. (interactive)
  6186. (save-excursion
  6187. (let ((level
  6188. (save-excursion
  6189. (goto-char (point-min))
  6190. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6191. (goto-char (match-beginning 0))
  6192. (funcall outline-level)))))
  6193. (and level (outline-hide-sublevels level)))))
  6194. (defun org-content (&optional arg)
  6195. "Show all headlines in the buffer, like a table of contents.
  6196. With numerical argument N, show content up to level N."
  6197. (interactive "P")
  6198. (org-overview)
  6199. (save-excursion
  6200. ;; Visit all headings and show their offspring
  6201. (and (integerp arg) (org-overview))
  6202. (goto-char (point-max))
  6203. (catch 'exit
  6204. (while (and (progn (condition-case nil
  6205. (outline-previous-visible-heading 1)
  6206. (error (goto-char (point-min))))
  6207. t)
  6208. (looking-at org-outline-regexp))
  6209. (if (integerp arg)
  6210. (org-show-children (1- arg))
  6211. (outline-show-branches))
  6212. (when (bobp) (throw 'exit nil))))))
  6213. (defun org-optimize-window-after-visibility-change (state)
  6214. "Adjust the window after a change in outline visibility.
  6215. This function is the default value of the hook `org-cycle-hook'."
  6216. (when (get-buffer-window (current-buffer))
  6217. (cond
  6218. ((eq state 'content) nil)
  6219. ((eq state 'all) nil)
  6220. ((eq state 'folded) nil)
  6221. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6222. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6223. (defun org-remove-empty-overlays-at (pos)
  6224. "Remove outline overlays that do not contain non-white stuff."
  6225. (dolist (o (overlays-at pos))
  6226. (and (eq 'outline (overlay-get o 'invisible))
  6227. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6228. (overlay-end o))))
  6229. (delete-overlay o))))
  6230. (defun org-clean-visibility-after-subtree-move ()
  6231. "Fix visibility issues after moving a subtree."
  6232. ;; First, find a reasonable region to look at:
  6233. ;; Start two siblings above, end three below
  6234. (let* ((beg (save-excursion
  6235. (and (org-get-last-sibling)
  6236. (org-get-last-sibling))
  6237. (point)))
  6238. (end (save-excursion
  6239. (and (org-get-next-sibling)
  6240. (org-get-next-sibling)
  6241. (org-get-next-sibling))
  6242. (if (org-at-heading-p)
  6243. (point-at-eol)
  6244. (point))))
  6245. (level (looking-at "\\*+"))
  6246. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6247. (save-excursion
  6248. (save-restriction
  6249. (narrow-to-region beg end)
  6250. (when re
  6251. ;; Properly fold already folded siblings
  6252. (goto-char (point-min))
  6253. (while (re-search-forward re nil t)
  6254. (when (and (not (outline-invisible-p))
  6255. (save-excursion
  6256. (goto-char (point-at-eol)) (outline-invisible-p)))
  6257. (outline-hide-entry))))
  6258. (org-cycle-show-empty-lines 'overview)
  6259. (org-cycle-hide-drawers 'overview)))))
  6260. (defun org-cycle-show-empty-lines (state)
  6261. "Show empty lines above all visible headlines.
  6262. The region to be covered depends on STATE when called through
  6263. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6264. entire buffer covered. Note that an empty line is only shown if there
  6265. are at least `org-cycle-separator-lines' empty lines before the headline."
  6266. (when (/= org-cycle-separator-lines 0)
  6267. (save-excursion
  6268. (let* ((n (abs org-cycle-separator-lines))
  6269. (re (cond
  6270. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6271. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6272. (t (let ((ns (number-to-string (- n 2))))
  6273. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6274. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6275. beg end)
  6276. (cond
  6277. ((memq state '(overview contents t))
  6278. (setq beg (point-min) end (point-max)))
  6279. ((memq state '(children folded))
  6280. (setq beg (point)
  6281. end (progn (org-end-of-subtree t t)
  6282. (line-beginning-position 2)))))
  6283. (when beg
  6284. (goto-char beg)
  6285. (while (re-search-forward re end t)
  6286. (unless (get-char-property (match-end 1) 'invisible)
  6287. (let ((e (match-end 1))
  6288. (b (if (>= org-cycle-separator-lines 0)
  6289. (match-beginning 1)
  6290. (save-excursion
  6291. (goto-char (match-beginning 0))
  6292. (skip-chars-backward " \t\n")
  6293. (line-end-position)))))
  6294. (outline-flag-region b e nil))))))))
  6295. ;; Never hide empty lines at the end of the file.
  6296. (save-excursion
  6297. (goto-char (point-max))
  6298. (outline-previous-heading)
  6299. (outline-end-of-heading)
  6300. (when (and (looking-at "[ \t\n]+")
  6301. (= (match-end 0) (point-max)))
  6302. (outline-flag-region (point) (match-end 0) nil))))
  6303. (defun org-show-empty-lines-in-parent ()
  6304. "Move to the parent and re-show empty lines before visible headlines."
  6305. (save-excursion
  6306. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6307. (org-cycle-show-empty-lines context))))
  6308. (defun org-files-list ()
  6309. "Return `org-agenda-files' list, plus all open Org files.
  6310. This is useful for operations that need to scan all of a user's
  6311. open and agenda-wise Org files."
  6312. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6313. (dolist (buf (buffer-list))
  6314. (with-current-buffer buf
  6315. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6316. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6317. files))
  6318. (defsubst org-entry-beginning-position ()
  6319. "Return the beginning position of the current entry."
  6320. (save-excursion (org-back-to-heading t) (point)))
  6321. (defsubst org-entry-end-position ()
  6322. "Return the end position of the current entry."
  6323. (save-excursion (outline-next-heading) (point)))
  6324. (defun org-cycle-hide-drawers (state &optional exceptions)
  6325. "Re-hide all drawers after a visibility state change.
  6326. When non-nil, optional argument EXCEPTIONS is a list of strings
  6327. specifying which drawers should not be hidden."
  6328. (when (and (derived-mode-p 'org-mode)
  6329. (not (memq state '(overview folded contents))))
  6330. (save-excursion
  6331. (let* ((globalp (memq state '(contents all)))
  6332. (beg (if globalp (point-min) (point)))
  6333. (end (if globalp (point-max)
  6334. (if (eq state 'children)
  6335. (save-excursion (outline-next-heading) (point))
  6336. (org-end-of-subtree t)))))
  6337. (goto-char beg)
  6338. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6339. (unless (member-ignore-case (match-string 1) exceptions)
  6340. (let ((drawer (org-element-at-point)))
  6341. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6342. (org-flag-drawer t drawer)
  6343. ;; Make sure to skip drawer entirely or we might flag
  6344. ;; it another time when matching its ending line with
  6345. ;; `org-drawer-regexp'.
  6346. (goto-char (org-element-property :end drawer))))))))))
  6347. (defun org-flag-drawer (flag &optional element)
  6348. "When FLAG is non-nil, hide the drawer we are at.
  6349. Otherwise make it visible. When optional argument ELEMENT is
  6350. a parsed drawer, as returned by `org-element-at-point', hide or
  6351. show that drawer instead."
  6352. (let ((drawer (or element
  6353. (and (save-excursion
  6354. (beginning-of-line)
  6355. (looking-at-p org-drawer-regexp))
  6356. (org-element-at-point)))))
  6357. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6358. (let ((post (org-element-property :post-affiliated drawer)))
  6359. (save-excursion
  6360. (outline-flag-region
  6361. (progn (goto-char post) (line-end-position))
  6362. (progn (goto-char (org-element-property :end drawer))
  6363. (skip-chars-backward " \r\t\n")
  6364. (line-end-position))
  6365. flag))
  6366. ;; When the drawer is hidden away, make sure point lies in
  6367. ;; a visible part of the buffer.
  6368. (when (and flag (> (line-beginning-position) post))
  6369. (goto-char post))))))
  6370. (defun org-subtree-end-visible-p ()
  6371. "Is the end of the current subtree visible?"
  6372. (pos-visible-in-window-p
  6373. (save-excursion (org-end-of-subtree t) (point))))
  6374. (defun org-first-headline-recenter ()
  6375. "Move cursor to the first headline and recenter the headline."
  6376. (let ((window (get-buffer-window)))
  6377. (when window
  6378. (goto-char (point-min))
  6379. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6380. (set-window-start window (line-beginning-position))))))
  6381. ;;; Saving and restoring visibility
  6382. (defun org-outline-overlay-data (&optional use-markers)
  6383. "Return a list of the locations of all outline overlays.
  6384. These are overlays with the `invisible' property value `outline'.
  6385. The return value is a list of cons cells, with start and stop
  6386. positions for each overlay.
  6387. If USE-MARKERS is set, return the positions as markers."
  6388. (let (beg end)
  6389. (org-with-wide-buffer
  6390. (delq nil
  6391. (mapcar (lambda (o)
  6392. (when (eq (overlay-get o 'invisible) 'outline)
  6393. (setq beg (overlay-start o)
  6394. end (overlay-end o))
  6395. (and beg end (> end beg)
  6396. (if use-markers
  6397. (cons (copy-marker beg)
  6398. (copy-marker end t))
  6399. (cons beg end)))))
  6400. (overlays-in (point-min) (point-max)))))))
  6401. (defun org-set-outline-overlay-data (data)
  6402. "Create visibility overlays for all positions in DATA.
  6403. DATA should have been made by `org-outline-overlay-data'."
  6404. (org-with-wide-buffer
  6405. (outline-show-all)
  6406. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6407. ;;; Folding of blocks
  6408. (defvar-local org-hide-block-overlays nil
  6409. "Overlays hiding blocks.")
  6410. (defun org-block-map (function &optional start end)
  6411. "Call FUNCTION at the head of all source blocks in the current buffer.
  6412. Optional arguments START and END can be used to limit the range."
  6413. (let ((start (or start (point-min)))
  6414. (end (or end (point-max))))
  6415. (save-excursion
  6416. (goto-char start)
  6417. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6418. (save-excursion
  6419. (save-match-data
  6420. (goto-char (match-beginning 0))
  6421. (funcall function)))))))
  6422. (defun org-hide-block-toggle-all ()
  6423. "Toggle the visibility of all blocks in the current buffer."
  6424. (org-block-map 'org-hide-block-toggle))
  6425. (defun org-hide-block-all ()
  6426. "Fold all blocks in the current buffer."
  6427. (interactive)
  6428. (org-show-block-all)
  6429. (org-block-map 'org-hide-block-toggle-maybe))
  6430. (defun org-show-block-all ()
  6431. "Unfold all blocks in the current buffer."
  6432. (interactive)
  6433. (mapc #'delete-overlay org-hide-block-overlays)
  6434. (setq org-hide-block-overlays nil))
  6435. (defun org-hide-block-toggle-maybe ()
  6436. "Toggle visibility of block at point.
  6437. Unlike to `org-hide-block-toggle', this function does not throw
  6438. an error. Return a non-nil value when toggling is successful."
  6439. (interactive)
  6440. (ignore-errors (org-hide-block-toggle)))
  6441. (defun org-hide-block-toggle (&optional force)
  6442. "Toggle the visibility of the current block.
  6443. When optional argument FORCE is `off', make block visible. If it
  6444. is non-nil, hide it unconditionally. Throw an error when not at
  6445. a block. Return a non-nil value when toggling is successful."
  6446. (interactive)
  6447. (let ((element (org-element-at-point)))
  6448. (unless (memq (org-element-type element)
  6449. '(center-block comment-block dynamic-block example-block
  6450. export-block quote-block special-block
  6451. src-block verse-block))
  6452. (user-error "Not at a block"))
  6453. (let* ((start (save-excursion
  6454. (goto-char (org-element-property :post-affiliated element))
  6455. (line-end-position)))
  6456. (end (save-excursion
  6457. (goto-char (org-element-property :end element))
  6458. (skip-chars-backward " \r\t\n")
  6459. (line-end-position)))
  6460. (overlays (overlays-at start)))
  6461. (cond
  6462. ;; Do nothing when not before or at the block opening line or
  6463. ;; at the block closing line.
  6464. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6465. ((and (not (eq force 'off))
  6466. (not (memq t (mapcar
  6467. (lambda (o)
  6468. (eq (overlay-get o 'invisible) 'org-hide-block))
  6469. overlays))))
  6470. (let ((ov (make-overlay start end)))
  6471. (overlay-put ov 'invisible 'org-hide-block)
  6472. ;; Make the block accessible to `isearch'.
  6473. (overlay-put
  6474. ov 'isearch-open-invisible
  6475. (lambda (ov)
  6476. (when (memq ov org-hide-block-overlays)
  6477. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6478. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6479. (delete-overlay ov))))
  6480. (push ov org-hide-block-overlays)
  6481. ;; When the block is hidden away, make sure point is left in
  6482. ;; a visible part of the buffer.
  6483. (when (> (line-beginning-position) start)
  6484. (goto-char start)
  6485. (beginning-of-line))
  6486. ;; Signal successful toggling.
  6487. t))
  6488. ((or (not force) (eq force 'off))
  6489. (dolist (ov overlays t)
  6490. (when (memq ov org-hide-block-overlays)
  6491. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6492. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6493. (delete-overlay ov))))))))
  6494. ;; Remove overlays when changing major mode
  6495. (add-hook 'org-mode-hook
  6496. (lambda () (add-hook 'change-major-mode-hook
  6497. 'org-show-block-all 'append 'local)))
  6498. ;;; Org-goto
  6499. (defvar org-goto-window-configuration nil)
  6500. (defvar org-goto-marker nil)
  6501. (defvar org-goto-map)
  6502. (defun org-goto-map ()
  6503. "Set the keymap `org-goto'."
  6504. (setq org-goto-map
  6505. (let ((map (make-sparse-keymap)))
  6506. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6507. mouse-drag-region universal-argument org-occur)))
  6508. (dolist (cmd cmds)
  6509. (substitute-key-definition cmd cmd map global-map)))
  6510. (suppress-keymap map)
  6511. (org-defkey map "\C-m" 'org-goto-ret)
  6512. (org-defkey map [(return)] 'org-goto-ret)
  6513. (org-defkey map [(left)] 'org-goto-left)
  6514. (org-defkey map [(right)] 'org-goto-right)
  6515. (org-defkey map [(control ?g)] 'org-goto-quit)
  6516. (org-defkey map "\C-i" 'org-cycle)
  6517. (org-defkey map [(tab)] 'org-cycle)
  6518. (org-defkey map [(down)] 'outline-next-visible-heading)
  6519. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6520. (if org-goto-auto-isearch
  6521. (if (fboundp 'define-key-after)
  6522. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6523. nil)
  6524. (org-defkey map "q" 'org-goto-quit)
  6525. (org-defkey map "n" 'outline-next-visible-heading)
  6526. (org-defkey map "p" 'outline-previous-visible-heading)
  6527. (org-defkey map "f" 'outline-forward-same-level)
  6528. (org-defkey map "b" 'outline-backward-same-level)
  6529. (org-defkey map "u" 'outline-up-heading))
  6530. (org-defkey map "/" 'org-occur)
  6531. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6532. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6533. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6534. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6535. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6536. map)))
  6537. (defconst org-goto-help
  6538. "Browse buffer copy, to find location or copy text.%s
  6539. RET=jump to location C-g=quit and return to previous location
  6540. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6541. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6542. (defun org-goto (&optional alternative-interface)
  6543. "Look up a different location in the current file, keeping current visibility.
  6544. When you want look-up or go to a different location in a
  6545. document, the fastest way is often to fold the entire buffer and
  6546. then dive into the tree. This method has the disadvantage, that
  6547. the previous location will be folded, which may not be what you
  6548. want.
  6549. This command works around this by showing a copy of the current
  6550. buffer in an indirect buffer, in overview mode. You can dive
  6551. into the tree in that copy, use org-occur and incremental search
  6552. to find a location. When pressing RET or `Q', the command
  6553. returns to the original buffer in which the visibility is still
  6554. unchanged. After RET it will also jump to the location selected
  6555. in the indirect buffer and expose the headline hierarchy above.
  6556. With a prefix argument, use the alternative interface: e.g., if
  6557. `org-goto-interface' is `outline' use `outline-path-completion'."
  6558. (interactive "P")
  6559. (org-goto-map)
  6560. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6561. (org-refile-use-outline-path t)
  6562. (org-refile-target-verify-function nil)
  6563. (interface
  6564. (if (not alternative-interface)
  6565. org-goto-interface
  6566. (if (eq org-goto-interface 'outline)
  6567. 'outline-path-completion
  6568. 'outline)))
  6569. (org-goto-start-pos (point))
  6570. (selected-point
  6571. (if (eq interface 'outline)
  6572. (car (org-get-location (current-buffer) org-goto-help))
  6573. (let ((pa (org-refile-get-location "Goto")))
  6574. (org-refile-check-position pa)
  6575. (nth 3 pa)))))
  6576. (if selected-point
  6577. (progn
  6578. (org-mark-ring-push org-goto-start-pos)
  6579. (goto-char selected-point)
  6580. (when (or (outline-invisible-p) (org-invisible-p2))
  6581. (org-show-context 'org-goto)))
  6582. (message "Quit"))))
  6583. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6584. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6585. (defvar org-goto-local-auto-isearch-map) ; defined below
  6586. (defun org-get-location (_buf help)
  6587. "Let the user select a location in current buffer.
  6588. This function uses a recursive edit. It returns the selected position
  6589. or nil."
  6590. (org-no-popups
  6591. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6592. (isearch-hide-immediately nil)
  6593. (isearch-search-fun-function
  6594. (lambda () 'org-goto-local-search-headings))
  6595. (org-goto-selected-point org-goto-exit-command))
  6596. (save-excursion
  6597. (save-window-excursion
  6598. (delete-other-windows)
  6599. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6600. (pop-to-buffer-same-window
  6601. (condition-case nil
  6602. (make-indirect-buffer (current-buffer) "*org-goto*")
  6603. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6604. (with-output-to-temp-buffer "*Org Help*"
  6605. (princ (format help (if org-goto-auto-isearch
  6606. " Just type for auto-isearch."
  6607. " n/p/f/b/u to navigate, q to quit."))))
  6608. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6609. (setq buffer-read-only nil)
  6610. (let ((org-startup-truncated t)
  6611. (org-startup-folded nil)
  6612. (org-startup-align-all-tables nil))
  6613. (org-mode)
  6614. (org-overview))
  6615. (setq buffer-read-only t)
  6616. (if (and (boundp 'org-goto-start-pos)
  6617. (integer-or-marker-p org-goto-start-pos))
  6618. (progn (goto-char org-goto-start-pos)
  6619. (when (outline-invisible-p)
  6620. (org-show-set-visibility 'lineage)))
  6621. (goto-char (point-min)))
  6622. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6623. (message "Select location and press RET")
  6624. (use-local-map org-goto-map)
  6625. (recursive-edit)))
  6626. (kill-buffer "*org-goto*")
  6627. (cons org-goto-selected-point org-goto-exit-command))))
  6628. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6629. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6630. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6631. (if (fboundp 'isearch-other-control-char)
  6632. (progn
  6633. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6634. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6635. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6636. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6637. (define-key org-goto-local-auto-isearch-map [return] nil))
  6638. (defun org-goto-local-search-headings (string bound noerror)
  6639. "Search and make sure that any matches are in headlines."
  6640. (catch 'return
  6641. (while (if isearch-forward
  6642. (search-forward string bound noerror)
  6643. (search-backward string bound noerror))
  6644. (when (save-match-data
  6645. (and (save-excursion
  6646. (beginning-of-line)
  6647. (looking-at org-complex-heading-regexp))
  6648. (or (not (match-beginning 5))
  6649. (< (point) (match-beginning 5)))))
  6650. (throw 'return (point))))))
  6651. (defun org-goto-local-auto-isearch ()
  6652. "Start isearch."
  6653. (interactive)
  6654. (goto-char (point-min))
  6655. (let ((keys (this-command-keys)))
  6656. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6657. (isearch-mode t)
  6658. (isearch-process-search-char (string-to-char keys)))))
  6659. (defun org-goto-ret (&optional _arg)
  6660. "Finish `org-goto' by going to the new location."
  6661. (interactive "P")
  6662. (setq org-goto-selected-point (point))
  6663. (setq org-goto-exit-command 'return)
  6664. (throw 'exit nil))
  6665. (defun org-goto-left ()
  6666. "Finish `org-goto' by going to the new location."
  6667. (interactive)
  6668. (if (org-at-heading-p)
  6669. (progn
  6670. (beginning-of-line 1)
  6671. (setq org-goto-selected-point (point)
  6672. org-goto-exit-command 'left)
  6673. (throw 'exit nil))
  6674. (user-error "Not on a heading")))
  6675. (defun org-goto-right ()
  6676. "Finish `org-goto' by going to the new location."
  6677. (interactive)
  6678. (if (org-at-heading-p)
  6679. (progn
  6680. (setq org-goto-selected-point (point)
  6681. org-goto-exit-command 'right)
  6682. (throw 'exit nil))
  6683. (user-error "Not on a heading")))
  6684. (defun org-goto-quit ()
  6685. "Finish `org-goto' without cursor motion."
  6686. (interactive)
  6687. (setq org-goto-selected-point nil)
  6688. (setq org-goto-exit-command 'quit)
  6689. (throw 'exit nil))
  6690. ;;; Indirect buffer display of subtrees
  6691. (defvar org-indirect-dedicated-frame nil
  6692. "This is the frame being used for indirect tree display.")
  6693. (defvar org-last-indirect-buffer nil)
  6694. (defun org-tree-to-indirect-buffer (&optional arg)
  6695. "Create indirect buffer and narrow it to current subtree.
  6696. With a numerical prefix ARG, go up to this level and then take that tree.
  6697. If ARG is negative, go up that many levels.
  6698. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6699. indirect buffer previously made with this command, to avoid proliferation of
  6700. indirect buffers. However, when you call the command with a \
  6701. `\\[universal-argument]' prefix, or
  6702. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6703. so that you can work with several indirect buffers at the same time. If
  6704. `org-indirect-buffer-display' is `dedicated-frame', the \
  6705. `\\[universal-argument]' prefix also
  6706. requests that a new frame be made for the new buffer, so that the dedicated
  6707. frame is not changed."
  6708. (interactive "P")
  6709. (let ((cbuf (current-buffer))
  6710. (cwin (selected-window))
  6711. (pos (point))
  6712. beg end level heading ibuf)
  6713. (save-excursion
  6714. (org-back-to-heading t)
  6715. (when (numberp arg)
  6716. (setq level (org-outline-level))
  6717. (when (< arg 0) (setq arg (+ level arg)))
  6718. (while (> (setq level (org-outline-level)) arg)
  6719. (org-up-heading-safe)))
  6720. (setq beg (point)
  6721. heading (org-get-heading 'no-tags))
  6722. (org-end-of-subtree t t)
  6723. (when (org-at-heading-p) (backward-char 1))
  6724. (setq end (point)))
  6725. (when (and (buffer-live-p org-last-indirect-buffer)
  6726. (not (eq org-indirect-buffer-display 'new-frame))
  6727. (not arg))
  6728. (kill-buffer org-last-indirect-buffer))
  6729. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6730. org-last-indirect-buffer ibuf)
  6731. (cond
  6732. ((or (eq org-indirect-buffer-display 'new-frame)
  6733. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6734. (select-frame (make-frame))
  6735. (delete-other-windows)
  6736. (pop-to-buffer-same-window ibuf)
  6737. (org-set-frame-title heading))
  6738. ((eq org-indirect-buffer-display 'dedicated-frame)
  6739. (raise-frame
  6740. (select-frame (or (and org-indirect-dedicated-frame
  6741. (frame-live-p org-indirect-dedicated-frame)
  6742. org-indirect-dedicated-frame)
  6743. (setq org-indirect-dedicated-frame (make-frame)))))
  6744. (delete-other-windows)
  6745. (pop-to-buffer-same-window ibuf)
  6746. (org-set-frame-title (concat "Indirect: " heading)))
  6747. ((eq org-indirect-buffer-display 'current-window)
  6748. (pop-to-buffer-same-window ibuf))
  6749. ((eq org-indirect-buffer-display 'other-window)
  6750. (pop-to-buffer ibuf))
  6751. (t (error "Invalid value")))
  6752. (narrow-to-region beg end)
  6753. (outline-show-all)
  6754. (goto-char pos)
  6755. (run-hook-with-args 'org-cycle-hook 'all)
  6756. (and (window-live-p cwin) (select-window cwin))))
  6757. (defun org-get-indirect-buffer (&optional buffer heading)
  6758. (setq buffer (or buffer (current-buffer)))
  6759. (let ((n 1) (base (buffer-name buffer)) bname)
  6760. (while (buffer-live-p
  6761. (get-buffer
  6762. (setq bname
  6763. (concat base "-"
  6764. (if heading (concat heading "-" (number-to-string n))
  6765. (number-to-string n))))))
  6766. (setq n (1+ n)))
  6767. (condition-case nil
  6768. (make-indirect-buffer buffer bname 'clone)
  6769. (error (make-indirect-buffer buffer bname)))))
  6770. (defun org-set-frame-title (title)
  6771. "Set the title of the current frame to the string TITLE."
  6772. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6773. ;;;; Structure editing
  6774. ;;; Inserting headlines
  6775. (defun org--line-empty-p (n)
  6776. "Is the Nth next line empty?
  6777. Counts the current line as N = 1 and the previous line as N = 0;
  6778. see `beginning-of-line'."
  6779. (save-excursion
  6780. (and (not (bobp))
  6781. (or (beginning-of-line n) t)
  6782. (save-match-data
  6783. (looking-at "[ \t]*$")))))
  6784. (defun org-previous-line-empty-p ()
  6785. "Is the previous line a blank line?
  6786. When NEXT is non-nil, check the next line instead."
  6787. (org--line-empty-p 0))
  6788. (defun org-next-line-empty-p ()
  6789. "Is the previous line a blank line?
  6790. When NEXT is non-nil, check the next line instead."
  6791. (org--line-empty-p 2))
  6792. (defun org--blank-before-heading-p (&optional parent)
  6793. "Non-nil when an empty line should precede a new heading here.
  6794. When optional argument PARENT is non-nil, consider parent
  6795. headline instead of current one."
  6796. (pcase (assq 'heading org-blank-before-new-entry)
  6797. (`(heading . auto)
  6798. (save-excursion
  6799. (org-with-limited-levels
  6800. (unless (and (org-before-first-heading-p)
  6801. (not (outline-next-heading)))
  6802. (org-back-to-heading t)
  6803. (when parent (org-up-heading-safe))
  6804. (cond ((not (bobp))
  6805. (org-previous-line-empty-p))
  6806. ((outline-next-heading)
  6807. (org-previous-line-empty-p))
  6808. ;; Ignore trailing spaces on last buffer line.
  6809. ((progn (skip-chars-backward " \t") (bolp))
  6810. (org-previous-line-empty-p))
  6811. (t nil))))))
  6812. (`(heading . ,value) value)
  6813. (_ nil)))
  6814. (defun org-insert-heading (&optional arg invisible-ok top)
  6815. "Insert a new heading or an item with the same depth at point.
  6816. If point is at the beginning of a heading, insert a new heading
  6817. or a new headline above the current one. When at the beginning
  6818. of a regular line of text, turn it into a heading.
  6819. If point is in the middle of a line, split it and create a new
  6820. headline with the text in the current line after point (see
  6821. `org-M-RET-may-split-line' on how to modify this behavior). As
  6822. a special case, on a headline, splitting can only happen on the
  6823. title itself. E.g., this excludes breaking stars or tags.
  6824. With a `\\[universal-argument]' prefix, set \
  6825. `org-insert-heading-respect-content' to
  6826. a non-nil value for the duration of the command. This forces the
  6827. insertion of a heading after the current subtree, independently
  6828. on the location of point.
  6829. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6830. insert the heading at the end of the tree
  6831. above the current heading. For example, if point is within a
  6832. 2nd-level heading, then it will insert a 2nd-level heading at
  6833. the end of the 1st-level parent subtree.
  6834. When INVISIBLE-OK is set, stop at invisible headlines when going
  6835. back. This is important for non-interactive uses of the
  6836. command.
  6837. When optional argument TOP is non-nil, insert a level 1 heading,
  6838. unconditionally."
  6839. (interactive "P")
  6840. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6841. (level (org-current-level))
  6842. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6843. (cond
  6844. ((or org-insert-heading-respect-content
  6845. (member arg '((4) (16)))
  6846. (and (not invisible-ok)
  6847. (invisible-p (max (1- (point)) (point-min)))))
  6848. ;; Position point at the location of insertion.
  6849. (if (not level) ;before first headline
  6850. (org-with-limited-levels (outline-next-heading))
  6851. ;; Make sure we end up on a visible headline if INVISIBLE-OK
  6852. ;; is nil.
  6853. (org-with-limited-levels (org-back-to-heading invisible-ok))
  6854. (cond ((equal arg '(16))
  6855. (org-up-heading-safe)
  6856. (org-end-of-subtree t t))
  6857. (t
  6858. (org-end-of-subtree t t))))
  6859. (unless (bolp) (insert "\n")) ;ensure final newline
  6860. (unless (and blank? (org-previous-line-empty-p))
  6861. (org-N-empty-lines-before-current (if blank? 1 0)))
  6862. (insert stars " \n")
  6863. (forward-char -1))
  6864. ;; At a headline...
  6865. ((org-at-heading-p)
  6866. (cond ((bolp)
  6867. (when blank? (save-excursion (insert "\n")))
  6868. (save-excursion (insert stars " \n"))
  6869. (unless (and blank? (org-previous-line-empty-p))
  6870. (org-N-empty-lines-before-current (if blank? 1 0)))
  6871. (end-of-line))
  6872. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6873. (org-match-line org-complex-heading-regexp)
  6874. (org-pos-in-match-range (point) 4))
  6875. ;; Grab the text that should moved to the new headline.
  6876. ;; Preserve tags.
  6877. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6878. (if (looking-at "[ \t]*$") (replace-match "")
  6879. (org-set-tags nil t))
  6880. (end-of-line)
  6881. (when blank? (insert "\n"))
  6882. (insert "\n" stars " ")
  6883. (when (org-string-nw-p split) (insert split))
  6884. (when (eobp) (save-excursion (insert "\n")))))
  6885. (t
  6886. (end-of-line)
  6887. (when blank? (insert "\n"))
  6888. (insert "\n" stars " ")
  6889. (when (eobp) (save-excursion (insert "\n"))))))
  6890. ;; On regular text, turn line into a headline or split, if
  6891. ;; appropriate.
  6892. ((bolp)
  6893. (insert stars " ")
  6894. (unless (and blank? (org-previous-line-empty-p))
  6895. (org-N-empty-lines-before-current (if blank? 1 0))))
  6896. (t
  6897. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6898. (end-of-line))
  6899. (insert "\n" stars " ")
  6900. (unless (and blank? (org-previous-line-empty-p))
  6901. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6902. (run-hooks 'org-insert-heading-hook))
  6903. (defun org-N-empty-lines-before-current (n)
  6904. "Make the number of empty lines before current exactly N.
  6905. So this will delete or add empty lines."
  6906. (let ((column (current-column)))
  6907. (beginning-of-line)
  6908. (unless (bobp)
  6909. (let ((start (save-excursion
  6910. (skip-chars-backward " \r\t\n")
  6911. (line-end-position))))
  6912. (delete-region start (line-end-position 0))))
  6913. (insert (make-string n ?\n))
  6914. (move-to-column column)))
  6915. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6916. "Return the heading of the current entry, without the stars.
  6917. When NO-TAGS is non-nil, don't include tags.
  6918. When NO-TODO is non-nil, don't include TODO keywords.
  6919. When NO-PRIORITY is non-nil, don't include priority cookie.
  6920. When NO-COMMENT is non-nil, don't include COMMENT string."
  6921. (save-excursion
  6922. (org-back-to-heading t)
  6923. (let ((case-fold-search nil))
  6924. (looking-at org-complex-heading-regexp)
  6925. (let ((todo (and (not no-todo) (match-string 2)))
  6926. (priority (and (not no-priority) (match-string 3)))
  6927. (headline (pcase (match-string 4)
  6928. (`nil "")
  6929. ((and (guard no-comment) h)
  6930. (replace-regexp-in-string
  6931. (eval-when-compile
  6932. (format "\\`%s[ \t]+" org-comment-string))
  6933. "" h))
  6934. (h h)))
  6935. (tags (and (not no-tags) (match-string 5))))
  6936. (mapconcat #'identity
  6937. (delq nil (list todo priority headline tags))
  6938. " ")))))
  6939. (defvar orgstruct-mode) ; defined below
  6940. (defun org-heading-components ()
  6941. "Return the components of the current heading.
  6942. This is a list with the following elements:
  6943. - the level as an integer
  6944. - the reduced level, different if `org-odd-levels-only' is set.
  6945. - the TODO keyword, or nil
  6946. - the priority character, like ?A, or nil if no priority is given
  6947. - the headline text itself, or the tags string if no headline text
  6948. - the tags string, or nil."
  6949. (save-excursion
  6950. (org-back-to-heading t)
  6951. (when (let (case-fold-search)
  6952. (looking-at
  6953. (if orgstruct-mode
  6954. org-heading-regexp
  6955. org-complex-heading-regexp)))
  6956. (if orgstruct-mode
  6957. (list (length (match-string 1))
  6958. (org-reduced-level (length (match-string 1)))
  6959. nil
  6960. nil
  6961. (match-string 2)
  6962. nil)
  6963. (list (length (match-string 1))
  6964. (org-reduced-level (length (match-string 1)))
  6965. (match-string-no-properties 2)
  6966. (and (match-end 3) (aref (match-string 3) 2))
  6967. (match-string-no-properties 4)
  6968. (match-string-no-properties 5))))))
  6969. (defun org-get-entry ()
  6970. "Get the entry text, after heading, entire subtree."
  6971. (save-excursion
  6972. (org-back-to-heading t)
  6973. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6974. (defun org-edit-headline (&optional heading)
  6975. "Edit the current headline.
  6976. Set it to HEADING when provided."
  6977. (interactive)
  6978. (org-with-wide-buffer
  6979. (org-back-to-heading t)
  6980. (let ((case-fold-search nil))
  6981. (when (looking-at org-complex-heading-regexp)
  6982. (let* ((old (match-string-no-properties 4))
  6983. (new (save-match-data
  6984. (org-trim (or heading (read-string "Edit: " old))))))
  6985. (unless (equal old new)
  6986. (if old (replace-match new t t nil 4)
  6987. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6988. (insert " " new))
  6989. (org-set-tags nil t)
  6990. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6991. (defun org-insert-heading-after-current ()
  6992. "Insert a new heading with same level as current, after current subtree."
  6993. (interactive)
  6994. (org-back-to-heading)
  6995. (org-insert-heading)
  6996. (org-move-subtree-down)
  6997. (end-of-line 1))
  6998. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6999. "Insert heading with `org-insert-heading-respect-content' set to t."
  7000. (interactive)
  7001. (org-insert-heading '(4) invisible-ok))
  7002. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7003. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7004. (interactive)
  7005. (org-insert-todo-heading force-state '(4)))
  7006. (defun org-insert-todo-heading (arg &optional force-heading)
  7007. "Insert a new heading with the same level and TODO state as current heading.
  7008. If the heading has no TODO state, or if the state is DONE, use
  7009. the first state (TODO by default). Also with one prefix arg,
  7010. force first state. With two prefix args, force inserting at the
  7011. end of the parent subtree.
  7012. When called at a plain list item, insert a new item with an
  7013. unchecked check box."
  7014. (interactive "P")
  7015. (when (or force-heading (not (org-insert-item 'checkbox)))
  7016. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7017. force-heading))
  7018. (save-excursion
  7019. (org-back-to-heading)
  7020. (outline-previous-heading)
  7021. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7022. (let* ((new-mark-x
  7023. (if (or (equal arg '(4))
  7024. (not (match-beginning 2))
  7025. (member (match-string 2) org-done-keywords))
  7026. (car org-todo-keywords-1)
  7027. (match-string 2)))
  7028. (new-mark
  7029. (or
  7030. (run-hook-with-args-until-success
  7031. 'org-todo-get-default-hook new-mark-x nil)
  7032. new-mark-x)))
  7033. (beginning-of-line 1)
  7034. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7035. (if org-treat-insert-todo-heading-as-state-change
  7036. (org-todo new-mark)
  7037. (insert new-mark " "))))
  7038. (when org-provide-todo-statistics
  7039. (org-update-parent-todo-statistics))))
  7040. (defun org-insert-subheading (arg)
  7041. "Insert a new subheading and demote it.
  7042. Works for outline headings and for plain lists alike."
  7043. (interactive "P")
  7044. (org-insert-heading arg)
  7045. (cond
  7046. ((org-at-heading-p) (org-do-demote))
  7047. ((org-at-item-p) (org-indent-item))))
  7048. (defun org-insert-todo-subheading (arg)
  7049. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7050. Works for outline headings and for plain lists alike."
  7051. (interactive "P")
  7052. (org-insert-todo-heading arg)
  7053. (cond
  7054. ((org-at-heading-p) (org-do-demote))
  7055. ((org-at-item-p) (org-indent-item))))
  7056. ;;; Promotion and Demotion
  7057. (defvar org-after-demote-entry-hook nil
  7058. "Hook run after an entry has been demoted.
  7059. The cursor will be at the beginning of the entry.
  7060. When a subtree is being demoted, the hook will be called for each node.")
  7061. (defvar org-after-promote-entry-hook nil
  7062. "Hook run after an entry has been promoted.
  7063. The cursor will be at the beginning of the entry.
  7064. When a subtree is being promoted, the hook will be called for each node.")
  7065. (defun org-promote-subtree ()
  7066. "Promote the entire subtree.
  7067. See also `org-promote'."
  7068. (interactive)
  7069. (save-excursion
  7070. (org-with-limited-levels (org-map-tree 'org-promote)))
  7071. (org-fix-position-after-promote))
  7072. (defun org-demote-subtree ()
  7073. "Demote the entire subtree.
  7074. See `org-demote' and `org-promote'."
  7075. (interactive)
  7076. (save-excursion
  7077. (org-with-limited-levels (org-map-tree 'org-demote)))
  7078. (org-fix-position-after-promote))
  7079. (defun org-do-promote ()
  7080. "Promote the current heading higher up the tree.
  7081. If the region is active in `transient-mark-mode', promote all
  7082. headings in the region."
  7083. (interactive)
  7084. (save-excursion
  7085. (if (org-region-active-p)
  7086. (org-map-region 'org-promote (region-beginning) (region-end))
  7087. (org-promote)))
  7088. (org-fix-position-after-promote))
  7089. (defun org-do-demote ()
  7090. "Demote the current heading lower down the tree.
  7091. If the region is active in `transient-mark-mode', demote all
  7092. headings in the region."
  7093. (interactive)
  7094. (save-excursion
  7095. (if (org-region-active-p)
  7096. (org-map-region 'org-demote (region-beginning) (region-end))
  7097. (org-demote)))
  7098. (org-fix-position-after-promote))
  7099. (defun org-fix-position-after-promote ()
  7100. "Fix cursor position and indentation after demoting/promoting."
  7101. (let ((pos (point)))
  7102. (when (save-excursion
  7103. (beginning-of-line)
  7104. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7105. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7106. (cond ((eobp) (insert " "))
  7107. ((eolp) (insert " "))
  7108. ((equal (char-after) ?\s) (forward-char 1))))))
  7109. (defun org-current-level ()
  7110. "Return the level of the current entry, or nil if before the first headline.
  7111. The level is the number of stars at the beginning of the
  7112. headline. Use `org-reduced-level' to remove the effect of
  7113. `org-odd-levels'. Unlike to `org-outline-level', this function
  7114. ignores inlinetasks."
  7115. (let ((level (org-with-limited-levels (org-outline-level))))
  7116. (and (> level 0) level)))
  7117. (defun org-get-previous-line-level ()
  7118. "Return the outline depth of the last headline before the current line.
  7119. Returns 0 for the first headline in the buffer, and nil if before the
  7120. first headline."
  7121. (and (org-current-level)
  7122. (or (and (/= (line-beginning-position) (point-min))
  7123. (save-excursion (beginning-of-line 0) (org-current-level)))
  7124. 0)))
  7125. (defun org-reduced-level (l)
  7126. "Compute the effective level of a heading.
  7127. This takes into account the setting of `org-odd-levels-only'."
  7128. (cond
  7129. ((zerop l) 0)
  7130. (org-odd-levels-only (1+ (floor (/ l 2))))
  7131. (t l)))
  7132. (defun org-level-increment ()
  7133. "Return the number of stars that will be added or removed at a
  7134. time to headlines when structure editing, based on the value of
  7135. `org-odd-levels-only'."
  7136. (if org-odd-levels-only 2 1))
  7137. (defun org-get-valid-level (level &optional change)
  7138. "Rectify a level change under the influence of `org-odd-levels-only'.
  7139. LEVEL is a current level, CHANGE is by how much the level should
  7140. be modified. Even if CHANGE is nil, LEVEL may be returned
  7141. modified because even level numbers will become the next higher
  7142. odd number. Returns values greater than 0."
  7143. (if org-odd-levels-only
  7144. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7145. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  7146. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7147. (max 1 (+ level (or change 0)))))
  7148. (defun org-promote ()
  7149. "Promote the current heading higher up the tree."
  7150. (org-with-wide-buffer
  7151. (org-back-to-heading t)
  7152. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7153. after-change-functions))
  7154. (level (save-match-data (funcall outline-level)))
  7155. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7156. (diff (abs (- level (length up-head) -1))))
  7157. (cond
  7158. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7159. (replace-match "# " nil t))
  7160. ((= level 1)
  7161. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7162. (t (replace-match up-head nil t)))
  7163. (unless (= level 1)
  7164. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7165. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7166. (run-hooks 'org-after-promote-entry-hook))))
  7167. (defun org-demote ()
  7168. "Demote the current heading lower down the tree."
  7169. (org-with-wide-buffer
  7170. (org-back-to-heading t)
  7171. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7172. after-change-functions))
  7173. (level (save-match-data (funcall outline-level)))
  7174. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7175. (diff (abs (- level (length down-head) -1))))
  7176. (replace-match down-head nil t)
  7177. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7178. (when org-adapt-indentation (org-fixup-indentation diff))
  7179. (run-hooks 'org-after-demote-entry-hook))))
  7180. (defun org-cycle-level ()
  7181. "Cycle the level of an empty headline through possible states.
  7182. This goes first to child, then to parent, level, then up the hierarchy.
  7183. After top level, it switches back to sibling level."
  7184. (interactive)
  7185. (let ((org-adapt-indentation nil))
  7186. (when (org-point-at-end-of-empty-headline)
  7187. (setq this-command 'org-cycle-level) ; Only needed for caching
  7188. (let ((cur-level (org-current-level))
  7189. (prev-level (org-get-previous-line-level)))
  7190. (cond
  7191. ;; If first headline in file, promote to top-level.
  7192. ((= prev-level 0)
  7193. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7194. do (org-do-promote)))
  7195. ;; If same level as prev, demote one.
  7196. ((= prev-level cur-level)
  7197. (org-do-demote))
  7198. ;; If parent is top-level, promote to top level if not already.
  7199. ((= prev-level 1)
  7200. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7201. do (org-do-promote)))
  7202. ;; If top-level, return to prev-level.
  7203. ((= cur-level 1)
  7204. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7205. do (org-do-demote)))
  7206. ;; If less than prev-level, promote one.
  7207. ((< cur-level prev-level)
  7208. (org-do-promote))
  7209. ;; If deeper than prev-level, promote until higher than
  7210. ;; prev-level.
  7211. ((> cur-level prev-level)
  7212. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7213. do (org-do-promote))))
  7214. t))))
  7215. (defun org-map-tree (fun)
  7216. "Call FUN for every heading underneath the current one."
  7217. (org-back-to-heading t)
  7218. (let ((level (funcall outline-level)))
  7219. (save-excursion
  7220. (funcall fun)
  7221. (while (and (progn
  7222. (outline-next-heading)
  7223. (> (funcall outline-level) level))
  7224. (not (eobp)))
  7225. (funcall fun)))))
  7226. (defun org-map-region (fun beg end)
  7227. "Call FUN for every heading between BEG and END."
  7228. (let ((org-ignore-region t))
  7229. (save-excursion
  7230. (setq end (copy-marker end))
  7231. (goto-char beg)
  7232. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7233. (< (point) end))
  7234. (funcall fun))
  7235. (while (and (progn
  7236. (outline-next-heading)
  7237. (< (point) end))
  7238. (not (eobp)))
  7239. (funcall fun)))))
  7240. (defun org-fixup-indentation (diff)
  7241. "Change the indentation in the current entry by DIFF.
  7242. DIFF is an integer. Indentation is done according to the
  7243. following rules:
  7244. - Planning information and property drawers are always indented
  7245. according to the new level of the headline;
  7246. - Footnote definitions and their contents are ignored;
  7247. - Inlinetasks' boundaries are not shifted;
  7248. - Empty lines are ignored;
  7249. - Other lines' indentation are shifted by DIFF columns, unless
  7250. it would introduce a structural change in the document, in
  7251. which case no shifting is done at all.
  7252. Assume point is at a heading or an inlinetask beginning."
  7253. (org-with-wide-buffer
  7254. (narrow-to-region (line-beginning-position)
  7255. (save-excursion
  7256. (if (org-with-limited-levels (org-at-heading-p))
  7257. (org-with-limited-levels (outline-next-heading))
  7258. (org-inlinetask-goto-end))
  7259. (point)))
  7260. (forward-line)
  7261. ;; Indent properly planning info and property drawer.
  7262. (when (looking-at-p org-planning-line-re)
  7263. (org-indent-line)
  7264. (forward-line))
  7265. (when (looking-at org-property-drawer-re)
  7266. (goto-char (match-end 0))
  7267. (forward-line)
  7268. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7269. (catch 'no-shift
  7270. (when (zerop diff) (throw 'no-shift nil))
  7271. ;; If DIFF is negative, first check if a shift is possible at all
  7272. ;; (e.g., it doesn't break structure). This can only happen if
  7273. ;; some contents are not properly indented.
  7274. (let ((case-fold-search t))
  7275. (when (< diff 0)
  7276. (let ((diff (- diff))
  7277. (forbidden-re (concat org-outline-regexp
  7278. "\\|"
  7279. (substring org-footnote-definition-re 1))))
  7280. (save-excursion
  7281. (while (not (eobp))
  7282. (cond
  7283. ((looking-at-p "[ \t]*$") (forward-line))
  7284. ((and (looking-at-p org-footnote-definition-re)
  7285. (let ((e (org-element-at-point)))
  7286. (and (eq (org-element-type e) 'footnote-definition)
  7287. (goto-char (org-element-property :end e))))))
  7288. ((looking-at-p org-outline-regexp) (forward-line))
  7289. ;; Give up if shifting would move before column 0 or
  7290. ;; if it would introduce a headline or a footnote
  7291. ;; definition.
  7292. (t
  7293. (skip-chars-forward " \t")
  7294. (let ((ind (current-column)))
  7295. (when (or (< ind diff)
  7296. (and (= ind diff) (looking-at-p forbidden-re)))
  7297. (throw 'no-shift nil)))
  7298. ;; Ignore contents of example blocks and source
  7299. ;; blocks if their indentation is meant to be
  7300. ;; preserved. Jump to block's closing line.
  7301. (beginning-of-line)
  7302. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7303. (let ((e (org-element-at-point)))
  7304. (and (memq (org-element-type e)
  7305. '(example-block src-block))
  7306. (or org-src-preserve-indentation
  7307. (org-element-property :preserve-indent e))
  7308. (goto-char (org-element-property :end e))
  7309. (progn (skip-chars-backward " \r\t\n")
  7310. (beginning-of-line)
  7311. t))))
  7312. (forward-line))))))))
  7313. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7314. ;; by DIFF. Also skip contents of source or example blocks
  7315. ;; when indentation is meant to be preserved.
  7316. (while (not (eobp))
  7317. (cond
  7318. ((and (looking-at-p org-footnote-definition-re)
  7319. (let ((e (org-element-at-point)))
  7320. (and (eq (org-element-type e) 'footnote-definition)
  7321. (goto-char (org-element-property :end e))))))
  7322. ((looking-at-p org-outline-regexp) (forward-line))
  7323. ((looking-at-p "[ \t]*$") (forward-line))
  7324. (t
  7325. (indent-line-to (+ (org-get-indentation) diff))
  7326. (beginning-of-line)
  7327. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7328. (let ((e (org-element-at-point)))
  7329. (and (memq (org-element-type e)
  7330. '(example-block src-block))
  7331. (or org-src-preserve-indentation
  7332. (org-element-property :preserve-indent e))
  7333. (goto-char (org-element-property :end e))
  7334. (progn (skip-chars-backward " \r\t\n")
  7335. (beginning-of-line)
  7336. t))))
  7337. (forward-line)))))))))
  7338. (defun org-convert-to-odd-levels ()
  7339. "Convert an Org file with all levels allowed to one with odd levels.
  7340. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7341. level 5 etc."
  7342. (interactive)
  7343. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7344. (let ((outline-level 'org-outline-level)
  7345. (org-odd-levels-only nil) n)
  7346. (save-excursion
  7347. (goto-char (point-min))
  7348. (while (re-search-forward "^\\*\\*+ " nil t)
  7349. (setq n (- (length (match-string 0)) 2))
  7350. (while (>= (setq n (1- n)) 0)
  7351. (org-demote))
  7352. (end-of-line 1))))))
  7353. (defun org-convert-to-oddeven-levels ()
  7354. "Convert an Org file with only odd levels to one with odd/even levels.
  7355. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7356. file contains a section with an even level, conversion would
  7357. destroy the structure of the file. An error is signaled in this
  7358. case."
  7359. (interactive)
  7360. (goto-char (point-min))
  7361. ;; First check if there are no even levels
  7362. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7363. (org-show-set-visibility 'canonical)
  7364. (error "Not all levels are odd in this file. Conversion not possible"))
  7365. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7366. (let ((outline-regexp org-outline-regexp)
  7367. (outline-level 'org-outline-level)
  7368. (org-odd-levels-only nil) n)
  7369. (save-excursion
  7370. (goto-char (point-min))
  7371. (while (re-search-forward "^\\*\\*+ " nil t)
  7372. (setq n (/ (1- (length (match-string 0))) 2))
  7373. (while (>= (setq n (1- n)) 0)
  7374. (org-promote))
  7375. (end-of-line 1))))))
  7376. (defun org-tr-level (n)
  7377. "Make N odd if required."
  7378. (if org-odd-levels-only (1+ (/ n 2)) n))
  7379. ;;; Vertical tree motion, cutting and pasting of subtrees
  7380. (defun org-move-subtree-up (&optional arg)
  7381. "Move the current subtree up past ARG headlines of the same level."
  7382. (interactive "p")
  7383. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7384. (defun org-move-subtree-down (&optional arg)
  7385. "Move the current subtree down past ARG headlines of the same level."
  7386. (interactive "p")
  7387. (setq arg (prefix-numeric-value arg))
  7388. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7389. 'org-get-last-sibling))
  7390. (ins-point (make-marker))
  7391. (cnt (abs arg))
  7392. (col (current-column))
  7393. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7394. ;; Select the tree
  7395. (org-back-to-heading)
  7396. (setq beg0 (point))
  7397. (save-excursion
  7398. (setq ne-beg (org-back-over-empty-lines))
  7399. (setq beg (point)))
  7400. (save-match-data
  7401. (save-excursion (outline-end-of-heading)
  7402. (setq folded (outline-invisible-p)))
  7403. (progn (org-end-of-subtree nil t)
  7404. (unless (eobp) (backward-char))))
  7405. (outline-next-heading)
  7406. (setq ne-end (org-back-over-empty-lines))
  7407. (setq end (point))
  7408. (goto-char beg0)
  7409. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7410. ;; include less whitespace
  7411. (save-excursion
  7412. (goto-char beg)
  7413. (forward-line (- ne-beg ne-end))
  7414. (setq beg (point))))
  7415. ;; Find insertion point, with error handling
  7416. (while (> cnt 0)
  7417. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7418. (progn (goto-char beg0)
  7419. (user-error "Cannot move past superior level or buffer limit")))
  7420. (setq cnt (1- cnt)))
  7421. (when (> arg 0)
  7422. ;; Moving forward - still need to move over subtree
  7423. (org-end-of-subtree t t)
  7424. (save-excursion
  7425. (org-back-over-empty-lines)
  7426. (or (bolp) (newline))))
  7427. (setq ne-ins (org-back-over-empty-lines))
  7428. (move-marker ins-point (point))
  7429. (setq txt (buffer-substring beg end))
  7430. (org-save-markers-in-region beg end)
  7431. (delete-region beg end)
  7432. (org-remove-empty-overlays-at beg)
  7433. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7434. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7435. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7436. (let ((bbb (point)))
  7437. (insert-before-markers txt)
  7438. (org-reinstall-markers-in-region bbb)
  7439. (move-marker ins-point bbb))
  7440. (or (bolp) (insert "\n"))
  7441. (setq ins-end (point))
  7442. (goto-char ins-point)
  7443. (org-skip-whitespace)
  7444. (when (and (< arg 0)
  7445. (org-first-sibling-p)
  7446. (> ne-ins ne-beg))
  7447. ;; Move whitespace back to beginning
  7448. (save-excursion
  7449. (goto-char ins-end)
  7450. (let ((kill-whole-line t))
  7451. (kill-line (- ne-ins ne-beg)) (point)))
  7452. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7453. (move-marker ins-point nil)
  7454. (if folded
  7455. (outline-hide-subtree)
  7456. (org-show-entry)
  7457. (org-show-children)
  7458. (org-cycle-hide-drawers 'children))
  7459. (org-clean-visibility-after-subtree-move)
  7460. ;; move back to the initial column we were at
  7461. (move-to-column col)))
  7462. (defvar org-subtree-clip ""
  7463. "Clipboard for cut and paste of subtrees.
  7464. This is actually only a copy of the kill, because we use the normal kill
  7465. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7466. (defvar org-subtree-clip-folded nil
  7467. "Was the last copied subtree folded?
  7468. This is used to fold the tree back after pasting.")
  7469. (defun org-cut-subtree (&optional n)
  7470. "Cut the current subtree into the clipboard.
  7471. With prefix arg N, cut this many sequential subtrees.
  7472. This is a short-hand for marking the subtree and then cutting it."
  7473. (interactive "p")
  7474. (org-copy-subtree n 'cut))
  7475. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7476. "Copy the current subtree it in the clipboard.
  7477. With prefix arg N, copy this many sequential subtrees.
  7478. This is a short-hand for marking the subtree and then copying it.
  7479. If CUT is non-nil, actually cut the subtree.
  7480. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7481. of some markers in the region, even if CUT is non-nil. This is
  7482. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7483. (interactive "p")
  7484. (let (beg end folded (beg0 (point)))
  7485. (if (called-interactively-p 'any)
  7486. (org-back-to-heading nil) ; take what looks like a subtree
  7487. (org-back-to-heading t)) ; take what is really there
  7488. (setq beg (point))
  7489. (skip-chars-forward " \t\r\n")
  7490. (save-match-data
  7491. (if nosubtrees
  7492. (outline-next-heading)
  7493. (save-excursion (outline-end-of-heading)
  7494. (setq folded (outline-invisible-p)))
  7495. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7496. (org-end-of-subtree t t)))
  7497. ;; Include the end of an inlinetask
  7498. (when (and (featurep 'org-inlinetask)
  7499. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7500. "END[ \t]*$")))
  7501. (end-of-line))
  7502. (setq end (point))
  7503. (goto-char beg0)
  7504. (when (> end beg)
  7505. (setq org-subtree-clip-folded folded)
  7506. (when (or cut force-store-markers)
  7507. (org-save-markers-in-region beg end))
  7508. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7509. (setq org-subtree-clip (current-kill 0))
  7510. (message "%s: Subtree(s) with %d characters"
  7511. (if cut "Cut" "Copied")
  7512. (length org-subtree-clip)))))
  7513. (defun org-paste-subtree (&optional level tree for-yank remove)
  7514. "Paste the clipboard as a subtree, with modification of headline level.
  7515. The entire subtree is promoted or demoted in order to match a new headline
  7516. level.
  7517. If the cursor is at the beginning of a headline, the same level as
  7518. that headline is used to paste the tree.
  7519. If not, the new level is derived from the *visible* headings
  7520. before and after the insertion point, and taken to be the inferior headline
  7521. level of the two. So if the previous visible heading is level 3 and the
  7522. next is level 4 (or vice versa), level 4 will be used for insertion.
  7523. This makes sure that the subtree remains an independent subtree and does
  7524. not swallow low level entries.
  7525. You can also force a different level, either by using a numeric prefix
  7526. argument, or by inserting the heading marker by hand. For example, if the
  7527. cursor is after \"*****\", then the tree will be shifted to level 5.
  7528. If optional TREE is given, use this text instead of the kill ring.
  7529. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7530. move back over whitespace before inserting, and move point to the end of
  7531. the inserted text when done.
  7532. When REMOVE is non-nil, remove the subtree from the clipboard."
  7533. (interactive "P")
  7534. (setq tree (or tree (and kill-ring (current-kill 0))))
  7535. (unless (org-kill-is-subtree-p tree)
  7536. (user-error "%s"
  7537. (substitute-command-keys
  7538. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7539. (org-with-limited-levels
  7540. (let* ((visp (not (outline-invisible-p)))
  7541. (txt tree)
  7542. (^re_ "\\(\\*+\\)[ \t]*")
  7543. (old-level (if (string-match org-outline-regexp-bol txt)
  7544. (- (match-end 0) (match-beginning 0) 1)
  7545. -1))
  7546. (force-level (cond (level (prefix-numeric-value level))
  7547. ((and (looking-at "[ \t]*$")
  7548. (string-match
  7549. "^\\*+$" (buffer-substring
  7550. (point-at-bol) (point))))
  7551. (- (match-end 0) (match-beginning 0)))
  7552. ((and (bolp)
  7553. (looking-at org-outline-regexp))
  7554. (- (match-end 0) (point) 1))))
  7555. (previous-level (save-excursion
  7556. (condition-case nil
  7557. (progn
  7558. (outline-previous-visible-heading 1)
  7559. (if (looking-at ^re_)
  7560. (- (match-end 0) (match-beginning 0) 1)
  7561. 1))
  7562. (error 1))))
  7563. (next-level (save-excursion
  7564. (condition-case nil
  7565. (progn
  7566. (or (looking-at org-outline-regexp)
  7567. (outline-next-visible-heading 1))
  7568. (if (looking-at ^re_)
  7569. (- (match-end 0) (match-beginning 0) 1)
  7570. 1))
  7571. (error 1))))
  7572. (new-level (or force-level (max previous-level next-level)))
  7573. (shift (if (or (= old-level -1)
  7574. (= new-level -1)
  7575. (= old-level new-level))
  7576. 0
  7577. (- new-level old-level)))
  7578. (delta (if (> shift 0) -1 1))
  7579. (func (if (> shift 0) 'org-demote 'org-promote))
  7580. (org-odd-levels-only nil)
  7581. beg end newend)
  7582. ;; Remove the forced level indicator
  7583. (when force-level
  7584. (delete-region (point-at-bol) (point)))
  7585. ;; Paste
  7586. (beginning-of-line (if (bolp) 1 2))
  7587. (setq beg (point))
  7588. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7589. (insert-before-markers txt)
  7590. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7591. (setq newend (point))
  7592. (org-reinstall-markers-in-region beg)
  7593. (setq end (point))
  7594. (goto-char beg)
  7595. (skip-chars-forward " \t\n\r")
  7596. (setq beg (point))
  7597. (when (and (outline-invisible-p) visp)
  7598. (save-excursion (outline-show-heading)))
  7599. ;; Shift if necessary
  7600. (unless (= shift 0)
  7601. (save-restriction
  7602. (narrow-to-region beg end)
  7603. (while (not (= shift 0))
  7604. (org-map-region func (point-min) (point-max))
  7605. (setq shift (+ delta shift)))
  7606. (goto-char (point-min))
  7607. (setq newend (point-max))))
  7608. (when (or (called-interactively-p 'interactive) for-yank)
  7609. (message "Clipboard pasted as level %d subtree" new-level))
  7610. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7611. kill-ring
  7612. (eq org-subtree-clip (current-kill 0))
  7613. org-subtree-clip-folded)
  7614. ;; The tree was folded before it was killed/copied
  7615. (outline-hide-subtree))
  7616. (and for-yank (goto-char newend))
  7617. (and remove (setq kill-ring (cdr kill-ring))))))
  7618. (defun org-kill-is-subtree-p (&optional txt)
  7619. "Check if the current kill is an outline subtree, or a set of trees.
  7620. Returns nil if kill does not start with a headline, or if the first
  7621. headline level is not the largest headline level in the tree.
  7622. So this will actually accept several entries of equal levels as well,
  7623. which is OK for `org-paste-subtree'.
  7624. If optional TXT is given, check this string instead of the current kill."
  7625. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7626. (re (org-get-limited-outline-regexp))
  7627. (^re (concat "^" re))
  7628. (start-level (and kill
  7629. (string-match
  7630. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7631. kill)
  7632. (- (match-end 2) (match-beginning 2) 1)))
  7633. (start (1+ (or (match-beginning 2) -1))))
  7634. (if (not start-level)
  7635. (progn
  7636. nil) ;; does not even start with a heading
  7637. (catch 'exit
  7638. (while (setq start (string-match ^re kill (1+ start)))
  7639. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7640. (throw 'exit nil)))
  7641. t))))
  7642. (defvar org-markers-to-move nil
  7643. "Markers that should be moved with a cut-and-paste operation.
  7644. Those markers are stored together with their positions relative to
  7645. the start of the region.")
  7646. (defun org-save-markers-in-region (beg end)
  7647. "Check markers in region.
  7648. If these markers are between BEG and END, record their position relative
  7649. to BEG, so that after moving the block of text, we can put the markers back
  7650. into place.
  7651. This function gets called just before an entry or tree gets cut from the
  7652. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7653. called immediately, to move the markers with the entries."
  7654. (setq org-markers-to-move nil)
  7655. (when (featurep 'org-clock)
  7656. (org-clock-save-markers-for-cut-and-paste beg end))
  7657. (when (featurep 'org-agenda)
  7658. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7659. (defun org-check-and-save-marker (marker beg end)
  7660. "Check if MARKER is between BEG and END.
  7661. If yes, remember the marker and the distance to BEG."
  7662. (when (and (marker-buffer marker)
  7663. (equal (marker-buffer marker) (current-buffer))
  7664. (>= marker beg) (< marker end))
  7665. (push (cons marker (- marker beg)) org-markers-to-move)))
  7666. (defun org-reinstall-markers-in-region (beg)
  7667. "Move all remembered markers to their position relative to BEG."
  7668. (dolist (x org-markers-to-move)
  7669. (move-marker (car x) (+ beg (cdr x))))
  7670. (setq org-markers-to-move nil))
  7671. (defun org-narrow-to-subtree ()
  7672. "Narrow buffer to the current subtree."
  7673. (interactive)
  7674. (save-excursion
  7675. (save-match-data
  7676. (org-with-limited-levels
  7677. (narrow-to-region
  7678. (progn (org-back-to-heading t) (point))
  7679. (progn (org-end-of-subtree t t)
  7680. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7681. (point)))))))
  7682. (defun org-narrow-to-block ()
  7683. "Narrow buffer to the current block."
  7684. (interactive)
  7685. (let* ((case-fold-search t)
  7686. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7687. "^[ \t]*#\\+end_.*")))
  7688. (if blockp
  7689. (narrow-to-region (car blockp) (cdr blockp))
  7690. (user-error "Not in a block"))))
  7691. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7692. "Clone the task (subtree) at point N times.
  7693. The clones will be inserted as siblings.
  7694. In interactive use, the user will be prompted for the number of
  7695. clones to be produced. If the entry has a timestamp, the user
  7696. will also be prompted for a time shift, which may be a repeater
  7697. as used in time stamps, for example `+3d'. To disable this,
  7698. you can call the function with a universal prefix argument.
  7699. When a valid repeater is given and the entry contains any time
  7700. stamps, the clones will become a sequence in time, with time
  7701. stamps in the subtree shifted for each clone produced. If SHIFT
  7702. is nil or the empty string, time stamps will be left alone. The
  7703. ID property of the original subtree is removed.
  7704. In each clone, all the CLOCK entries will be removed. This
  7705. prevents Org from considering that the clocked times overlap.
  7706. If the original subtree did contain time stamps with a repeater,
  7707. the following will happen:
  7708. - the repeater will be removed in each clone
  7709. - an additional clone will be produced, with the current, unshifted
  7710. date(s) in the entry.
  7711. - the original entry will be placed *after* all the clones, with
  7712. repeater intact.
  7713. - the start days in the repeater in the original entry will be shifted
  7714. to past the last clone.
  7715. In this way you can spell out a number of instances of a repeating task,
  7716. and still retain the repeater to cover future instances of the task.
  7717. As described above, N+1 clones are produced when the original
  7718. subtree has a repeater. Setting N to 0, then, can be used to
  7719. remove the repeater from a subtree and create a shifted clone
  7720. with the original repeater."
  7721. (interactive "nNumber of clones to produce: ")
  7722. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7723. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7724. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7725. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7726. (shift
  7727. (or shift
  7728. (if (and (not (equal current-prefix-arg '(4)))
  7729. (save-excursion
  7730. (goto-char beg)
  7731. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7732. (read-from-minibuffer
  7733. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7734. ""))) ;No time shift
  7735. (doshift
  7736. (and (org-string-nw-p shift)
  7737. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7738. shift)
  7739. (user-error "Invalid shift specification %s" shift)))))
  7740. (goto-char end-of-tree)
  7741. (unless (bolp) (insert "\n"))
  7742. (let* ((end (point))
  7743. (template (buffer-substring beg end))
  7744. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7745. (shift-what (pcase (and doshift (match-string 2 shift))
  7746. (`nil nil)
  7747. ("d" 'day)
  7748. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7749. ("m" 'month)
  7750. ("y" 'year)
  7751. (_ (error "Unsupported time unit"))))
  7752. (nmin 1)
  7753. (nmax n)
  7754. (n-no-remove -1)
  7755. (idprop (org-entry-get nil "ID")))
  7756. (when (and doshift
  7757. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7758. template))
  7759. (delete-region beg end)
  7760. (setq end beg)
  7761. (setq nmin 0)
  7762. (setq nmax (1+ nmax))
  7763. (setq n-no-remove nmax))
  7764. (goto-char end)
  7765. (cl-loop for n from nmin to nmax do
  7766. (insert
  7767. ;; Prepare clone.
  7768. (with-temp-buffer
  7769. (insert template)
  7770. (org-mode)
  7771. (goto-char (point-min))
  7772. (org-show-subtree)
  7773. (and idprop (if org-clone-delete-id
  7774. (org-entry-delete nil "ID")
  7775. (org-id-get-create t)))
  7776. (unless (= n 0)
  7777. (while (re-search-forward org-clock-line-re nil t)
  7778. (delete-region (line-beginning-position)
  7779. (line-beginning-position 2)))
  7780. (goto-char (point-min))
  7781. (while (re-search-forward org-drawer-regexp nil t)
  7782. (org-remove-empty-drawer-at (point))))
  7783. (goto-char (point-min))
  7784. (when doshift
  7785. (while (re-search-forward org-ts-regexp-both nil t)
  7786. (org-timestamp-change (* n shift-n) shift-what))
  7787. (unless (= n n-no-remove)
  7788. (goto-char (point-min))
  7789. (while (re-search-forward org-ts-regexp nil t)
  7790. (save-excursion
  7791. (goto-char (match-beginning 0))
  7792. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7793. (delete-region (match-beginning 1) (match-end 1)))))))
  7794. (buffer-string)))))
  7795. (goto-char beg)))
  7796. ;;; Outline Sorting
  7797. (defun org-sort (&optional with-case)
  7798. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7799. Optional argument WITH-CASE means sort case-sensitively."
  7800. (interactive "P")
  7801. (org-call-with-arg
  7802. (cond ((org-at-table-p) #'org-table-sort-lines)
  7803. ((org-at-item-p) #'org-sort-list)
  7804. (t #'org-sort-entries))
  7805. with-case))
  7806. (defun org-sort-remove-invisible (s)
  7807. "Remove invisible part of links and emphasis markers from string S."
  7808. (remove-text-properties 0 (length s) org-rm-props s)
  7809. (replace-regexp-in-string
  7810. org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
  7811. (replace-regexp-in-string
  7812. org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
  7813. (org-link-display-format s)
  7814. t t) t t))
  7815. (defvar org-priority-regexp) ; defined later in the file
  7816. (defvar org-after-sorting-entries-or-items-hook nil
  7817. "Hook that is run after a bunch of entries or items have been sorted.
  7818. When children are sorted, the cursor is in the parent line when this
  7819. hook gets called. When a region or a plain list is sorted, the cursor
  7820. will be in the first entry of the sorted region/list.")
  7821. (defun org-sort-entries
  7822. (&optional with-case sorting-type getkey-func compare-func property
  7823. interactive?)
  7824. "Sort entries on a certain level of an outline tree.
  7825. If there is an active region, the entries in the region are sorted.
  7826. Else, if the cursor is before the first entry, sort the top-level items.
  7827. Else, the children of the entry at point are sorted.
  7828. Sorting can be alphabetically, numerically, by date/time as given by
  7829. a time stamp, by a property, by priority order, or by a custom function.
  7830. The command prompts for the sorting type unless it has been given to the
  7831. function through the SORTING-TYPE argument, which needs to be a character,
  7832. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7833. the precise meaning of each character:
  7834. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7835. c By creation time, which is assumed to be the first inactive time stamp
  7836. at the beginning of a line.
  7837. d By deadline date/time.
  7838. k By clocking time.
  7839. n Numerically, by converting the beginning of the entry/item to a number.
  7840. o By order of TODO keywords.
  7841. p By priority according to the cookie.
  7842. r By the value of a property.
  7843. s By scheduled date/time.
  7844. t By date/time, either the first active time stamp in the entry, or, if
  7845. none exist, by the first inactive one.
  7846. Capital letters will reverse the sort order.
  7847. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7848. called with point at the beginning of the record. It must return a
  7849. value that is compatible with COMPARE-FUNC, the function used to
  7850. compare entries.
  7851. Comparing entries ignores case by default. However, with an optional argument
  7852. WITH-CASE, the sorting considers case as well.
  7853. Sorting is done against the visible part of the headlines, it ignores hidden
  7854. links.
  7855. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7856. A non-nil value for INTERACTIVE? is used to signal that this
  7857. function is being called interactively."
  7858. (interactive (list current-prefix-arg nil nil nil nil t))
  7859. (let ((case-func (if with-case 'identity 'downcase))
  7860. (cmstr
  7861. ;; The clock marker is lost when using `sort-subr', let's
  7862. ;; store the clocking string.
  7863. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  7864. (save-excursion
  7865. (goto-char org-clock-marker)
  7866. (buffer-substring-no-properties (line-beginning-position)
  7867. (point)))))
  7868. start beg end stars re re2
  7869. txt what tmp)
  7870. ;; Find beginning and end of region to sort
  7871. (cond
  7872. ((org-region-active-p)
  7873. ;; we will sort the region
  7874. (setq end (region-end)
  7875. what "region")
  7876. (goto-char (region-beginning))
  7877. (unless (org-at-heading-p) (outline-next-heading))
  7878. (setq start (point)))
  7879. ((or (org-at-heading-p)
  7880. (ignore-errors (progn (org-back-to-heading) t)))
  7881. ;; we will sort the children of the current headline
  7882. (org-back-to-heading)
  7883. (setq start (point)
  7884. end (progn (org-end-of-subtree t t)
  7885. (or (bolp) (insert "\n"))
  7886. (when (>= (org-back-over-empty-lines) 1)
  7887. (forward-line 1))
  7888. (point))
  7889. what "children")
  7890. (goto-char start)
  7891. (outline-show-subtree)
  7892. (outline-next-heading))
  7893. (t
  7894. ;; we will sort the top-level entries in this file
  7895. (goto-char (point-min))
  7896. (or (org-at-heading-p) (outline-next-heading))
  7897. (setq start (point))
  7898. (goto-char (point-max))
  7899. (beginning-of-line 1)
  7900. (when (looking-at ".*?\\S-")
  7901. ;; File ends in a non-white line
  7902. (end-of-line 1)
  7903. (insert "\n"))
  7904. (setq end (point-max))
  7905. (setq what "top-level")
  7906. (goto-char start)
  7907. (outline-show-all)))
  7908. (setq beg (point))
  7909. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7910. (looking-at "\\(\\*+\\)")
  7911. (setq stars (match-string 1)
  7912. re (concat "^" (regexp-quote stars) " +")
  7913. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7914. txt (buffer-substring beg end))
  7915. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7916. (when (and (not (equal stars "*")) (string-match re2 txt))
  7917. (user-error "Region to sort contains a level above the first entry"))
  7918. (unless sorting-type
  7919. (message
  7920. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7921. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7922. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7923. what)
  7924. (setq sorting-type (read-char-exclusive)))
  7925. (unless getkey-func
  7926. (and (= (downcase sorting-type) ?f)
  7927. (setq getkey-func
  7928. (or (and interactive?
  7929. (org-read-function
  7930. "Function for extracting keys: "))
  7931. (error "Missing key extractor")))))
  7932. (and (= (downcase sorting-type) ?r)
  7933. (not property)
  7934. (setq property
  7935. (completing-read "Property: "
  7936. (mapcar #'list (org-buffer-property-keys t))
  7937. nil t)))
  7938. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7939. (message "Sorting entries...")
  7940. (save-restriction
  7941. (narrow-to-region start end)
  7942. (let ((dcst (downcase sorting-type))
  7943. (case-fold-search nil)
  7944. (now (current-time)))
  7945. (sort-subr
  7946. (/= dcst sorting-type)
  7947. ;; This function moves to the beginning character of the "record" to
  7948. ;; be sorted.
  7949. (lambda nil
  7950. (if (re-search-forward re nil t)
  7951. (goto-char (match-beginning 0))
  7952. (goto-char (point-max))))
  7953. ;; This function moves to the last character of the "record" being
  7954. ;; sorted.
  7955. (lambda nil
  7956. (save-match-data
  7957. (condition-case nil
  7958. (outline-forward-same-level 1)
  7959. (error
  7960. (goto-char (point-max))))))
  7961. ;; This function returns the value that gets sorted against.
  7962. (lambda nil
  7963. (cond
  7964. ((= dcst ?n)
  7965. (if (looking-at org-complex-heading-regexp)
  7966. (string-to-number (org-sort-remove-invisible (match-string 4)))
  7967. nil))
  7968. ((= dcst ?a)
  7969. (if (looking-at org-complex-heading-regexp)
  7970. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  7971. nil))
  7972. ((= dcst ?k)
  7973. (or (get-text-property (point) :org-clock-minutes) 0))
  7974. ((= dcst ?t)
  7975. (let ((end (save-excursion (outline-next-heading) (point))))
  7976. (if (or (re-search-forward org-ts-regexp end t)
  7977. (re-search-forward org-ts-regexp-both end t))
  7978. (org-time-string-to-seconds (match-string 0))
  7979. (float-time now))))
  7980. ((= dcst ?c)
  7981. (let ((end (save-excursion (outline-next-heading) (point))))
  7982. (if (re-search-forward
  7983. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7984. end t)
  7985. (org-time-string-to-seconds (match-string 0))
  7986. (float-time now))))
  7987. ((= dcst ?s)
  7988. (let ((end (save-excursion (outline-next-heading) (point))))
  7989. (if (re-search-forward org-scheduled-time-regexp end t)
  7990. (org-time-string-to-seconds (match-string 1))
  7991. (float-time now))))
  7992. ((= dcst ?d)
  7993. (let ((end (save-excursion (outline-next-heading) (point))))
  7994. (if (re-search-forward org-deadline-time-regexp end t)
  7995. (org-time-string-to-seconds (match-string 1))
  7996. (float-time now))))
  7997. ((= dcst ?p)
  7998. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7999. (string-to-char (match-string 2))
  8000. org-default-priority))
  8001. ((= dcst ?r)
  8002. (or (org-entry-get nil property) ""))
  8003. ((= dcst ?o)
  8004. (when (looking-at org-complex-heading-regexp)
  8005. (let* ((m (match-string 2))
  8006. (s (if (member m org-done-keywords) '- '+)))
  8007. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8008. ((= dcst ?f)
  8009. (if getkey-func
  8010. (progn
  8011. (setq tmp (funcall getkey-func))
  8012. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8013. tmp)
  8014. (error "Invalid key function `%s'" getkey-func)))
  8015. (t (error "Invalid sorting type `%c'" sorting-type))))
  8016. nil
  8017. (cond
  8018. ((= dcst ?a) 'string<)
  8019. ((= dcst ?f)
  8020. (or compare-func
  8021. (and interactive?
  8022. (org-read-function
  8023. (concat "Function for comparing keys "
  8024. "(empty for default `sort-subr' predicate): ")
  8025. 'allow-empty))))
  8026. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8027. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8028. ;; Reset the clock marker if needed
  8029. (when cmstr
  8030. (save-excursion
  8031. (goto-char start)
  8032. (search-forward cmstr nil t)
  8033. (move-marker org-clock-marker (point))))
  8034. (message "Sorting entries...done")))
  8035. ;;; The orgstruct minor mode
  8036. ;; Define a minor mode which can be used in other modes in order to
  8037. ;; integrate the Org mode structure editing commands.
  8038. ;; This is really a hack, because the Org mode structure commands use
  8039. ;; keys which normally belong to the major mode. Here is how it
  8040. ;; works: The minor mode defines all the keys necessary to operate the
  8041. ;; structure commands, but wraps the commands into a function which
  8042. ;; tests if the cursor is currently at a headline or a plain list
  8043. ;; item. If that is the case, the structure command is used,
  8044. ;; temporarily setting many Org mode variables like regular
  8045. ;; expressions for filling etc. However, when any of those keys is
  8046. ;; used at a different location, function uses `key-binding' to look
  8047. ;; up if the key has an associated command in another currently active
  8048. ;; keymap (minor modes, major mode, global), and executes that
  8049. ;; command. There might be problems if any of the keys is otherwise
  8050. ;; used as a prefix key.
  8051. (defcustom orgstruct-heading-prefix-regexp ""
  8052. "Regexp that matches the custom prefix of Org headlines in
  8053. orgstruct(++)-mode."
  8054. :group 'org
  8055. :version "24.4"
  8056. :package-version '(Org . "8.3")
  8057. :type 'regexp)
  8058. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8059. (defcustom orgstruct-setup-hook nil
  8060. "Hook run after orgstruct-mode-map is filled."
  8061. :group 'org
  8062. :version "24.4"
  8063. :package-version '(Org . "8.0")
  8064. :type 'hook)
  8065. (defvar orgstruct-initialized nil)
  8066. (defvar org-local-vars nil
  8067. "List of local variables, for use by `orgstruct-mode'.")
  8068. ;;;###autoload
  8069. (define-minor-mode orgstruct-mode
  8070. "Toggle the minor mode `orgstruct-mode'.
  8071. This mode is for using Org mode structure commands in other
  8072. modes. The following keys behave as if Org mode were active, if
  8073. the cursor is on a headline, or on a plain list item (both as
  8074. defined by Org mode)."
  8075. nil " OrgStruct" (make-sparse-keymap)
  8076. (funcall (if orgstruct-mode
  8077. 'add-to-invisibility-spec
  8078. 'remove-from-invisibility-spec)
  8079. '(outline . t))
  8080. (when orgstruct-mode
  8081. (org-load-modules-maybe)
  8082. (unless orgstruct-initialized
  8083. (orgstruct-setup)
  8084. (setq orgstruct-initialized t))))
  8085. ;;;###autoload
  8086. (defun turn-on-orgstruct ()
  8087. "Unconditionally turn on `orgstruct-mode'."
  8088. (orgstruct-mode 1))
  8089. (defvar-local orgstruct-is-++ nil
  8090. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8091. (defvar-local org-fb-vars nil)
  8092. (defun orgstruct++-mode (&optional arg)
  8093. "Toggle `orgstruct-mode', the enhanced version of it.
  8094. In addition to setting orgstruct-mode, this also exports all
  8095. indentation and autofilling variables from Org mode into the
  8096. buffer. It will also recognize item context in multiline items."
  8097. (interactive "P")
  8098. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8099. (if (< arg 1)
  8100. (progn (orgstruct-mode -1)
  8101. (dolist (v org-fb-vars)
  8102. (set (make-local-variable (car v))
  8103. (if (eq (car-safe (cadr v)) 'quote)
  8104. (cl-cadadr v)
  8105. (nth 1 v)))))
  8106. (orgstruct-mode 1)
  8107. (setq org-fb-vars nil)
  8108. (unless org-local-vars
  8109. (setq org-local-vars (org-get-local-variables)))
  8110. (let (var val)
  8111. (dolist (x org-local-vars)
  8112. (when (string-match
  8113. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8114. \\|fill-prefix\\|indent-\\)"
  8115. (symbol-name (car x)))
  8116. (setq var (car x) val (nth 1 x))
  8117. (push (list var `(quote ,(eval var))) org-fb-vars)
  8118. (set (make-local-variable var)
  8119. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8120. (setq-local orgstruct-is-++ t))))
  8121. ;;;###autoload
  8122. (defun turn-on-orgstruct++ ()
  8123. "Unconditionally turn on `orgstruct++-mode'."
  8124. (orgstruct++-mode 1))
  8125. (defun orgstruct-error ()
  8126. "Error when there is no default binding for a structure key."
  8127. (interactive)
  8128. (funcall (if (fboundp 'user-error)
  8129. 'user-error
  8130. 'error)
  8131. "This key has no function outside structure elements"))
  8132. (defun orgstruct-setup ()
  8133. "Setup orgstruct keymap."
  8134. (dolist (cell '((org-demote . t)
  8135. (org-metaleft . t)
  8136. (org-metaright . t)
  8137. (org-promote . t)
  8138. (org-shiftmetaleft . t)
  8139. (org-shiftmetaright . t)
  8140. org-backward-element
  8141. org-backward-heading-same-level
  8142. org-ctrl-c-ret
  8143. org-ctrl-c-minus
  8144. org-ctrl-c-star
  8145. org-cycle
  8146. org-force-cycle-archived
  8147. org-forward-heading-same-level
  8148. org-insert-heading
  8149. org-insert-heading-respect-content
  8150. org-kill-note-or-show-branches
  8151. org-mark-subtree
  8152. org-meta-return
  8153. org-metadown
  8154. org-metaup
  8155. org-narrow-to-subtree
  8156. org-promote-subtree
  8157. org-reveal
  8158. org-shiftdown
  8159. org-shiftleft
  8160. org-shiftmetadown
  8161. org-shiftmetaup
  8162. org-shiftright
  8163. org-shifttab
  8164. org-shifttab
  8165. org-shiftup
  8166. org-show-children
  8167. org-show-subtree
  8168. org-sort
  8169. org-up-element
  8170. outline-demote
  8171. outline-next-visible-heading
  8172. outline-previous-visible-heading
  8173. outline-promote
  8174. outline-up-heading))
  8175. (let ((f (or (car-safe cell) cell))
  8176. (disable-when-heading-prefix (cdr-safe cell)))
  8177. (when (fboundp f)
  8178. (let ((new-bindings))
  8179. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8180. (where-is-internal f outline-mode-map)))
  8181. (push binding new-bindings)
  8182. ;; TODO use local-function-key-map
  8183. (dolist (rep '(("<tab>" . "TAB")
  8184. ("<return>" . "RET")
  8185. ("<escape>" . "ESC")
  8186. ("<delete>" . "DEL")))
  8187. (setq binding (read-kbd-macro
  8188. (let ((case-fold-search))
  8189. (replace-regexp-in-string
  8190. (regexp-quote (cdr rep))
  8191. (car rep)
  8192. (key-description binding)))))
  8193. (cl-pushnew binding new-bindings :test 'equal)))
  8194. (dolist (binding new-bindings)
  8195. (let ((key (lookup-key orgstruct-mode-map binding)))
  8196. (when (or (not key) (numberp key))
  8197. (ignore-errors
  8198. (org-defkey orgstruct-mode-map
  8199. binding
  8200. (orgstruct-make-binding
  8201. f binding disable-when-heading-prefix))))))))))
  8202. (run-hooks 'orgstruct-setup-hook))
  8203. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8204. "Create a function for binding in the structure minor mode.
  8205. FUN is the command to call inside a table. KEY is the key that
  8206. should be checked in for a command to execute outside of tables.
  8207. Non-nil `disable-when-heading-prefix' means to disable the command
  8208. if `orgstruct-heading-prefix-regexp' is not empty."
  8209. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8210. (let ((nname name)
  8211. (i 0))
  8212. (while (fboundp (intern nname))
  8213. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8214. (setq name (intern nname)))
  8215. (eval
  8216. (let ((bindings '((org-heading-regexp
  8217. (concat "^"
  8218. orgstruct-heading-prefix-regexp
  8219. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8220. (org-outline-regexp
  8221. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8222. (org-outline-regexp-bol
  8223. (concat "^" org-outline-regexp))
  8224. (outline-regexp org-outline-regexp)
  8225. (outline-heading-end-regexp "\n")
  8226. (outline-level 'org-outline-level)
  8227. (outline-heading-alist))))
  8228. `(defun ,name (arg)
  8229. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8230. "Outside of structure, run the binding of `"
  8231. (key-description key) "'."
  8232. (when disable-when-heading-prefix
  8233. (concat
  8234. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8235. "back to the default binding due to limitations of Org's implementation of\n"
  8236. "`" (symbol-name fun) "'.")))
  8237. (interactive "p")
  8238. (let* ((disable
  8239. ,(and disable-when-heading-prefix
  8240. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8241. (fallback
  8242. (or disable
  8243. (not
  8244. (let* ,bindings
  8245. (org-context-p 'headline 'item
  8246. ,(when (memq fun
  8247. '(org-insert-heading
  8248. org-insert-heading-respect-content
  8249. org-meta-return))
  8250. '(when orgstruct-is-++
  8251. 'item-body))))))))
  8252. (if fallback
  8253. (let* ((orgstruct-mode)
  8254. (binding
  8255. (let ((key ,key))
  8256. (catch 'exit
  8257. (dolist
  8258. (rep
  8259. '(nil
  8260. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8261. ("<\\([^>]*\\)return>" . "\\1RET")
  8262. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8263. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8264. nil)
  8265. (when rep
  8266. (setq key (read-kbd-macro
  8267. (let ((case-fold-search))
  8268. (replace-regexp-in-string
  8269. (car rep)
  8270. (cdr rep)
  8271. (key-description key))))))
  8272. (when (key-binding key)
  8273. (throw 'exit (key-binding key))))))))
  8274. (if (keymapp binding)
  8275. (org-set-transient-map binding)
  8276. (let ((func (or binding
  8277. (unless disable
  8278. 'orgstruct-error))))
  8279. (when func
  8280. (call-interactively func)))))
  8281. (org-run-like-in-org-mode
  8282. (lambda ()
  8283. (interactive)
  8284. (let* ,bindings
  8285. (call-interactively ',fun)))))))))
  8286. name))
  8287. (defun org-contextualize-keys (alist contexts)
  8288. "Return valid elements in ALIST depending on CONTEXTS.
  8289. `org-agenda-custom-commands' or `org-capture-templates' are the
  8290. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8291. or `org-capture-templates-contexts' are the associated contexts
  8292. definitions."
  8293. (let ((contexts
  8294. ;; normalize contexts
  8295. (mapcar
  8296. (lambda(c) (cond ((listp (cadr c))
  8297. (list (car c) (car c) (nth 1 c)))
  8298. ((string= "" (cadr c))
  8299. (list (car c) (car c) (nth 2 c)))
  8300. (t c)))
  8301. contexts))
  8302. (a alist) r s)
  8303. ;; loop over all commands or templates
  8304. (dolist (c a)
  8305. (let (vrules repl)
  8306. (cond
  8307. ((not (assoc (car c) contexts))
  8308. (push c r))
  8309. ((and (assoc (car c) contexts)
  8310. (setq vrules (org-contextualize-validate-key
  8311. (car c) contexts)))
  8312. (mapc (lambda (vr)
  8313. (unless (equal (car vr) (cadr vr))
  8314. (setq repl vr)))
  8315. vrules)
  8316. (if (not repl) (push c r)
  8317. (push (cadr repl) s)
  8318. (push
  8319. (cons (car c)
  8320. (cdr (or (assoc (cadr repl) alist)
  8321. (error "Undefined key `%s' as contextual replacement for `%s'"
  8322. (cadr repl) (car c)))))
  8323. r))))))
  8324. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8325. (delq
  8326. nil
  8327. (delete-dups
  8328. (mapcar (lambda (x)
  8329. (let ((tpl (car x)))
  8330. (unless (delq
  8331. nil
  8332. (mapcar (lambda (y)
  8333. (equal y tpl))
  8334. s))
  8335. x)))
  8336. (reverse r))))))
  8337. (defun org-contextualize-validate-key (key contexts)
  8338. "Check CONTEXTS for agenda or capture KEY."
  8339. (let (res)
  8340. (dolist (r contexts)
  8341. (dolist (rr (car (last r)))
  8342. (when
  8343. (and (equal key (car r))
  8344. (if (functionp rr) (funcall rr)
  8345. (or (and (eq (car rr) 'in-file)
  8346. (buffer-file-name)
  8347. (string-match (cdr rr) (buffer-file-name)))
  8348. (and (eq (car rr) 'in-mode)
  8349. (string-match (cdr rr) (symbol-name major-mode)))
  8350. (and (eq (car rr) 'in-buffer)
  8351. (string-match (cdr rr) (buffer-name)))
  8352. (when (and (eq (car rr) 'not-in-file)
  8353. (buffer-file-name))
  8354. (not (string-match (cdr rr) (buffer-file-name))))
  8355. (when (eq (car rr) 'not-in-mode)
  8356. (not (string-match (cdr rr) (symbol-name major-mode))))
  8357. (when (eq (car rr) 'not-in-buffer)
  8358. (not (string-match (cdr rr) (buffer-name)))))))
  8359. (push r res))))
  8360. (delete-dups (delq nil res))))
  8361. (defun org-context-p (&rest contexts)
  8362. "Check if local context is any of CONTEXTS.
  8363. Possible values in the list of contexts are `table', `headline', and `item'."
  8364. (let ((pos (point)))
  8365. (goto-char (point-at-bol))
  8366. (prog1 (or (and (memq 'table contexts)
  8367. (looking-at "[ \t]*|"))
  8368. (and (memq 'headline contexts)
  8369. (looking-at org-outline-regexp))
  8370. (and (memq 'item contexts)
  8371. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8372. (and (memq 'item-body contexts)
  8373. (org-in-item-p)))
  8374. (goto-char pos))))
  8375. (defconst org-unique-local-variables
  8376. '(org-element--cache
  8377. org-element--cache-objects
  8378. org-element--cache-sync-keys
  8379. org-element--cache-sync-requests
  8380. org-element--cache-sync-timer)
  8381. "List of local variables that cannot be transferred to another buffer.")
  8382. (defun org-get-local-variables ()
  8383. "Return a list of all local variables in an Org mode buffer."
  8384. (delq nil
  8385. (mapcar
  8386. (lambda (x)
  8387. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8388. (name (car binding)))
  8389. (and (not (get name 'org-state))
  8390. (not (memq name org-unique-local-variables))
  8391. (string-match-p
  8392. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8393. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8394. (symbol-name name))
  8395. binding)))
  8396. (with-temp-buffer
  8397. (org-mode)
  8398. (buffer-local-variables)))))
  8399. (defun org-clone-local-variables (from-buffer &optional regexp)
  8400. "Clone local variables from FROM-BUFFER.
  8401. Optional argument REGEXP selects variables to clone."
  8402. (dolist (pair (buffer-local-variables from-buffer))
  8403. (pcase pair
  8404. (`(,name ,_) ;ignore unbound variables
  8405. (when (and (not (memq name org-unique-local-variables))
  8406. (or (null regexp) (string-match-p regexp (symbol-name name))))
  8407. (set (make-local-variable name) (cdr pair)))))))
  8408. ;;;###autoload
  8409. (defun org-run-like-in-org-mode (cmd)
  8410. "Run a command, pretending that the current buffer is in Org mode.
  8411. This will temporarily bind local variables that are typically bound in
  8412. Org mode to the values they have in Org mode, and then interactively
  8413. call CMD."
  8414. (org-load-modules-maybe)
  8415. (unless org-local-vars
  8416. (setq org-local-vars (org-get-local-variables)))
  8417. (let (binds)
  8418. (dolist (var org-local-vars)
  8419. (when (or (not (boundp (car var)))
  8420. (eq (symbol-value (car var))
  8421. (default-value (car var))))
  8422. (push (list (car var) `(quote ,(cadr var))) binds)))
  8423. (eval `(let ,binds
  8424. (call-interactively (quote ,cmd))))))
  8425. (defun org-get-category (&optional pos force-refresh)
  8426. "Get the category applying to position POS."
  8427. (save-match-data
  8428. (when force-refresh (org-refresh-category-properties))
  8429. (let ((pos (or pos (point))))
  8430. (or (get-text-property pos 'org-category)
  8431. (progn (org-refresh-category-properties)
  8432. (get-text-property pos 'org-category))))))
  8433. ;;; Refresh properties
  8434. (defun org-refresh-properties (dprop tprop)
  8435. "Refresh buffer text properties.
  8436. DPROP is the drawer property and TPROP is either the
  8437. corresponding text property to set, or an alist with each element
  8438. being a text property (as a symbol) and a function to apply to
  8439. the value of the drawer property."
  8440. (let* ((case-fold-search t)
  8441. (inhibit-read-only t)
  8442. (inherit? (org-property-inherit-p dprop))
  8443. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8444. (global (and inherit? (org--property-global-value dprop nil))))
  8445. (org-with-silent-modifications
  8446. (org-with-point-at 1
  8447. ;; Set global values (e.g., values defined through
  8448. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8449. (when global (put-text-property (point-min) (point-max) tprop global))
  8450. ;; Set local values.
  8451. (while (re-search-forward property-re nil t)
  8452. (when (org-at-property-p)
  8453. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8454. (outline-next-heading))))))
  8455. (defun org-refresh-property (tprop p &optional inherit)
  8456. "Refresh the buffer text property TPROP from the drawer property P.
  8457. The refresh happens only for the current headline, or the whole
  8458. sub-tree if optional argument INHERIT is non-nil."
  8459. (unless (org-before-first-heading-p)
  8460. (save-excursion
  8461. (org-back-to-heading t)
  8462. (let ((start (point))
  8463. (end (save-excursion
  8464. (if inherit (org-end-of-subtree t t)
  8465. (or (outline-next-heading) (point-max))))))
  8466. (if (symbolp tprop)
  8467. ;; TPROP is a text property symbol.
  8468. (put-text-property start end tprop p)
  8469. ;; TPROP is an alist with (property . function) elements.
  8470. (pcase-dolist (`(,prop . ,f) tprop)
  8471. (put-text-property start end prop (funcall f p))))))))
  8472. (defun org-refresh-category-properties ()
  8473. "Refresh category text properties in the buffer."
  8474. (let ((case-fold-search t)
  8475. (inhibit-read-only t)
  8476. (default-category
  8477. (cond ((null org-category)
  8478. (if buffer-file-name
  8479. (file-name-sans-extension
  8480. (file-name-nondirectory buffer-file-name))
  8481. "???"))
  8482. ((symbolp org-category) (symbol-name org-category))
  8483. (t org-category))))
  8484. (org-with-silent-modifications
  8485. (org-with-wide-buffer
  8486. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8487. ;; This is the default category for the buffer. If none is
  8488. ;; found, fall-back to `org-category' or buffer file name.
  8489. (put-text-property
  8490. (point-min) (point-max)
  8491. 'org-category
  8492. (catch 'buffer-category
  8493. (goto-char (point-max))
  8494. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8495. (let ((element (org-element-at-point)))
  8496. (when (eq (org-element-type element) 'keyword)
  8497. (throw 'buffer-category
  8498. (org-element-property :value element)))))
  8499. default-category))
  8500. ;; Set sub-tree specific categories.
  8501. (goto-char (point-min))
  8502. (let ((regexp (org-re-property "CATEGORY")))
  8503. (while (re-search-forward regexp nil t)
  8504. (let ((value (match-string-no-properties 3)))
  8505. (when (org-at-property-p)
  8506. (put-text-property
  8507. (save-excursion (org-back-to-heading t) (point))
  8508. (save-excursion (org-end-of-subtree t t) (point))
  8509. 'org-category
  8510. value)))))))))
  8511. (defun org-refresh-stats-properties ()
  8512. "Refresh stats text properties in the buffer."
  8513. (org-with-silent-modifications
  8514. (org-with-point-at 1
  8515. (let ((regexp (concat org-outline-regexp-bol
  8516. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8517. (while (re-search-forward regexp nil t)
  8518. (let* ((numerator (string-to-number (match-string 1)))
  8519. (denominator (and (match-end 2)
  8520. (string-to-number (match-string 2))))
  8521. (stats (cond ((not denominator) numerator) ;percent
  8522. ((= denominator 0) 0)
  8523. (t (/ (* numerator 100) denominator)))))
  8524. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8525. 'org-stats stats)))))))
  8526. (defun org-refresh-effort-properties ()
  8527. "Refresh effort properties"
  8528. (org-refresh-properties
  8529. org-effort-property
  8530. '((effort . identity)
  8531. (effort-minutes . org-duration-to-minutes))))
  8532. ;;;; Link Stuff
  8533. ;;; Link abbreviations
  8534. (defun org-link-expand-abbrev (link)
  8535. "Apply replacements as defined in `org-link-abbrev-alist'."
  8536. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8537. (let* ((key (match-string 1 link))
  8538. (as (or (assoc key org-link-abbrev-alist-local)
  8539. (assoc key org-link-abbrev-alist)))
  8540. (tag (and (match-end 2) (match-string 3 link)))
  8541. rpl)
  8542. (if (not as)
  8543. link
  8544. (setq rpl (cdr as))
  8545. (cond
  8546. ((symbolp rpl) (funcall rpl tag))
  8547. ((string-match "%(\\([^)]+\\))" rpl)
  8548. (replace-match
  8549. (save-match-data
  8550. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8551. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8552. ((string-match "%h" rpl)
  8553. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8554. (t (concat rpl tag)))))
  8555. link))
  8556. ;;; Storing and inserting links
  8557. (defvar org-insert-link-history nil
  8558. "Minibuffer history for links inserted with `org-insert-link'.")
  8559. (defvar org-stored-links nil
  8560. "Contains the links stored with `org-store-link'.")
  8561. (defvar org-store-link-plist nil
  8562. "Plist with info about the most recently link created with `org-store-link'.")
  8563. (defun org-store-link-functions ()
  8564. "Return a list of functions that are called to create and store a link.
  8565. The functions defined in the :store property of
  8566. `org-link-parameters'.
  8567. Each function will be called in turn until one returns a non-nil
  8568. value. Each function should check if it is responsible for
  8569. creating this link (for example by looking at the major mode).
  8570. If not, it must exit and return nil. If yes, it should return
  8571. a non-nil value after calling `org-store-link-props' with a list
  8572. of properties and values. Special properties are:
  8573. :type The link prefix, like \"http\". This must be given.
  8574. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8575. This is obligatory as well.
  8576. :description Optional default description for the second pair
  8577. of brackets in an Org mode link. The user can still change
  8578. this when inserting this link into an Org mode buffer.
  8579. In addition to these, any additional properties can be specified
  8580. and then used in capture templates."
  8581. (cl-loop for link in org-link-parameters
  8582. with store-func
  8583. do (setq store-func (org-link-get-parameter (car link) :store))
  8584. if store-func
  8585. collect store-func))
  8586. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8587. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8588. ;;;###autoload
  8589. (defun org-store-link (arg)
  8590. "Store an org-link to the current location.
  8591. \\<org-mode-map>
  8592. This link is added to `org-stored-links' and can later be inserted
  8593. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8594. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8595. A single
  8596. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8597. `org-gnus-prefer-web-links' for links to Usenet articles.
  8598. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8599. skipping storing functions that are not
  8600. part of Org core.
  8601. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8602. prefix ARG forces storing a link for each line in the
  8603. active region."
  8604. (interactive "P")
  8605. (org-load-modules-maybe)
  8606. (if (and (equal arg '(64)) (org-region-active-p))
  8607. (save-excursion
  8608. (let ((end (region-end)))
  8609. (goto-char (region-beginning))
  8610. (set-mark (point))
  8611. (while (< (point-at-eol) end)
  8612. (move-end-of-line 1) (activate-mark)
  8613. (let (current-prefix-arg)
  8614. (call-interactively 'org-store-link))
  8615. (move-beginning-of-line 2)
  8616. (set-mark (point)))))
  8617. (setq org-store-link-plist nil)
  8618. (let (link cpltxt desc description search
  8619. txt custom-id agenda-link sfuns sfunsn)
  8620. (cond
  8621. ;; Store a link using an external link type
  8622. ((and (not (equal arg '(16)))
  8623. (setq sfuns
  8624. (delq
  8625. nil (mapcar (lambda (f)
  8626. (let (fs) (if (funcall f) (push f fs))))
  8627. (org-store-link-functions)))
  8628. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8629. (or (and (cdr sfuns)
  8630. (funcall (intern
  8631. (completing-read
  8632. "Which function for creating the link? "
  8633. sfunsn nil t (car sfunsn)))))
  8634. (funcall (caar sfuns)))
  8635. (setq link (plist-get org-store-link-plist :link)
  8636. desc (or (plist-get org-store-link-plist
  8637. :description)
  8638. link))))
  8639. ;; Store a link from a source code buffer.
  8640. ((org-src-edit-buffer-p)
  8641. (let ((coderef-format (org-src-coderef-format)))
  8642. (cond ((save-excursion
  8643. (beginning-of-line)
  8644. (looking-at (org-src-coderef-regexp coderef-format)))
  8645. (setq link (format "(%s)" (match-string-no-properties 3))))
  8646. ((called-interactively-p 'any)
  8647. (let ((label (read-string "Code line label: ")))
  8648. (end-of-line)
  8649. (setq link (format coderef-format label))
  8650. (let ((gc (- 79 (length link))))
  8651. (if (< (current-column) gc)
  8652. (org-move-to-column gc t)
  8653. (insert " ")))
  8654. (insert link)
  8655. (setq link (concat "(" label ")"))
  8656. (setq desc nil)))
  8657. (t (setq link nil)))))
  8658. ;; We are in the agenda, link to referenced location
  8659. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8660. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8661. (get-text-property (point) 'org-marker))))
  8662. (when m
  8663. (org-with-point-at m
  8664. (setq agenda-link
  8665. (if (called-interactively-p 'any)
  8666. (call-interactively 'org-store-link)
  8667. (org-store-link nil)))))))
  8668. ((eq major-mode 'calendar-mode)
  8669. (let ((cd (calendar-cursor-to-date)))
  8670. (setq link
  8671. (format-time-string
  8672. (car org-time-stamp-formats)
  8673. (apply 'encode-time
  8674. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8675. nil nil nil))))
  8676. (org-store-link-props :type "calendar" :date cd)))
  8677. ((eq major-mode 'help-mode)
  8678. (setq link (concat "help:" (save-excursion
  8679. (goto-char (point-min))
  8680. (looking-at "^[^ ]+")
  8681. (match-string 0))))
  8682. (org-store-link-props :type "help"))
  8683. ((eq major-mode 'w3-mode)
  8684. (setq cpltxt (if (and (buffer-name)
  8685. (not (string-match "Untitled" (buffer-name))))
  8686. (buffer-name)
  8687. (url-view-url t))
  8688. link (url-view-url t))
  8689. (org-store-link-props :type "w3" :url (url-view-url t)))
  8690. ((eq major-mode 'image-mode)
  8691. (setq cpltxt (concat "file:"
  8692. (abbreviate-file-name buffer-file-name))
  8693. link cpltxt)
  8694. (org-store-link-props :type "image" :file buffer-file-name))
  8695. ;; In dired, store a link to the file of the current line
  8696. ((derived-mode-p 'dired-mode)
  8697. (let ((file (dired-get-filename nil t)))
  8698. (setq file (if file
  8699. (abbreviate-file-name
  8700. (expand-file-name (dired-get-filename nil t)))
  8701. ;; otherwise, no file so use current directory.
  8702. default-directory))
  8703. (setq cpltxt (concat "file:" file)
  8704. link cpltxt)))
  8705. ((setq search (run-hook-with-args-until-success
  8706. 'org-create-file-search-functions))
  8707. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8708. "::" search))
  8709. (setq cpltxt (or description link)))
  8710. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8711. (org-with-limited-levels
  8712. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8713. (cond
  8714. ;; Store a link using the target at point
  8715. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8716. (setq cpltxt
  8717. (concat "file:"
  8718. (abbreviate-file-name
  8719. (buffer-file-name (buffer-base-buffer)))
  8720. "::" (match-string 1))
  8721. link cpltxt))
  8722. ((and (featurep 'org-id)
  8723. (or (eq org-id-link-to-org-use-id t)
  8724. (and (called-interactively-p 'any)
  8725. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8726. (and (eq org-id-link-to-org-use-id
  8727. 'create-if-interactive-and-no-custom-id)
  8728. (not custom-id))))
  8729. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8730. ;; Store a link using the ID at point
  8731. (setq link (condition-case nil
  8732. (prog1 (org-id-store-link)
  8733. (setq desc (or (plist-get org-store-link-plist
  8734. :description)
  8735. "")))
  8736. (error
  8737. ;; Probably before first headline, link only to file
  8738. (concat "file:"
  8739. (abbreviate-file-name
  8740. (buffer-file-name (buffer-base-buffer))))))))
  8741. (t
  8742. ;; Just link to current headline
  8743. (setq cpltxt (concat "file:"
  8744. (abbreviate-file-name
  8745. (buffer-file-name (buffer-base-buffer)))))
  8746. ;; Add a context search string
  8747. (when (org-xor org-context-in-file-links
  8748. (equal arg '(4)))
  8749. (let* ((element (org-element-at-point))
  8750. (name (org-element-property :name element)))
  8751. (setq txt (cond
  8752. ((org-at-heading-p) nil)
  8753. (name)
  8754. ((org-region-active-p)
  8755. (buffer-substring (region-beginning) (region-end)))))
  8756. (when (or (null txt) (string-match "\\S-" txt))
  8757. (setq cpltxt
  8758. (concat cpltxt "::"
  8759. (condition-case nil
  8760. (org-make-org-heading-search-string txt)
  8761. (error "")))
  8762. desc (or name
  8763. (nth 4 (ignore-errors (org-heading-components)))
  8764. "NONE")))))
  8765. (when (string-match "::\\'" cpltxt)
  8766. (setq cpltxt (substring cpltxt 0 -2)))
  8767. (setq link cpltxt)))))
  8768. ((buffer-file-name (buffer-base-buffer))
  8769. ;; Just link to this file here.
  8770. (setq cpltxt (concat "file:"
  8771. (abbreviate-file-name
  8772. (buffer-file-name (buffer-base-buffer)))))
  8773. ;; Add a context string.
  8774. (when (org-xor org-context-in-file-links
  8775. (equal arg '(4)))
  8776. (setq txt (if (org-region-active-p)
  8777. (buffer-substring (region-beginning) (region-end))
  8778. (buffer-substring (point-at-bol) (point-at-eol))))
  8779. ;; Only use search option if there is some text.
  8780. (when (string-match "\\S-" txt)
  8781. (setq cpltxt
  8782. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8783. desc "NONE")))
  8784. (setq link cpltxt))
  8785. ((called-interactively-p 'interactive)
  8786. (user-error "No method for storing a link from this buffer"))
  8787. (t (setq link nil)))
  8788. ;; We're done setting link and desc, clean up
  8789. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8790. (setq link (or link cpltxt)
  8791. desc (or desc cpltxt))
  8792. (cond ((not desc))
  8793. ((equal desc "NONE") (setq desc nil))
  8794. (t (setq desc
  8795. (replace-regexp-in-string
  8796. org-bracket-link-analytic-regexp
  8797. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8798. desc))))
  8799. ;; Return the link
  8800. (if (not (and (or (called-interactively-p 'any)
  8801. executing-kbd-macro)
  8802. link))
  8803. (or agenda-link (and link (org-make-link-string link desc)))
  8804. (push (list link desc) org-stored-links)
  8805. (message "Stored: %s" (or desc link))
  8806. (when custom-id
  8807. (setq link (concat "file:" (abbreviate-file-name
  8808. (buffer-file-name)) "::#" custom-id))
  8809. (push (list link desc) org-stored-links))
  8810. (car org-stored-links)))))
  8811. (defun org-store-link-props (&rest plist)
  8812. "Store link properties, extract names, addresses and dates."
  8813. (let ((x (plist-get plist :from)))
  8814. (when x
  8815. (let ((adr (mail-extract-address-components x)))
  8816. (setq plist (plist-put plist :fromname (car adr)))
  8817. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8818. (let ((x (plist-get plist :to)))
  8819. (when x
  8820. (let ((adr (mail-extract-address-components x)))
  8821. (setq plist (plist-put plist :toname (car adr)))
  8822. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8823. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8824. (when x
  8825. (setq plist (plist-put plist :date-timestamp
  8826. (format-time-string
  8827. (org-time-stamp-format t) x)))
  8828. (setq plist (plist-put plist :date-timestamp-inactive
  8829. (format-time-string
  8830. (org-time-stamp-format t t) x)))))
  8831. (let ((from (plist-get plist :from))
  8832. (to (plist-get plist :to)))
  8833. (when (and from to org-from-is-user-regexp)
  8834. (setq plist
  8835. (plist-put plist :fromto
  8836. (if (string-match org-from-is-user-regexp from)
  8837. (concat "to %t")
  8838. (concat "from %f"))))))
  8839. (setq org-store-link-plist plist))
  8840. (defun org-add-link-props (&rest plist)
  8841. "Add these properties to the link property list."
  8842. (let (key value)
  8843. (while plist
  8844. (setq key (pop plist) value (pop plist))
  8845. (setq org-store-link-plist
  8846. (plist-put org-store-link-plist key value)))))
  8847. (defun org-email-link-description (&optional fmt)
  8848. "Return the description part of an email link.
  8849. This takes information from `org-store-link-plist' and formats it
  8850. according to FMT (default from `org-email-link-description-format')."
  8851. (setq fmt (or fmt org-email-link-description-format))
  8852. (let* ((p org-store-link-plist)
  8853. (to (plist-get p :toaddress))
  8854. (from (plist-get p :fromaddress))
  8855. (table
  8856. (list
  8857. (cons "%c" (plist-get p :fromto))
  8858. (cons "%F" (plist-get p :from))
  8859. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  8860. (cons "%T" (plist-get p :to))
  8861. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  8862. (cons "%s" (plist-get p :subject))
  8863. (cons "%d" (plist-get p :date))
  8864. (cons "%m" (plist-get p :message-id)))))
  8865. (when (string-match "%c" fmt)
  8866. ;; Check if the user wrote this message
  8867. (if (and org-from-is-user-regexp from to
  8868. (save-match-data (string-match org-from-is-user-regexp from)))
  8869. (setq fmt (replace-match "to %t" t t fmt))
  8870. (setq fmt (replace-match "from %f" t t fmt))))
  8871. (org-replace-escapes fmt table)))
  8872. (defun org-make-org-heading-search-string (&optional string)
  8873. "Make search string for the current headline or STRING."
  8874. (let ((s (or string
  8875. (and (derived-mode-p 'org-mode)
  8876. (save-excursion
  8877. (org-back-to-heading t)
  8878. (org-element-property :raw-value (org-element-at-point))))))
  8879. (lines org-context-in-file-links))
  8880. (or string (setq s (concat "*" s))) ; Add * for headlines
  8881. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  8882. (when (and string (integerp lines) (> lines 0))
  8883. (let ((slines (org-split-string s "\n")))
  8884. (when (< lines (length slines))
  8885. (setq s (mapconcat
  8886. 'identity
  8887. (reverse (nthcdr (- (length slines) lines)
  8888. (reverse slines))) "\n")))))
  8889. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  8890. (defun org-make-link-string (link &optional description)
  8891. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  8892. (unless (org-string-nw-p link) (error "Empty link"))
  8893. (let ((uri (cond ((string-match org-link-types-re link)
  8894. (concat (match-string 1 link)
  8895. (org-link-escape (substring link (match-end 1)))))
  8896. ;; For readability, url-encode internal links only
  8897. ;; when absolutely needed (i.e, when they contain
  8898. ;; square brackets). File links however, are
  8899. ;; encoded since, e.g., spaces are significant.
  8900. ((or (file-name-absolute-p link)
  8901. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  8902. (org-link-escape link))
  8903. (t link)))
  8904. (description
  8905. (and (org-string-nw-p description)
  8906. ;; Remove brackets from description, as they are fatal.
  8907. (replace-regexp-in-string
  8908. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  8909. (org-trim description)))))
  8910. (format "[[%s]%s]"
  8911. uri
  8912. (if description (format "[%s]" description) ""))))
  8913. (defconst org-link-escape-chars
  8914. ;;%20 %5B %5D %25
  8915. '(?\s ?\[ ?\] ?%)
  8916. "List of characters that should be escaped in a link when stored to Org.
  8917. This is the list that is used for internal purposes.")
  8918. (defun org-link-escape (text &optional table merge)
  8919. "Return percent escaped representation of TEXT.
  8920. TEXT is a string with the text to escape.
  8921. Optional argument TABLE is a list with characters that should be
  8922. escaped. When nil, `org-link-escape-chars' is used.
  8923. If optional argument MERGE is set, merge TABLE into
  8924. `org-link-escape-chars'."
  8925. (let ((characters-to-encode
  8926. (cond ((null table) org-link-escape-chars)
  8927. (merge (append org-link-escape-chars table))
  8928. (t table))))
  8929. (mapconcat
  8930. (lambda (c)
  8931. (if (or (memq c characters-to-encode)
  8932. (and org-url-hexify-p (or (< c 32) (> c 126))))
  8933. (mapconcat (lambda (e) (format "%%%.2X" e))
  8934. (or (encode-coding-char c 'utf-8)
  8935. (error "Unable to percent escape character: %c" c))
  8936. "")
  8937. (char-to-string c)))
  8938. text "")))
  8939. (defun org-link-unescape (str)
  8940. "Unhex hexified Unicode parts in string STR.
  8941. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  8942. reciprocal of `org-link-escape', which see."
  8943. (if (org-string-nw-p str)
  8944. (replace-regexp-in-string
  8945. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  8946. str))
  8947. (defun org-link-unescape-compound (hex)
  8948. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  8949. Note: this function also decodes single byte encodings like
  8950. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  8951. (save-match-data
  8952. (let* ((bytes (cdr (split-string hex "%")))
  8953. (ret "")
  8954. (eat 0)
  8955. (sum 0))
  8956. (while bytes
  8957. (let* ((val (string-to-number (pop bytes) 16))
  8958. (shift-xor
  8959. (if (= 0 eat)
  8960. (cond
  8961. ((>= val 252) (cons 6 252))
  8962. ((>= val 248) (cons 5 248))
  8963. ((>= val 240) (cons 4 240))
  8964. ((>= val 224) (cons 3 224))
  8965. ((>= val 192) (cons 2 192))
  8966. (t (cons 0 0)))
  8967. (cons 6 128))))
  8968. (when (>= val 192) (setq eat (car shift-xor)))
  8969. (setq val (logxor val (cdr shift-xor)))
  8970. (setq sum (+ (lsh sum (car shift-xor)) val))
  8971. (when (> eat 0) (setq eat (- eat 1)))
  8972. (cond
  8973. ((= 0 eat) ;multi byte
  8974. (setq ret (concat ret (char-to-string sum)))
  8975. (setq sum 0))
  8976. ((not bytes) ; single byte(s)
  8977. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  8978. ret)))
  8979. (defun org-link-unescape-single-byte-sequence (hex)
  8980. "Unhexify hex-encoded single byte character sequences."
  8981. (mapconcat (lambda (byte)
  8982. (char-to-string (string-to-number byte 16)))
  8983. (cdr (split-string hex "%")) ""))
  8984. (defun org-xor (a b)
  8985. "Exclusive or."
  8986. (if a (not b) b))
  8987. (defun org-fixup-message-id-for-http (s)
  8988. "Replace special characters in a message id, so it can be used in an http query."
  8989. (when (string-match "%" s)
  8990. (setq s (mapconcat (lambda (c)
  8991. (if (eq c ?%)
  8992. "%25"
  8993. (char-to-string c)))
  8994. s "")))
  8995. (while (string-match "<" s)
  8996. (setq s (replace-match "%3C" t t s)))
  8997. (while (string-match ">" s)
  8998. (setq s (replace-match "%3E" t t s)))
  8999. (while (string-match "@" s)
  9000. (setq s (replace-match "%40" t t s)))
  9001. s)
  9002. (defun org-link-prettify (link)
  9003. "Return a human-readable representation of LINK.
  9004. The car of LINK must be a raw link.
  9005. The cdr of LINK must be either a link description or nil."
  9006. (let ((desc (or (cadr link) "<no description>")))
  9007. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9008. "<" (car link) ">")))
  9009. ;;;###autoload
  9010. (defun org-insert-link-global ()
  9011. "Insert a link like Org mode does.
  9012. This command can be called in any mode to insert a link in Org syntax."
  9013. (interactive)
  9014. (org-load-modules-maybe)
  9015. (org-run-like-in-org-mode 'org-insert-link))
  9016. (defun org-insert-all-links (arg &optional pre post)
  9017. "Insert all links in `org-stored-links'.
  9018. When a universal prefix, do not delete the links from `org-stored-links'.
  9019. When `ARG' is a number, insert the last N link(s).
  9020. `PRE' and `POST' are optional arguments to define a string to
  9021. prepend or to append."
  9022. (interactive "P")
  9023. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9024. (links (copy-sequence org-stored-links))
  9025. (pr (or pre "- "))
  9026. (po (or post "\n"))
  9027. (cnt 1) l)
  9028. (if (null org-stored-links)
  9029. (message "No link to insert")
  9030. (while (and (or (listp arg) (>= arg cnt))
  9031. (setq l (if (listp arg)
  9032. (pop links)
  9033. (pop org-stored-links))))
  9034. (setq cnt (1+ cnt))
  9035. (insert pr)
  9036. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9037. (insert po)))))
  9038. (defun org-insert-last-stored-link (arg)
  9039. "Insert the last link stored in `org-stored-links'."
  9040. (interactive "p")
  9041. (org-insert-all-links arg "" "\n"))
  9042. (defun org-link-fontify-links-to-this-file ()
  9043. "Fontify links to the current file in `org-stored-links'."
  9044. (let ((f (buffer-file-name)) a b)
  9045. (setq a (mapcar (lambda(l)
  9046. (let ((ll (car l)))
  9047. (when (and (string-match "^file:\\(.+\\)::" ll)
  9048. (equal f (expand-file-name (match-string 1 ll))))
  9049. ll)))
  9050. org-stored-links))
  9051. (when (featurep 'org-id)
  9052. (setq b (mapcar (lambda(l)
  9053. (let ((ll (car l)))
  9054. (when (and (string-match "^id:\\(.+\\)$" ll)
  9055. (equal f (expand-file-name
  9056. (or (org-id-find-id-file
  9057. (match-string 1 ll)) ""))))
  9058. ll)))
  9059. org-stored-links)))
  9060. (mapcar (lambda(l)
  9061. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9062. (delq nil (append a b)))))
  9063. (defvar org--links-history nil)
  9064. (defun org-insert-link (&optional complete-file link-location default-description)
  9065. "Insert a link. At the prompt, enter the link.
  9066. Completion can be used to insert any of the link protocol prefixes in use.
  9067. The history can be used to select a link previously stored with
  9068. `org-store-link'. When the empty string is entered (i.e. if you just
  9069. press `RET' at the prompt), the link defaults to the most recently
  9070. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9071. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9072. You will also be prompted for a description, and if one is given, it will
  9073. be displayed in the buffer instead of the link.
  9074. If there is already a link at point, this command will allow you to edit
  9075. link and description parts.
  9076. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9077. file name can be
  9078. selected using completion. The path to the file will be relative to the
  9079. current directory if the file is in the current directory or a subdirectory.
  9080. Otherwise, the link will be the absolute path as completed in the minibuffer
  9081. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9082. option `org-link-file-path-type'.
  9083. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9084. absolute path even if the file is in
  9085. the current directory or below.
  9086. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9087. prefix negates `org-keep-stored-link-after-insertion'.
  9088. If `org-make-link-description-function' is non-nil, this function will be
  9089. called with the link target, and the result will be the default
  9090. link description.
  9091. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9092. the link location instead of reading one interactively.
  9093. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9094. as the default description."
  9095. (interactive "P")
  9096. (let* ((wcf (current-window-configuration))
  9097. (origbuf (current-buffer))
  9098. (region (when (org-region-active-p)
  9099. (buffer-substring (region-beginning) (region-end))))
  9100. (remove (and region (list (region-beginning) (region-end))))
  9101. (desc region)
  9102. (link link-location)
  9103. (abbrevs org-link-abbrev-alist-local)
  9104. entry all-prefixes auto-desc)
  9105. (cond
  9106. (link-location) ; specified by arg, just use it.
  9107. ((org-in-regexp org-bracket-link-regexp 1)
  9108. ;; We do have a link at point, and we are going to edit it.
  9109. (setq remove (list (match-beginning 0) (match-end 0)))
  9110. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9111. (setq link (read-string "Link: "
  9112. (org-link-unescape
  9113. (match-string-no-properties 1)))))
  9114. ((or (org-in-regexp org-angle-link-re)
  9115. (org-in-regexp org-plain-link-re))
  9116. ;; Convert to bracket link
  9117. (setq remove (list (match-beginning 0) (match-end 0))
  9118. link (read-string "Link: "
  9119. (org-unbracket-string "<" ">" (match-string 0)))))
  9120. ((member complete-file '((4) (16)))
  9121. ;; Completing read for file names.
  9122. (setq link (org-file-complete-link complete-file)))
  9123. (t
  9124. ;; Read link, with completion for stored links.
  9125. (org-link-fontify-links-to-this-file)
  9126. (org-switch-to-buffer-other-window "*Org Links*")
  9127. (with-current-buffer "*Org Links*"
  9128. (erase-buffer)
  9129. (insert "Insert a link.
  9130. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9131. (when org-stored-links
  9132. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9133. (insert (mapconcat 'org-link-prettify
  9134. (reverse org-stored-links) "\n")))
  9135. (goto-char (point-min)))
  9136. (let ((cw (selected-window)))
  9137. (select-window (get-buffer-window "*Org Links*" 'visible))
  9138. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9139. (unless (pos-visible-in-window-p (point-max))
  9140. (org-fit-window-to-buffer))
  9141. (and (window-live-p cw) (select-window cw)))
  9142. (setq all-prefixes (append (mapcar 'car abbrevs)
  9143. (mapcar 'car org-link-abbrev-alist)
  9144. (org-link-types)))
  9145. (unwind-protect
  9146. ;; Fake a link history, containing the stored links.
  9147. (let ((org--links-history
  9148. (append (mapcar #'car org-stored-links)
  9149. org-insert-link-history)))
  9150. (setq link
  9151. (org-completing-read
  9152. "Link: "
  9153. (append
  9154. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9155. (mapcar #'car org-stored-links))
  9156. nil nil nil
  9157. 'org--links-history
  9158. (caar org-stored-links)))
  9159. (unless (org-string-nw-p link) (user-error "No link selected"))
  9160. (dolist (l org-stored-links)
  9161. (when (equal link (cadr l))
  9162. (setq link (car l))
  9163. (setq auto-desc t)))
  9164. (when (or (member link all-prefixes)
  9165. (and (equal ":" (substring link -1))
  9166. (member (substring link 0 -1) all-prefixes)
  9167. (setq link (substring link 0 -1))))
  9168. (setq link (with-current-buffer origbuf
  9169. (org-link-try-special-completion link)))))
  9170. (set-window-configuration wcf)
  9171. (kill-buffer "*Org Links*"))
  9172. (setq entry (assoc link org-stored-links))
  9173. (or entry (push link org-insert-link-history))
  9174. (setq desc (or desc (nth 1 entry)))))
  9175. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9176. (not org-keep-stored-link-after-insertion))
  9177. (setq org-stored-links (delq (assoc link org-stored-links)
  9178. org-stored-links)))
  9179. (when (and (string-match org-plain-link-re link)
  9180. (not (string-match org-ts-regexp link)))
  9181. ;; URL-like link, normalize the use of angular brackets.
  9182. (setq link (org-unbracket-string "<" ">" link)))
  9183. ;; Check if we are linking to the current file with a search
  9184. ;; option If yes, simplify the link by using only the search
  9185. ;; option.
  9186. (when (and buffer-file-name
  9187. (let ((case-fold-search nil))
  9188. (string-match "\\`file:\\(.+?\\)::" link)))
  9189. (let ((path (match-string-no-properties 1 link))
  9190. (search (substring-no-properties link (match-end 0))))
  9191. (save-match-data
  9192. (when (equal (file-truename buffer-file-name) (file-truename path))
  9193. ;; We are linking to this same file, with a search option
  9194. (setq link search)))))
  9195. ;; Check if we can/should use a relative path. If yes, simplify the link
  9196. (let ((case-fold-search nil))
  9197. (when (string-match "\\`\\(file\\|docview\\):" link)
  9198. (let* ((type (match-string-no-properties 0 link))
  9199. (path (substring-no-properties link (match-end 0)))
  9200. (origpath path))
  9201. (cond
  9202. ((or (eq org-link-file-path-type 'absolute)
  9203. (equal complete-file '(16)))
  9204. (setq path (abbreviate-file-name (expand-file-name path))))
  9205. ((eq org-link-file-path-type 'noabbrev)
  9206. (setq path (expand-file-name path)))
  9207. ((eq org-link-file-path-type 'relative)
  9208. (setq path (file-relative-name path)))
  9209. (t
  9210. (save-match-data
  9211. (if (string-match (concat "^" (regexp-quote
  9212. (expand-file-name
  9213. (file-name-as-directory
  9214. default-directory))))
  9215. (expand-file-name path))
  9216. ;; We are linking a file with relative path name.
  9217. (setq path (substring (expand-file-name path)
  9218. (match-end 0)))
  9219. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9220. (setq link (concat type path))
  9221. (when (equal desc origpath)
  9222. (setq desc path)))))
  9223. (if org-make-link-description-function
  9224. (setq desc
  9225. (or (condition-case nil
  9226. (funcall org-make-link-description-function link desc)
  9227. (error (progn (message "Can't get link description from `%s'"
  9228. (symbol-name org-make-link-description-function))
  9229. (sit-for 2) nil)))
  9230. (read-string "Description: " default-description)))
  9231. (if default-description (setq desc default-description)
  9232. (setq desc (or (and auto-desc desc)
  9233. (read-string "Description: " desc)))))
  9234. (unless (string-match "\\S-" desc) (setq desc nil))
  9235. (when remove (apply 'delete-region remove))
  9236. (insert (org-make-link-string link desc))
  9237. ;; Redisplay so as the new link has proper invisible characters.
  9238. (sit-for 0)))
  9239. (defun org-link-try-special-completion (type)
  9240. "If there is completion support for link type TYPE, offer it."
  9241. (let ((fun (org-link-get-parameter type :complete)))
  9242. (if (functionp fun)
  9243. (funcall fun)
  9244. (read-string "Link (no completion support): " (concat type ":")))))
  9245. (defun org-file-complete-link (&optional arg)
  9246. "Create a file link using completion."
  9247. (let ((file (read-file-name "File: "))
  9248. (pwd (file-name-as-directory (expand-file-name ".")))
  9249. (pwd1 (file-name-as-directory (abbreviate-file-name
  9250. (expand-file-name ".")))))
  9251. (cond ((equal arg '(16))
  9252. (concat "file:"
  9253. (abbreviate-file-name (expand-file-name file))))
  9254. ((string-match
  9255. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9256. (concat "file:" (match-string 1 file)))
  9257. ((string-match
  9258. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9259. (expand-file-name file))
  9260. (concat "file:"
  9261. (match-string 1 (expand-file-name file))))
  9262. (t (concat "file:" file)))))
  9263. (defun org-completing-read (&rest args)
  9264. "Completing-read with SPACE being a normal character."
  9265. (let ((enable-recursive-minibuffers t)
  9266. (minibuffer-local-completion-map
  9267. (copy-keymap minibuffer-local-completion-map)))
  9268. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9269. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9270. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9271. 'org-time-stamp-inactive)
  9272. (apply #'completing-read args)))
  9273. ;;; Opening/following a link
  9274. (defvar org-link-search-failed nil)
  9275. (defvar org-open-link-functions nil
  9276. "Hook for functions finding a plain text link.
  9277. These functions must take a single argument, the link content.
  9278. They will be called for links that look like [[link text][description]]
  9279. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9280. like a filename (e.g. \"./blue.png\").
  9281. These functions will be called *before* Org attempts to resolve the
  9282. link by doing text searches in the current buffer - so if you want a
  9283. link \"[[target]]\" to still find \"<<target>>\", your function should
  9284. handle this as a special case.
  9285. When the function does handle the link, it must return a non-nil value.
  9286. If it decides that it is not responsible for this link, it must return
  9287. nil to indicate that that Org can continue with other options like
  9288. exact and fuzzy text search.")
  9289. (defun org-next-link (&optional search-backward)
  9290. "Move forward to the next link.
  9291. If the link is in hidden text, expose it."
  9292. (interactive "P")
  9293. (when (and org-link-search-failed (eq this-command last-command))
  9294. (goto-char (point-min))
  9295. (message "Link search wrapped back to beginning of buffer"))
  9296. (setq org-link-search-failed nil)
  9297. (let* ((pos (point))
  9298. (ct (org-context))
  9299. (a (assq :link ct))
  9300. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9301. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9302. ((looking-at org-any-link-re)
  9303. ;; Don't stay stuck at link without an org-link face
  9304. (forward-char (if search-backward -1 1))))
  9305. (if (funcall srch-fun org-any-link-re nil t)
  9306. (progn
  9307. (goto-char (match-beginning 0))
  9308. (when (outline-invisible-p) (org-show-context)))
  9309. (goto-char pos)
  9310. (setq org-link-search-failed t)
  9311. (message "No further link found"))))
  9312. (defun org-previous-link ()
  9313. "Move backward to the previous link.
  9314. If the link is in hidden text, expose it."
  9315. (interactive)
  9316. (funcall 'org-next-link t))
  9317. (defun org-translate-link (s)
  9318. "Translate a link string if a translation function has been defined."
  9319. (with-temp-buffer
  9320. (insert (org-trim s))
  9321. (org-trim (org-element-interpret-data (org-element-context)))))
  9322. (defun org-translate-link-from-planner (type path)
  9323. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9324. This is still an experimental function, your mileage may vary."
  9325. (cond
  9326. ((member type '("http" "https" "news" "ftp"))
  9327. ;; standard Internet links are the same.
  9328. nil)
  9329. ((and (equal type "irc") (string-match "^//" path))
  9330. ;; Planner has two / at the beginning of an irc link, we have 1.
  9331. ;; We should have zero, actually....
  9332. (setq path (substring path 1)))
  9333. ((and (equal type "lisp") (string-match "^/" path))
  9334. ;; Planner has a slash, we do not.
  9335. (setq type "elisp" path (substring path 1)))
  9336. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9337. ;; A typical message link. Planner has the id after the final slash,
  9338. ;; we separate it with a hash mark
  9339. (setq path (concat (match-string 1 path) "#"
  9340. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9341. (cons type path))
  9342. (defun org-find-file-at-mouse (ev)
  9343. "Open file link or URL at mouse."
  9344. (interactive "e")
  9345. (mouse-set-point ev)
  9346. (org-open-at-point 'in-emacs))
  9347. (defun org-open-at-mouse (ev)
  9348. "Open file link or URL at mouse.
  9349. See the docstring of `org-open-file' for details."
  9350. (interactive "e")
  9351. (mouse-set-point ev)
  9352. (when (eq major-mode 'org-agenda-mode)
  9353. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9354. (org-open-at-point))
  9355. (defvar org-window-config-before-follow-link nil
  9356. "The window configuration before following a link.
  9357. This is saved in case the need arises to restore it.")
  9358. ;;;###autoload
  9359. (defun org-open-at-point-global ()
  9360. "Follow a link or time-stamp like Org mode does.
  9361. This command can be called in any mode to follow an external link
  9362. or a time-stamp that has Org mode syntax. Its behavior is
  9363. undefined when called on internal links (e.g., fuzzy links).
  9364. Raise an error when there is nothing to follow. "
  9365. (interactive)
  9366. (cond ((org-in-regexp org-any-link-re)
  9367. (org-open-link-from-string (match-string-no-properties 0)))
  9368. ((or (org-in-regexp org-ts-regexp-both nil t)
  9369. (org-in-regexp org-tsr-regexp-both nil t))
  9370. (org-follow-timestamp-link))
  9371. (t (user-error "No link found"))))
  9372. ;;;###autoload
  9373. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9374. "Open a link in the string S, as if it was in Org mode."
  9375. (interactive "sLink: \nP")
  9376. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9377. (with-temp-buffer
  9378. (let ((org-inhibit-startup (not reference-buffer)))
  9379. (org-mode)
  9380. (insert s)
  9381. (goto-char (point-min))
  9382. (when reference-buffer
  9383. (setq org-link-abbrev-alist-local
  9384. (with-current-buffer reference-buffer
  9385. org-link-abbrev-alist-local)))
  9386. (org-open-at-point arg reference-buffer)))))
  9387. (defvar org-open-at-point-functions nil
  9388. "Hook that is run when following a link at point.
  9389. Functions in this hook must return t if they identify and follow
  9390. a link at point. If they don't find anything interesting at point,
  9391. they must return nil.")
  9392. (defvar org-link-search-inhibit-query nil)
  9393. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9394. (defun org--open-doi-link (path)
  9395. "Open a \"doi\" type link.
  9396. PATH is a the path to search for, as a string."
  9397. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9398. (defun org--open-elisp-link (path)
  9399. "Open a \"elisp\" type link.
  9400. PATH is the sexp to evaluate, as a string."
  9401. (let ((cmd path))
  9402. (if (or (and (org-string-nw-p
  9403. org-confirm-elisp-link-not-regexp)
  9404. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9405. (not org-confirm-elisp-link-function)
  9406. (funcall org-confirm-elisp-link-function
  9407. (format "Execute \"%s\" as elisp? "
  9408. (org-add-props cmd nil 'face 'org-warning))))
  9409. (message "%s => %s" cmd
  9410. (if (eq (string-to-char cmd) ?\()
  9411. (eval (read cmd))
  9412. (call-interactively (read cmd))))
  9413. (user-error "Abort"))))
  9414. (defun org--open-help-link (path)
  9415. "Open a \"help\" type link.
  9416. PATH is a symbol name, as a string."
  9417. (pcase (intern path)
  9418. ((and (pred fboundp) variable) (describe-function variable))
  9419. ((and (pred boundp) function) (describe-variable function))
  9420. (name (user-error "Unknown function or variable: %s" name))))
  9421. (defun org--open-shell-link (path)
  9422. "Open a \"shell\" type link.
  9423. PATH is the command to execute, as a string."
  9424. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9425. (cmd path))
  9426. (if (or (and (org-string-nw-p
  9427. org-confirm-shell-link-not-regexp)
  9428. (string-match
  9429. org-confirm-shell-link-not-regexp cmd))
  9430. (not org-confirm-shell-link-function)
  9431. (funcall org-confirm-shell-link-function
  9432. (format "Execute \"%s\" in shell? "
  9433. (org-add-props cmd nil
  9434. 'face 'org-warning))))
  9435. (progn
  9436. (message "Executing %s" cmd)
  9437. (shell-command cmd buf)
  9438. (when (featurep 'midnight)
  9439. (setq clean-buffer-list-kill-buffer-names
  9440. (cons (buffer-name buf)
  9441. clean-buffer-list-kill-buffer-names))))
  9442. (user-error "Abort"))))
  9443. (defun org-open-at-point (&optional arg reference-buffer)
  9444. "Open link, timestamp, footnote or tags at point.
  9445. When point is on a link, follow it. Normally, files will be
  9446. opened by an appropriate application. If the optional prefix
  9447. argument ARG is non-nil, Emacs will visit the file. With
  9448. a double prefix argument, try to open outside of Emacs, in the
  9449. application the system uses for this file type.
  9450. When point is on a timestamp, open the agenda at the day
  9451. specified.
  9452. When point is a footnote definition, move to the first reference
  9453. found. If it is on a reference, move to the associated
  9454. definition.
  9455. When point is on a headline, display a list of every link in the
  9456. entry, so it is possible to pick one, or all, of them. If point
  9457. is on a tag, call `org-tags-view' instead.
  9458. When optional argument REFERENCE-BUFFER is non-nil, it should
  9459. specify a buffer from where the link search should happen. This
  9460. is used internally by `org-open-link-from-string'.
  9461. On top of syntactically correct links, this function will open
  9462. the link at point in comments or comment blocks and the first
  9463. link in a property drawer line."
  9464. (interactive "P")
  9465. ;; On a code block, open block's results.
  9466. (unless (call-interactively 'org-babel-open-src-block-result)
  9467. (org-load-modules-maybe)
  9468. (setq org-window-config-before-follow-link (current-window-configuration))
  9469. (org-remove-occur-highlights nil nil t)
  9470. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9471. (let* ((context
  9472. ;; Only consider supported types, even if they are not
  9473. ;; the closest one.
  9474. (org-element-lineage
  9475. (org-element-context)
  9476. '(clock comment comment-block footnote-definition
  9477. footnote-reference headline inlinetask keyword link
  9478. node-property timestamp)
  9479. t))
  9480. (type (org-element-type context))
  9481. (value (org-element-property :value context)))
  9482. (cond
  9483. ((not context) (user-error "No link found"))
  9484. ;; Exception: open timestamps and links in properties
  9485. ;; drawers, keywords and comments.
  9486. ((memq type '(comment comment-block keyword node-property))
  9487. (call-interactively #'org-open-at-point-global))
  9488. ;; On a headline or an inlinetask, but not on a timestamp,
  9489. ;; a link, a footnote reference or on tags.
  9490. ((and (memq type '(headline inlinetask))
  9491. ;; Not on tags.
  9492. (let ((case-fold-search nil))
  9493. (save-excursion
  9494. (beginning-of-line)
  9495. (looking-at org-complex-heading-regexp))
  9496. (or (not (match-beginning 5))
  9497. (< (point) (match-beginning 5)))))
  9498. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9499. (links (car data))
  9500. (links-end (cdr data)))
  9501. (if links
  9502. (dolist (link (if (stringp links) (list links) links))
  9503. (search-forward link nil links-end)
  9504. (goto-char (match-beginning 0))
  9505. (org-open-at-point))
  9506. (require 'org-attach)
  9507. (org-attach-reveal 'if-exists))))
  9508. ;; On a clock line, make sure point is on the timestamp
  9509. ;; before opening it.
  9510. ((and (eq type 'clock)
  9511. value
  9512. (>= (point) (org-element-property :begin value))
  9513. (<= (point) (org-element-property :end value)))
  9514. (org-follow-timestamp-link))
  9515. ;; Do nothing on white spaces after an object.
  9516. ((>= (point)
  9517. (save-excursion
  9518. (goto-char (org-element-property :end context))
  9519. (skip-chars-backward " \t")
  9520. (point)))
  9521. (user-error "No link found"))
  9522. ((eq type 'timestamp) (org-follow-timestamp-link))
  9523. ;; On tags within a headline or an inlinetask.
  9524. ((and (memq type '(headline inlinetask))
  9525. (let ((case-fold-search nil))
  9526. (save-excursion (beginning-of-line)
  9527. (looking-at org-complex-heading-regexp))
  9528. (and (match-beginning 5)
  9529. (>= (point) (match-beginning 5)))))
  9530. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9531. ((eq type 'link)
  9532. (let ((type (org-element-property :type context))
  9533. (path (org-link-unescape (org-element-property :path context))))
  9534. ;; Switch back to REFERENCE-BUFFER needed when called in
  9535. ;; a temporary buffer through `org-open-link-from-string'.
  9536. (with-current-buffer (or reference-buffer (current-buffer))
  9537. (cond
  9538. ((equal type "file")
  9539. (if (string-match "[*?{]" (file-name-nondirectory path))
  9540. (dired path)
  9541. ;; Look into `org-link-parameters' in order to find
  9542. ;; a DEDICATED-FUNCTION to open file. The function
  9543. ;; will be applied on raw link instead of parsed
  9544. ;; link due to the limitation in `org-add-link-type'
  9545. ;; ("open" function called with a single argument).
  9546. ;; If no such function is found, fallback to
  9547. ;; `org-open-file'.
  9548. (let* ((option (org-element-property :search-option context))
  9549. (app (org-element-property :application context))
  9550. (dedicated-function
  9551. (org-link-get-parameter
  9552. (if app (concat type "+" app) type)
  9553. :follow)))
  9554. (if dedicated-function
  9555. (funcall dedicated-function
  9556. (concat path
  9557. (and option (concat "::" option))))
  9558. (apply #'org-open-file
  9559. path
  9560. (cond (arg)
  9561. ((equal app "emacs") 'emacs)
  9562. ((equal app "sys") 'system))
  9563. (cond ((not option) nil)
  9564. ((string-match-p "\\`[0-9]+\\'" option)
  9565. (list (string-to-number option)))
  9566. (t (list nil
  9567. (org-link-unescape option)))))))))
  9568. ((functionp (org-link-get-parameter type :follow))
  9569. (funcall (org-link-get-parameter type :follow) path))
  9570. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9571. (unless (run-hook-with-args-until-success
  9572. 'org-open-link-functions path)
  9573. (if (not arg) (org-mark-ring-push)
  9574. (switch-to-buffer-other-window
  9575. (org-get-buffer-for-internal-link (current-buffer))))
  9576. (let ((destination
  9577. (org-with-wide-buffer
  9578. (if (equal type "radio")
  9579. (org-search-radio-target
  9580. (org-element-property :path context))
  9581. (org-link-search
  9582. (if (member type '("custom-id" "coderef"))
  9583. (org-element-property :raw-link context)
  9584. path)
  9585. ;; Prevent fuzzy links from matching
  9586. ;; themselves.
  9587. (and (equal type "fuzzy")
  9588. (+ 2 (org-element-property :begin context)))))
  9589. (point))))
  9590. (unless (and (<= (point-min) destination)
  9591. (>= (point-max) destination))
  9592. (widen))
  9593. (goto-char destination))))
  9594. (t (browse-url-at-point))))))
  9595. ;; On a footnote reference or at a footnote definition's label.
  9596. ((or (eq type 'footnote-reference)
  9597. (and (eq type 'footnote-definition)
  9598. (save-excursion
  9599. ;; Do not validate action when point is on the
  9600. ;; spaces right after the footnote label, in
  9601. ;; order to be on par with behaviour on links.
  9602. (skip-chars-forward " \t")
  9603. (let ((begin
  9604. (org-element-property :contents-begin context)))
  9605. (if begin (< (point) begin)
  9606. (= (org-element-property :post-affiliated context)
  9607. (line-beginning-position)))))))
  9608. (org-footnote-action))
  9609. (t (user-error "No link found")))))
  9610. (run-hook-with-args 'org-follow-link-hook)))
  9611. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9612. "Offer links in the current entry and return the selected link.
  9613. If there is only one link, return it.
  9614. If NTH is an integer, return the NTH link found.
  9615. If ZERO is a string, check also this string for a link, and if
  9616. there is one, return it."
  9617. (with-current-buffer buffer
  9618. (org-with-wide-buffer
  9619. (goto-char marker)
  9620. (let ((cnt ?0)
  9621. have-zero end links link c)
  9622. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9623. (push (match-string 0 zero) links)
  9624. (setq cnt (1- cnt) have-zero t))
  9625. (save-excursion
  9626. (org-back-to-heading t)
  9627. (setq end (save-excursion (outline-next-heading) (point)))
  9628. (while (re-search-forward org-any-link-re end t)
  9629. (push (match-string 0) links))
  9630. (setq links (org-uniquify (reverse links))))
  9631. (cond
  9632. ((null links)
  9633. (message "No links"))
  9634. ((equal (length links) 1)
  9635. (setq link (car links)))
  9636. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9637. (setq link (nth (if have-zero nth (1- nth)) links)))
  9638. (t ; we have to select a link
  9639. (save-excursion
  9640. (save-window-excursion
  9641. (delete-other-windows)
  9642. (with-output-to-temp-buffer "*Select Link*"
  9643. (dolist (l links)
  9644. (cond
  9645. ((not (string-match org-bracket-link-regexp l))
  9646. (princ (format "[%c] %s\n" (cl-incf cnt)
  9647. (org-unbracket-string "<" ">" l))))
  9648. ((match-end 3)
  9649. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9650. (match-string 3 l) (match-string 1 l))))
  9651. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9652. (match-string 1 l)))))))
  9653. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9654. (message "Select link to open, RET to open all:")
  9655. (setq c (read-char-exclusive))
  9656. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9657. (when (equal c ?q) (user-error "Abort"))
  9658. (if (equal c ?\C-m)
  9659. (setq link links)
  9660. (setq nth (- c ?0))
  9661. (when have-zero (setq nth (1+ nth)))
  9662. (unless (and (integerp nth) (>= (length links) nth))
  9663. (user-error "Invalid link selection"))
  9664. (setq link (nth (1- nth) links)))))
  9665. (cons link end)))))
  9666. ;; TODO: These functions are deprecated since `org-open-at-point'
  9667. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9668. (defun org-open-file-with-system (path)
  9669. "Open file at PATH using the system way of opening it."
  9670. (org-open-file path 'system))
  9671. (defun org-open-file-with-emacs (path)
  9672. "Open file at PATH in Emacs."
  9673. (org-open-file path 'emacs))
  9674. ;;; File search
  9675. (defvar org-create-file-search-functions nil
  9676. "List of functions to construct the right search string for a file link.
  9677. These functions are called in turn with point at the location to
  9678. which the link should point.
  9679. A function in the hook should first test if it would like to
  9680. handle this file type, for example by checking the `major-mode'
  9681. or the file extension. If it decides not to handle this file, it
  9682. should just return nil to give other functions a chance. If it
  9683. does handle the file, it must return the search string to be used
  9684. when following the link. The search string will be part of the
  9685. file link, given after a double colon, and `org-open-at-point'
  9686. will automatically search for it. If special measures must be
  9687. taken to make the search successful, another function should be
  9688. added to the companion hook `org-execute-file-search-functions',
  9689. which see.
  9690. A function in this hook may also use `setq' to set the variable
  9691. `description' to provide a suggestion for the descriptive text to
  9692. be used for this link when it gets inserted into an Org buffer
  9693. with \\[org-insert-link].")
  9694. (defvar org-execute-file-search-functions nil
  9695. "List of functions to execute a file search triggered by a link.
  9696. Functions added to this hook must accept a single argument, the
  9697. search string that was part of the file link, the part after the
  9698. double colon. The function must first check if it would like to
  9699. handle this search, for example by checking the `major-mode' or
  9700. the file extension. If it decides not to handle this search, it
  9701. should just return nil to give other functions a chance. If it
  9702. does handle the search, it must return a non-nil value to keep
  9703. other functions from trying.
  9704. Each function can access the current prefix argument through the
  9705. variable `current-prefix-arg'. Note that a single prefix is used
  9706. to force opening a link in Emacs, so it may be good to only use a
  9707. numeric or double prefix to guide the search function.
  9708. In case this is needed, a function in this hook can also restore
  9709. the window configuration before `org-open-at-point' was called using:
  9710. (set-window-configuration org-window-config-before-follow-link)")
  9711. (defun org-search-radio-target (target)
  9712. "Search a radio target matching TARGET in current buffer.
  9713. White spaces are not significant."
  9714. (let ((re (format "<<<%s>>>"
  9715. (mapconcat #'regexp-quote
  9716. (org-split-string target "[ \t\n]+")
  9717. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9718. (origin (point)))
  9719. (goto-char (point-min))
  9720. (catch :radio-match
  9721. (while (re-search-forward re nil t)
  9722. (backward-char)
  9723. (let ((object (org-element-context)))
  9724. (when (eq (org-element-type object) 'radio-target)
  9725. (goto-char (org-element-property :begin object))
  9726. (org-show-context 'link-search)
  9727. (throw :radio-match nil))))
  9728. (goto-char origin)
  9729. (user-error "No match for radio target: %s" target))))
  9730. (defun org-link-search (s &optional avoid-pos stealth)
  9731. "Search for a search string S.
  9732. If S starts with \"#\", it triggers a custom ID search.
  9733. If S is enclosed within parenthesis, it initiates a coderef
  9734. search.
  9735. If S is surrounded by forward slashes, it is interpreted as
  9736. a regular expression. In Org mode files, this will create an
  9737. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9738. to list matches. If the current buffer is in `dired-mode', grep
  9739. will be used to search in all files.
  9740. When AVOID-POS is given, ignore matches near that position.
  9741. When optional argument STEALTH is non-nil, do not modify
  9742. visibility around point, thus ignoring `org-show-context-detail'
  9743. variable.
  9744. Search is case-insensitive and ignores white spaces. Return type
  9745. of matched result, which is either `dedicated' or `fuzzy'."
  9746. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9747. (let* ((case-fold-search t)
  9748. (origin (point))
  9749. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9750. (starred (eq (string-to-char normalized) ?*))
  9751. (words (split-string (if starred (substring s 1) s)))
  9752. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9753. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9754. type)
  9755. (cond
  9756. ;; Check if there are any special search functions.
  9757. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9758. ((eq (string-to-char s) ?#)
  9759. ;; Look for a custom ID S if S starts with "#".
  9760. (let* ((id (substring normalized 1))
  9761. (match (org-find-property "CUSTOM_ID" id)))
  9762. (if match (progn (goto-char match) (setf type 'dedicated))
  9763. (error "No match for custom ID: %s" id))))
  9764. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9765. ;; Look for coderef targets if S is enclosed within parenthesis.
  9766. (let ((coderef (match-string-no-properties 1 normalized))
  9767. (re (substring s-single-re 1 -1)))
  9768. (goto-char (point-min))
  9769. (catch :coderef-match
  9770. (while (re-search-forward re nil t)
  9771. (let ((element (org-element-at-point)))
  9772. (when (and (memq (org-element-type element)
  9773. '(example-block src-block))
  9774. ;; Build proper regexp according to current
  9775. ;; block's label format.
  9776. (let ((label-fmt
  9777. (regexp-quote
  9778. (or (org-element-property :label-fmt element)
  9779. org-coderef-label-format))))
  9780. (save-excursion
  9781. (beginning-of-line)
  9782. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9783. (format label-fmt coderef))))))
  9784. (setq type 'dedicated)
  9785. (goto-char (match-beginning 1))
  9786. (throw :coderef-match nil))))
  9787. (goto-char origin)
  9788. (error "No match for coderef: %s" coderef))))
  9789. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9790. ;; Look for a regular expression.
  9791. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9792. (match-string 1 s)))
  9793. ;; From here, we handle fuzzy links.
  9794. ;;
  9795. ;; Look for targets, only if not in a headline search.
  9796. ((and (not starred)
  9797. (let ((target (format "<<%s>>" s-multi-re)))
  9798. (catch :target-match
  9799. (goto-char (point-min))
  9800. (while (re-search-forward target nil t)
  9801. (backward-char)
  9802. (let ((context (org-element-context)))
  9803. (when (eq (org-element-type context) 'target)
  9804. (setq type 'dedicated)
  9805. (goto-char (org-element-property :begin context))
  9806. (throw :target-match t))))
  9807. nil))))
  9808. ;; Look for elements named after S, only if not in a headline
  9809. ;; search.
  9810. ((and (not starred)
  9811. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9812. (catch :name-match
  9813. (goto-char (point-min))
  9814. (while (re-search-forward name nil t)
  9815. (let ((element (org-element-at-point)))
  9816. (when (equal words
  9817. (split-string
  9818. (org-element-property :name element)))
  9819. (setq type 'dedicated)
  9820. (beginning-of-line)
  9821. (throw :name-match t))))
  9822. nil))))
  9823. ;; Regular text search. Prefer headlines in Org mode buffers.
  9824. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9825. ;; statistics cookies and tags.
  9826. ((and (derived-mode-p 'org-mode)
  9827. (let ((title-re
  9828. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9829. org-outline-regexp-bol
  9830. org-comment-string
  9831. (mapconcat #'regexp-quote words ".+")))
  9832. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9833. (comment-re (eval-when-compile
  9834. (format "\\`%s[ \t]+" org-comment-string))))
  9835. (goto-char (point-min))
  9836. (catch :found
  9837. (while (re-search-forward title-re nil t)
  9838. (when (equal words
  9839. (split-string
  9840. (replace-regexp-in-string
  9841. cookie-re ""
  9842. (replace-regexp-in-string
  9843. comment-re "" (org-get-heading t t t)))))
  9844. (throw :found t)))
  9845. nil)))
  9846. (beginning-of-line)
  9847. (setq type 'dedicated))
  9848. ;; Offer to create non-existent headline depending on
  9849. ;; `org-link-search-must-match-exact-headline'.
  9850. ((and (derived-mode-p 'org-mode)
  9851. (not org-link-search-inhibit-query)
  9852. (eq org-link-search-must-match-exact-headline 'query-to-create)
  9853. (yes-or-no-p "No match - create this as a new heading? "))
  9854. (goto-char (point-max))
  9855. (unless (bolp) (newline))
  9856. (org-insert-heading nil t t)
  9857. (insert s "\n")
  9858. (beginning-of-line 0))
  9859. ;; Only headlines are looked after. No need to process
  9860. ;; further: throw an error.
  9861. ((and (derived-mode-p 'org-mode)
  9862. (or starred org-link-search-must-match-exact-headline))
  9863. (goto-char origin)
  9864. (error "No match for fuzzy expression: %s" normalized))
  9865. ;; Regular text search.
  9866. ((catch :fuzzy-match
  9867. (goto-char (point-min))
  9868. (while (re-search-forward s-multi-re nil t)
  9869. ;; Skip match if it contains AVOID-POS or it is included in
  9870. ;; a link with a description but outside the description.
  9871. (unless (or (and avoid-pos
  9872. (<= (match-beginning 0) avoid-pos)
  9873. (> (match-end 0) avoid-pos))
  9874. (and (save-match-data
  9875. (org-in-regexp org-bracket-link-regexp))
  9876. (match-beginning 3)
  9877. (or (> (match-beginning 3) (point))
  9878. (<= (match-end 3) (point)))
  9879. (org-element-lineage
  9880. (save-match-data (org-element-context))
  9881. '(link) t)))
  9882. (goto-char (match-beginning 0))
  9883. (setq type 'fuzzy)
  9884. (throw :fuzzy-match t)))
  9885. nil))
  9886. ;; All failed. Throw an error.
  9887. (t (goto-char origin)
  9888. (error "No match for fuzzy expression: %s" normalized)))
  9889. ;; Disclose surroundings of match, if appropriate.
  9890. (when (and (derived-mode-p 'org-mode) (not stealth))
  9891. (org-show-context 'link-search))
  9892. type))
  9893. (defun org-get-buffer-for-internal-link (buffer)
  9894. "Return a buffer to be used for displaying the link target of internal links."
  9895. (cond
  9896. ((not org-display-internal-link-with-indirect-buffer)
  9897. buffer)
  9898. ((string-suffix-p "(Clone)" (buffer-name buffer))
  9899. (message "Buffer is already a clone, not making another one")
  9900. ;; we also do not modify visibility in this case
  9901. buffer)
  9902. (t ; make a new indirect buffer for displaying the link
  9903. (let* ((bn (buffer-name buffer))
  9904. (ibn (concat bn "(Clone)"))
  9905. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  9906. (with-current-buffer ib (org-overview))
  9907. ib))))
  9908. (defun org-do-occur (regexp &optional cleanup)
  9909. "Call the Emacs command `occur'.
  9910. If CLEANUP is non-nil, remove the printout of the regular expression
  9911. in the *Occur* buffer. This is useful if the regex is long and not useful
  9912. to read."
  9913. (occur regexp)
  9914. (when cleanup
  9915. (let ((cwin (selected-window)) win beg end)
  9916. (when (setq win (get-buffer-window "*Occur*"))
  9917. (select-window win))
  9918. (goto-char (point-min))
  9919. (when (re-search-forward "match[a-z]+" nil t)
  9920. (setq beg (match-end 0))
  9921. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  9922. (setq end (1- (match-beginning 0)))))
  9923. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  9924. (goto-char (point-min))
  9925. (select-window cwin))))
  9926. ;;; The mark ring for links jumps
  9927. (defvar org-mark-ring nil
  9928. "Mark ring for positions before jumps in Org mode.")
  9929. (defvar org-mark-ring-last-goto nil
  9930. "Last position in the mark ring used to go back.")
  9931. ;; Fill and close the ring
  9932. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  9933. (dotimes (_ org-mark-ring-length)
  9934. (push (make-marker) org-mark-ring))
  9935. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  9936. org-mark-ring)
  9937. (defun org-mark-ring-push (&optional pos buffer)
  9938. "Put the current position or POS into the mark ring and rotate it."
  9939. (interactive)
  9940. (setq pos (or pos (point)))
  9941. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  9942. (move-marker (car org-mark-ring)
  9943. (or pos (point))
  9944. (or buffer (current-buffer)))
  9945. (message "%s"
  9946. (substitute-command-keys
  9947. "Position saved to mark ring, go back with \
  9948. `\\[org-mark-ring-goto]'.")))
  9949. (defun org-mark-ring-goto (&optional n)
  9950. "Jump to the previous position in the mark ring.
  9951. With prefix arg N, jump back that many stored positions. When
  9952. called several times in succession, walk through the entire ring.
  9953. Org mode commands jumping to a different position in the current file,
  9954. or to another Org file, automatically push the old position onto the ring."
  9955. (interactive "p")
  9956. (let (p m)
  9957. (if (eq last-command this-command)
  9958. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  9959. (setq p org-mark-ring))
  9960. (setq org-mark-ring-last-goto p)
  9961. (setq m (car p))
  9962. (pop-to-buffer-same-window (marker-buffer m))
  9963. (goto-char m)
  9964. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  9965. (defun org-add-angle-brackets (s)
  9966. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  9967. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  9968. s)
  9969. ;;; Following specific links
  9970. (defvar org-agenda-buffer-tmp-name)
  9971. (defvar org-agenda-start-on-weekday)
  9972. (defun org-follow-timestamp-link ()
  9973. "Open an agenda view for the time-stamp date/range at point."
  9974. (cond
  9975. ((org-at-date-range-p t)
  9976. (let ((org-agenda-start-on-weekday)
  9977. (t1 (match-string 1))
  9978. (t2 (match-string 2)) tt1 tt2)
  9979. (setq tt1 (time-to-days (org-time-string-to-time t1))
  9980. tt2 (time-to-days (org-time-string-to-time t2)))
  9981. (let ((org-agenda-buffer-tmp-name
  9982. (format "*Org Agenda(a:%s)"
  9983. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  9984. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  9985. ((org-at-timestamp-p 'lax)
  9986. (let ((org-agenda-buffer-tmp-name
  9987. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  9988. (org-agenda-list nil (time-to-days (org-time-string-to-time
  9989. (substring (match-string 1) 0 10)))
  9990. 1)))
  9991. (t (error "This should not happen"))))
  9992. ;;; Following file links
  9993. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  9994. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  9995. (declare-function mailcap-mime-info
  9996. "mailcap" (string &optional request no-decode))
  9997. (defvar org-wait nil)
  9998. (defun org-open-file (path &optional in-emacs line search)
  9999. "Open the file at PATH.
  10000. First, this expands any special file name abbreviations. Then the
  10001. configuration variable `org-file-apps' is checked if it contains an
  10002. entry for this file type, and if yes, the corresponding command is launched.
  10003. If no application is found, Emacs simply visits the file.
  10004. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10005. With a double \\[universal-argument] \\[universal-argument] \
  10006. prefix arg, Org tries to avoid opening in Emacs
  10007. and to use an external application to visit the file.
  10008. Optional LINE specifies a line to go to, optional SEARCH a string
  10009. to search for. If LINE or SEARCH is given, the file will be
  10010. opened in Emacs, unless an entry from org-file-apps that makes
  10011. use of groups in a regexp matches.
  10012. If you want to change the way frames are used when following a
  10013. link, please customize `org-link-frame-setup'.
  10014. If the file does not exist, an error is thrown."
  10015. (let* ((file (if (equal path "")
  10016. buffer-file-name
  10017. (substitute-in-file-name (expand-file-name path))))
  10018. (file-apps (append org-file-apps (org-default-apps)))
  10019. (apps (cl-remove-if
  10020. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10021. (apps-dlink (cl-remove-if-not
  10022. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10023. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10024. (dirp (unless remp (file-directory-p file)))
  10025. (file (if (and dirp org-open-directory-means-index-dot-org)
  10026. (concat (file-name-as-directory file) "index.org")
  10027. file))
  10028. (a-m-a-p (assq 'auto-mode apps))
  10029. (dfile (downcase file))
  10030. ;; Reconstruct the original link from the PATH, LINE and
  10031. ;; SEARCH args.
  10032. (link (cond (line (concat file "::" (number-to-string line)))
  10033. (search (concat file "::" search))
  10034. (t file)))
  10035. (dlink (downcase link))
  10036. (ext
  10037. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10038. (match-string 1 dfile)))
  10039. (save-position-maybe
  10040. (let ((old-buffer (current-buffer))
  10041. (old-pos (point))
  10042. (old-mode major-mode))
  10043. (lambda ()
  10044. (and (derived-mode-p 'org-mode)
  10045. (eq old-mode 'org-mode)
  10046. (or (not (eq old-buffer (current-buffer)))
  10047. (not (eq old-pos (point))))
  10048. (org-mark-ring-push old-pos old-buffer)))))
  10049. cmd link-match-data)
  10050. (cond
  10051. ((member in-emacs '((16) system))
  10052. (setq cmd (cdr (assq 'system apps))))
  10053. (in-emacs (setq cmd 'emacs))
  10054. (t
  10055. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10056. (and dirp (cdr (assq 'directory apps)))
  10057. ;; First, try matching against apps-dlink if we
  10058. ;; get a match here, store the match data for
  10059. ;; later.
  10060. (let ((match (assoc-default dlink apps-dlink
  10061. 'string-match)))
  10062. (if match
  10063. (progn (setq link-match-data (match-data))
  10064. match)
  10065. (progn (setq in-emacs (or in-emacs line search))
  10066. nil))) ; if we have no match in apps-dlink,
  10067. ; always open the file in emacs if line or search
  10068. ; is given (for backwards compatibility)
  10069. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10070. 'string-match)
  10071. (cdr (assoc ext apps))
  10072. (cdr (assq t apps))))))
  10073. (when (eq cmd 'system)
  10074. (setq cmd (cdr (assq 'system apps))))
  10075. (when (eq cmd 'default)
  10076. (setq cmd (cdr (assoc t apps))))
  10077. (when (eq cmd 'mailcap)
  10078. (require 'mailcap)
  10079. (mailcap-parse-mailcaps)
  10080. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10081. (command (mailcap-mime-info mime-type)))
  10082. (if (stringp command)
  10083. (setq cmd command)
  10084. (setq cmd 'emacs))))
  10085. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10086. (not (file-exists-p file))
  10087. (not org-open-non-existing-files))
  10088. (user-error "No such file: %s" file))
  10089. (cond
  10090. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10091. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10092. (while (string-match "['\"]%s['\"]" cmd)
  10093. (setq cmd (replace-match "%s" t t cmd)))
  10094. (setq cmd (replace-regexp-in-string
  10095. "%s"
  10096. (shell-quote-argument (convert-standard-filename file))
  10097. cmd
  10098. nil t))
  10099. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10100. (save-match-data
  10101. (let ((match-index 1)
  10102. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10103. (set-match-data link-match-data)
  10104. (while (<= match-index number-of-groups)
  10105. (let ((regex (concat "%" (number-to-string match-index)))
  10106. (replace-with (match-string match-index dlink)))
  10107. (while (string-match regex cmd)
  10108. (setq cmd (replace-match replace-with t t cmd))))
  10109. (setq match-index (+ match-index 1)))))
  10110. (save-window-excursion
  10111. (message "Running %s...done" cmd)
  10112. (start-process-shell-command cmd nil cmd)
  10113. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10114. ((or (stringp cmd)
  10115. (eq cmd 'emacs))
  10116. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10117. (widen)
  10118. (cond (line (org-goto-line line)
  10119. (when (derived-mode-p 'org-mode) (org-reveal)))
  10120. (search (condition-case err
  10121. (org-link-search search)
  10122. ;; Save position before error-ing out so user
  10123. ;; can easily move back to the original buffer.
  10124. (error (funcall save-position-maybe)
  10125. (error (nth 1 err)))))))
  10126. ((functionp cmd)
  10127. (save-match-data
  10128. (set-match-data link-match-data)
  10129. (condition-case nil
  10130. (funcall cmd file link)
  10131. ;; FIXME: Remove this check when most default installations
  10132. ;; of Emacs have at least Org 9.0.
  10133. ((debug wrong-number-of-arguments wrong-type-argument
  10134. invalid-function)
  10135. (user-error "Please see Org News for version 9.0 about \
  10136. `org-file-apps'--Lisp error: %S" cmd)))))
  10137. ((consp cmd)
  10138. ;; FIXME: Remove this check when most default installations of
  10139. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  10140. ;; fall back to `org-link-frame-setup' for an old usage of
  10141. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  10142. (user-error "Please see Org News for version 9.0 about \
  10143. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10144. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10145. (funcall save-position-maybe)))
  10146. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10147. "This function returns non-nil if `entry' uses a regular
  10148. expression which should be matched against the whole link by
  10149. org-open-file.
  10150. It assumes that is the case when the entry uses a regular
  10151. expression which has at least one grouping construct and the
  10152. action is either a lisp form or a command string containing
  10153. `%1', i.e. using at least one subexpression match as a
  10154. parameter."
  10155. (let ((selector (car entry))
  10156. (action (cdr entry)))
  10157. (if (stringp selector)
  10158. (and (> (regexp-opt-depth selector) 0)
  10159. (or (and (stringp action)
  10160. (string-match "%[0-9]" action))
  10161. (consp action)))
  10162. nil)))
  10163. (defun org-default-apps ()
  10164. "Return the default applications for this operating system."
  10165. (cond
  10166. ((eq system-type 'darwin)
  10167. org-file-apps-defaults-macosx)
  10168. ((eq system-type 'windows-nt)
  10169. org-file-apps-defaults-windowsnt)
  10170. (t org-file-apps-defaults-gnu)))
  10171. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10172. "Convert extensions to regular expressions in the cars of LIST.
  10173. Also, weed out any non-string entries, because the return value is used
  10174. only for regexp matching.
  10175. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10176. point to the symbol `emacs', indicating that the file should
  10177. be opened in Emacs."
  10178. (append
  10179. (delq nil
  10180. (mapcar (lambda (x)
  10181. (unless (not (stringp (car x)))
  10182. (if (string-match "\\W" (car x))
  10183. x
  10184. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10185. list))
  10186. (when add-auto-mode
  10187. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10188. (defvar ange-ftp-name-format)
  10189. (defun org-file-remote-p (file)
  10190. "Test whether FILE specifies a location on a remote system.
  10191. Return non-nil if the location is indeed remote.
  10192. For example, the filename \"/user@host:/foo\" specifies a location
  10193. on the system \"/user@host:\"."
  10194. (cond ((fboundp 'file-remote-p)
  10195. (file-remote-p file))
  10196. ((fboundp 'tramp-handle-file-remote-p)
  10197. (tramp-handle-file-remote-p file))
  10198. ((and (boundp 'ange-ftp-name-format)
  10199. (string-match (car ange-ftp-name-format) file))
  10200. t)))
  10201. ;;;; Refiling
  10202. (defun org-get-org-file ()
  10203. "Read a filename, with default directory `org-directory'."
  10204. (let ((default (or org-default-notes-file remember-data-file)))
  10205. (read-file-name (format "File name [%s]: " default)
  10206. (file-name-as-directory org-directory)
  10207. default)))
  10208. (defun org-notes-order-reversed-p ()
  10209. "Check if the current file should receive notes in reversed order."
  10210. (cond
  10211. ((not org-reverse-note-order) nil)
  10212. ((eq t org-reverse-note-order) t)
  10213. ((not (listp org-reverse-note-order)) nil)
  10214. (t (catch 'exit
  10215. (dolist (entry org-reverse-note-order)
  10216. (when (string-match (car entry) buffer-file-name)
  10217. (throw 'exit (cdr entry))))))))
  10218. (defvar org-refile-target-table nil
  10219. "The list of refile targets, created by `org-refile'.")
  10220. (defvar org-agenda-new-buffers nil
  10221. "Buffers created to visit agenda files.")
  10222. (defvar org-refile-cache nil
  10223. "Cache for refile targets.")
  10224. (defvar org-refile-markers nil
  10225. "All the markers used for caching refile locations.")
  10226. (defun org-refile-marker (pos)
  10227. "Get a new refile marker, but only if caching is in use."
  10228. (if (not org-refile-use-cache)
  10229. pos
  10230. (let ((m (make-marker)))
  10231. (move-marker m pos)
  10232. (push m org-refile-markers)
  10233. m)))
  10234. (defun org-refile-cache-clear ()
  10235. "Clear the refile cache and disable all the markers."
  10236. (dolist (m org-refile-markers) (move-marker m nil))
  10237. (setq org-refile-markers nil)
  10238. (setq org-refile-cache nil)
  10239. (message "Refile cache has been cleared"))
  10240. (defun org-refile-cache-check-set (set)
  10241. "Check if all the markers in the cache still have live buffers."
  10242. (let (marker)
  10243. (catch 'exit
  10244. (while (and set (setq marker (nth 3 (pop set))))
  10245. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10246. (when (and marker (null (marker-buffer marker)))
  10247. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10248. (sit-for 3)
  10249. (throw 'exit nil)))
  10250. t)))
  10251. (defun org-refile-cache-put (set &rest identifiers)
  10252. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10253. (let* ((key (sha1 (prin1-to-string identifiers)))
  10254. (entry (assoc key org-refile-cache)))
  10255. (if entry
  10256. (setcdr entry set)
  10257. (push (cons key set) org-refile-cache))))
  10258. (defun org-refile-cache-get (&rest identifiers)
  10259. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10260. (cond
  10261. ((not org-refile-cache) nil)
  10262. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10263. (t
  10264. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10265. org-refile-cache))))
  10266. (and set (org-refile-cache-check-set set) set)))))
  10267. (defvar org-outline-path-cache nil
  10268. "Alist between buffer positions and outline paths.
  10269. It value is an alist (POSITION . PATH) where POSITION is the
  10270. buffer position at the beginning of an entry and PATH is a list
  10271. of strings describing the outline path for that entry, in reverse
  10272. order.")
  10273. (defun org-refile-get-targets (&optional default-buffer)
  10274. "Produce a table with refile targets."
  10275. (let ((case-fold-search nil)
  10276. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10277. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10278. targets tgs files desc descre)
  10279. (message "Getting targets...")
  10280. (with-current-buffer (or default-buffer (current-buffer))
  10281. (dolist (entry entries)
  10282. (setq files (car entry) desc (cdr entry))
  10283. (cond
  10284. ((null files) (setq files (list (current-buffer))))
  10285. ((eq files 'org-agenda-files)
  10286. (setq files (org-agenda-files 'unrestricted)))
  10287. ((and (symbolp files) (fboundp files))
  10288. (setq files (funcall files)))
  10289. ((and (symbolp files) (boundp files))
  10290. (setq files (symbol-value files))))
  10291. (when (stringp files) (setq files (list files)))
  10292. (cond
  10293. ((eq (car desc) :tag)
  10294. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10295. ((eq (car desc) :todo)
  10296. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10297. ((eq (car desc) :regexp)
  10298. (setq descre (cdr desc)))
  10299. ((eq (car desc) :level)
  10300. (setq descre (concat "^\\*\\{" (number-to-string
  10301. (if org-odd-levels-only
  10302. (1- (* 2 (cdr desc)))
  10303. (cdr desc)))
  10304. "\\}[ \t]")))
  10305. ((eq (car desc) :maxlevel)
  10306. (setq descre (concat "^\\*\\{1," (number-to-string
  10307. (if org-odd-levels-only
  10308. (1- (* 2 (cdr desc)))
  10309. (cdr desc)))
  10310. "\\}[ \t]")))
  10311. (t (error "Bad refiling target description %s" desc)))
  10312. (dolist (f files)
  10313. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10314. (or
  10315. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10316. (progn
  10317. (when (bufferp f)
  10318. (setq f (buffer-file-name (buffer-base-buffer f))))
  10319. (setq f (and f (expand-file-name f)))
  10320. (when (eq org-refile-use-outline-path 'file)
  10321. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10322. (when (eq org-refile-use-outline-path 'buffer-name)
  10323. (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
  10324. (when (eq org-refile-use-outline-path 'full-file-path)
  10325. (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
  10326. (org-with-wide-buffer
  10327. (goto-char (point-min))
  10328. (setq org-outline-path-cache nil)
  10329. (while (re-search-forward descre nil t)
  10330. (beginning-of-line)
  10331. (let ((case-fold-search nil))
  10332. (looking-at org-complex-heading-regexp))
  10333. (let ((begin (point))
  10334. (heading (match-string-no-properties 4)))
  10335. (unless (or (and
  10336. org-refile-target-verify-function
  10337. (not
  10338. (funcall org-refile-target-verify-function)))
  10339. (not heading))
  10340. (let ((re (format org-complex-heading-regexp-format
  10341. (regexp-quote heading)))
  10342. (target
  10343. (if (not org-refile-use-outline-path) heading
  10344. (mapconcat
  10345. #'identity
  10346. (append
  10347. (pcase org-refile-use-outline-path
  10348. (`file (list (file-name-nondirectory
  10349. (buffer-file-name
  10350. (buffer-base-buffer)))))
  10351. (`full-file-path
  10352. (list (buffer-file-name
  10353. (buffer-base-buffer))))
  10354. (`buffer-name
  10355. (list (buffer-name
  10356. (buffer-base-buffer))))
  10357. (_ nil))
  10358. (mapcar (lambda (s) (replace-regexp-in-string
  10359. "/" "\\/" s nil t))
  10360. (org-get-outline-path t t)))
  10361. "/"))))
  10362. (push (list target f re (org-refile-marker (point)))
  10363. tgs)))
  10364. (when (= (point) begin)
  10365. ;; Verification function has not moved point.
  10366. (end-of-line)))))))
  10367. (when org-refile-use-cache
  10368. (org-refile-cache-put tgs (buffer-file-name) descre))
  10369. (setq targets (append tgs targets))))))
  10370. (message "Getting targets...done")
  10371. (delete-dups (nreverse targets))))
  10372. (defun org--get-outline-path-1 (&optional use-cache)
  10373. "Return outline path to current headline.
  10374. Outline path is a list of strings, in reverse order. When
  10375. optional argument USE-CACHE is non-nil, make use of a cache. See
  10376. `org-get-outline-path' for details.
  10377. Assume buffer is widened and point is on a headline."
  10378. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10379. (let ((p (point))
  10380. (heading (let ((case-fold-search nil))
  10381. (looking-at org-complex-heading-regexp)
  10382. (if (not (match-end 4)) ""
  10383. ;; Remove statistics cookies.
  10384. (org-trim
  10385. (org-link-display-format
  10386. (replace-regexp-in-string
  10387. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10388. (match-string-no-properties 4))))))))
  10389. (if (org-up-heading-safe)
  10390. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10391. (when use-cache
  10392. (push (cons p path) org-outline-path-cache))
  10393. path)
  10394. ;; This is a new root node. Since we assume we are moving
  10395. ;; forward, we can drop previous cache so as to limit number
  10396. ;; of associations there.
  10397. (let ((path (list heading)))
  10398. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10399. path)))))
  10400. (defun org-get-outline-path (&optional with-self use-cache)
  10401. "Return the outline path to the current entry.
  10402. An outline path is a list of ancestors for current headline, as
  10403. a list of strings. Statistics cookies are removed and links are
  10404. replaced with their description, if any, or their path otherwise.
  10405. When optional argument WITH-SELF is non-nil, the path also
  10406. includes the current headline.
  10407. When optional argument USE-CACHE is non-nil, cache outline paths
  10408. between calls to this function so as to avoid backtracking. This
  10409. argument is useful when planning to find more than one outline
  10410. path in the same document. In that case, there are two
  10411. conditions to satisfy:
  10412. - `org-outline-path-cache' is set to nil before starting the
  10413. process;
  10414. - outline paths are computed by increasing buffer positions."
  10415. (org-with-wide-buffer
  10416. (and (or (and with-self (org-back-to-heading t))
  10417. (org-up-heading-safe))
  10418. (reverse (org--get-outline-path-1 use-cache)))))
  10419. (defun org-format-outline-path (path &optional width prefix separator)
  10420. "Format the outline path PATH for display.
  10421. WIDTH is the maximum number of characters that is available.
  10422. PREFIX is a prefix to be included in the returned string,
  10423. such as the file name.
  10424. SEPARATOR is inserted between the different parts of the path,
  10425. the default is \"/\"."
  10426. (setq width (or width 79))
  10427. (setq path (delq nil path))
  10428. (unless (> width 0)
  10429. (user-error "Argument `width' must be positive"))
  10430. (setq separator (or separator "/"))
  10431. (let* ((org-odd-levels-only nil)
  10432. (fpath (concat
  10433. prefix (and prefix path separator)
  10434. (mapconcat
  10435. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10436. (cl-loop for head in path
  10437. for n from 0
  10438. collect (org-add-props
  10439. head nil 'face
  10440. (nth (% n org-n-level-faces) org-level-faces)))
  10441. separator))))
  10442. (when (> (length fpath) width)
  10443. (if (< width 7)
  10444. ;; It's unlikely that `width' will be this small, but don't
  10445. ;; waste characters by adding ".." if it is.
  10446. (setq fpath (substring fpath 0 width))
  10447. (setf (substring fpath (- width 2)) "..")))
  10448. fpath))
  10449. (defun org-display-outline-path (&optional file current separator just-return-string)
  10450. "Display the current outline path in the echo area.
  10451. If FILE is non-nil, prepend the output with the file name.
  10452. If CURRENT is non-nil, append the current heading to the output.
  10453. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10454. the different parts of the path and defaults to \"/\".
  10455. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10456. (interactive "P")
  10457. (let* (case-fold-search
  10458. (bfn (buffer-file-name (buffer-base-buffer)))
  10459. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10460. res)
  10461. (when current (setq path (append path
  10462. (save-excursion
  10463. (org-back-to-heading t)
  10464. (when (looking-at org-complex-heading-regexp)
  10465. (list (match-string 4)))))))
  10466. (setq res
  10467. (org-format-outline-path
  10468. path
  10469. (1- (frame-width))
  10470. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10471. separator))
  10472. (if just-return-string
  10473. (org-no-properties res)
  10474. (org-unlogged-message "%s" res))))
  10475. (defvar org-refile-history nil
  10476. "History for refiling operations.")
  10477. (defvar org-after-refile-insert-hook nil
  10478. "Hook run after `org-refile' has inserted its stuff at the new location.
  10479. Note that this is still *before* the stuff will be removed from
  10480. the *old* location.")
  10481. (defvar org-capture-last-stored-marker)
  10482. (defvar org-refile-keep nil
  10483. "Non-nil means `org-refile' will copy instead of refile.")
  10484. (defun org-copy ()
  10485. "Like `org-refile', but copy."
  10486. (interactive)
  10487. (let ((org-refile-keep t))
  10488. (funcall 'org-refile nil nil nil "Copy")))
  10489. (defun org-refile (&optional arg default-buffer rfloc msg)
  10490. "Move the entry or entries at point to another heading.
  10491. The list of target headings is compiled using the information in
  10492. `org-refile-targets', which see.
  10493. At the target location, the entry is filed as a subitem of the
  10494. target heading. Depending on `org-reverse-note-order', the new
  10495. subitem will either be the first or the last subitem.
  10496. If there is an active region, all entries in that region will be
  10497. refiled. However, the region must fulfill the requirement that
  10498. the first heading sets the top-level of the moved text.
  10499. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10500. location
  10501. and not actually move anything.
  10502. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10503. location where the last
  10504. refiling operation has put the subtree.
  10505. With a numeric prefix argument of `2', refile to the running clock.
  10506. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10507. being set to t and copy to the target location, don't move it.
  10508. Beware that keeping refiled entries may result in duplicated ID
  10509. properties.
  10510. RFLOC can be a refile location obtained in a different way.
  10511. MSG is a string to replace \"Refile\" in the default prompt with
  10512. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10513. See also `org-refile-use-outline-path'.
  10514. If you are using target caching (see `org-refile-use-cache'), you
  10515. have to clear the target cache in order to find new targets.
  10516. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10517. prefix argument (`C-u C-u C-u C-c C-w')."
  10518. (interactive "P")
  10519. (if (member arg '(0 (64)))
  10520. (org-refile-cache-clear)
  10521. (let* ((actionmsg (cond (msg msg)
  10522. ((equal arg 3) "Refile (and keep)")
  10523. (t "Refile")))
  10524. (regionp (org-region-active-p))
  10525. (region-start (and regionp (region-beginning)))
  10526. (region-end (and regionp (region-end)))
  10527. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10528. pos it nbuf file level reversed)
  10529. (setq last-command nil)
  10530. (when regionp
  10531. (goto-char region-start)
  10532. (or (bolp) (goto-char (point-at-bol)))
  10533. (setq region-start (point))
  10534. (unless (or (org-kill-is-subtree-p
  10535. (buffer-substring region-start region-end))
  10536. (prog1 org-refile-active-region-within-subtree
  10537. (let ((s (point-at-eol)))
  10538. (org-toggle-heading)
  10539. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10540. (user-error "The region is not a (sequence of) subtree(s)")))
  10541. (if (equal arg '(16))
  10542. (org-refile-goto-last-stored)
  10543. (when (or
  10544. (and (equal arg 2)
  10545. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10546. (prog1
  10547. (setq it (list (or org-clock-heading "running clock")
  10548. (buffer-file-name
  10549. (marker-buffer org-clock-hd-marker))
  10550. ""
  10551. (marker-position org-clock-hd-marker)))
  10552. (setq arg nil)))
  10553. (setq it
  10554. (or rfloc
  10555. (let (heading-text)
  10556. (save-excursion
  10557. (unless (and arg (listp arg))
  10558. (org-back-to-heading t)
  10559. (setq heading-text
  10560. (replace-regexp-in-string
  10561. org-bracket-link-regexp
  10562. "\\3"
  10563. (or (nth 4 (org-heading-components))
  10564. ""))))
  10565. (org-refile-get-location
  10566. (cond ((and arg (listp arg)) "Goto")
  10567. (regionp (concat actionmsg " region to"))
  10568. (t (concat actionmsg " subtree \""
  10569. heading-text "\" to")))
  10570. default-buffer
  10571. (and (not (equal '(4) arg))
  10572. org-refile-allow-creating-parent-nodes)))))))
  10573. (setq file (nth 1 it)
  10574. pos (nth 3 it))
  10575. (when (and (not arg)
  10576. pos
  10577. (equal (buffer-file-name) file)
  10578. (if regionp
  10579. (and (>= pos region-start)
  10580. (<= pos region-end))
  10581. (and (>= pos (point))
  10582. (< pos (save-excursion
  10583. (org-end-of-subtree t t))))))
  10584. (error "Cannot refile to position inside the tree or region"))
  10585. (setq nbuf (or (find-buffer-visiting file)
  10586. (find-file-noselect file)))
  10587. (if (and arg (not (equal arg 3)))
  10588. (progn
  10589. (pop-to-buffer-same-window nbuf)
  10590. (goto-char pos)
  10591. (org-show-context 'org-goto))
  10592. (if regionp
  10593. (progn
  10594. (org-kill-new (buffer-substring region-start region-end))
  10595. (org-save-markers-in-region region-start region-end))
  10596. (org-copy-subtree 1 nil t))
  10597. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10598. (find-file-noselect file)))
  10599. (setq reversed (org-notes-order-reversed-p))
  10600. (org-with-wide-buffer
  10601. (if pos
  10602. (progn
  10603. (goto-char pos)
  10604. (setq level (org-get-valid-level (funcall outline-level) 1))
  10605. (goto-char
  10606. (if reversed
  10607. (or (outline-next-heading) (point-max))
  10608. (or (save-excursion (org-get-next-sibling))
  10609. (org-end-of-subtree t t)
  10610. (point-max)))))
  10611. (setq level 1)
  10612. (if (not reversed)
  10613. (goto-char (point-max))
  10614. (goto-char (point-min))
  10615. (or (outline-next-heading) (goto-char (point-max)))))
  10616. (unless (bolp) (newline))
  10617. (org-paste-subtree level nil nil t)
  10618. (when org-log-refile
  10619. (org-add-log-setup 'refile nil nil org-log-refile)
  10620. (unless (eq org-log-refile 'note)
  10621. (save-excursion (org-add-log-note))))
  10622. (and org-auto-align-tags
  10623. (let ((org-loop-over-headlines-in-active-region nil))
  10624. (org-set-tags nil t)))
  10625. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10626. :last-refile)))
  10627. (when bookmark-name
  10628. (with-demoted-errors
  10629. (bookmark-set bookmark-name))))
  10630. ;; If we are refiling for capture, make sure that the
  10631. ;; last-capture pointers point here
  10632. (when (bound-and-true-p org-capture-is-refiling)
  10633. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10634. :last-capture-marker)))
  10635. (when bookmark-name
  10636. (with-demoted-errors
  10637. (bookmark-set bookmark-name))))
  10638. (move-marker org-capture-last-stored-marker (point)))
  10639. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10640. (run-hooks 'org-after-refile-insert-hook)))
  10641. (unless org-refile-keep
  10642. (if regionp
  10643. (delete-region (point) (+ (point) (- region-end region-start)))
  10644. (delete-region
  10645. (and (org-back-to-heading t) (point))
  10646. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10647. (when (featurep 'org-inlinetask)
  10648. (org-inlinetask-remove-END-maybe))
  10649. (setq org-markers-to-move nil)
  10650. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10651. (defun org-refile-goto-last-stored ()
  10652. "Go to the location where the last refile was stored."
  10653. (interactive)
  10654. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10655. (message "This is the location of the last refile"))
  10656. (defun org-refile--get-location (refloc tbl)
  10657. "When user refile to REFLOC, find the associated target in TBL.
  10658. Also check `org-refile-target-table'."
  10659. (car (delq
  10660. nil
  10661. (mapcar
  10662. (lambda (r) (or (assoc r tbl)
  10663. (assoc r org-refile-target-table)))
  10664. (list (replace-regexp-in-string "/$" "" refloc)
  10665. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10666. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10667. "Prompt the user for a refile location, using PROMPT.
  10668. PROMPT should not be suffixed with a colon and a space, because
  10669. this function appends the default value from
  10670. `org-refile-history' automatically, if that is not empty."
  10671. (let ((org-refile-targets org-refile-targets)
  10672. (org-refile-use-outline-path org-refile-use-outline-path))
  10673. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10674. (unless org-refile-target-table
  10675. (user-error "No refile targets"))
  10676. (let* ((cbuf (current-buffer))
  10677. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10678. (cfunc (if (and org-refile-use-outline-path
  10679. org-outline-path-complete-in-steps)
  10680. #'org-olpath-completing-read
  10681. #'completing-read))
  10682. (extra (if org-refile-use-outline-path "/" ""))
  10683. (cbnex (concat (buffer-name) extra))
  10684. (filename (and cfn (expand-file-name cfn)))
  10685. (tbl (mapcar
  10686. (lambda (x)
  10687. (if (and (not (member org-refile-use-outline-path
  10688. '(file full-file-path)))
  10689. (not (equal filename (nth 1 x))))
  10690. (cons (concat (car x) extra " ("
  10691. (file-name-nondirectory (nth 1 x)) ")")
  10692. (cdr x))
  10693. (cons (concat (car x) extra) (cdr x))))
  10694. org-refile-target-table))
  10695. (completion-ignore-case t)
  10696. cdef
  10697. (prompt (concat prompt
  10698. (or (and (car org-refile-history)
  10699. (concat " (default " (car org-refile-history) ")"))
  10700. (and (assoc cbnex tbl) (setq cdef cbnex)
  10701. (concat " (default " cbnex ")"))) ": "))
  10702. pa answ parent-target child parent old-hist)
  10703. (setq old-hist org-refile-history)
  10704. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10705. nil 'org-refile-history (or cdef (car org-refile-history))))
  10706. (if (setq pa (org-refile--get-location answ tbl))
  10707. (progn
  10708. (org-refile-check-position pa)
  10709. (when (or (not org-refile-history)
  10710. (not (eq old-hist org-refile-history))
  10711. (not (equal (car pa) (car org-refile-history))))
  10712. (setq org-refile-history
  10713. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10714. org-refile-history
  10715. (cdr org-refile-history))))
  10716. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10717. (pop org-refile-history)))
  10718. pa)
  10719. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10720. (progn
  10721. (setq parent (match-string 1 answ)
  10722. child (match-string 2 answ))
  10723. (setq parent-target (org-refile--get-location parent tbl))
  10724. (when (and parent-target
  10725. (or (eq new-nodes t)
  10726. (and (eq new-nodes 'confirm)
  10727. (y-or-n-p (format "Create new node \"%s\"? "
  10728. child)))))
  10729. (org-refile-new-child parent-target child)))
  10730. (user-error "Invalid target location")))))
  10731. (declare-function org-string-nw-p "org-macs" (s))
  10732. (defun org-refile-check-position (refile-pointer)
  10733. "Check if the refile pointer matches the headline to which it points."
  10734. (let* ((file (nth 1 refile-pointer))
  10735. (re (nth 2 refile-pointer))
  10736. (pos (nth 3 refile-pointer))
  10737. buffer)
  10738. (if (and (not (markerp pos)) (not file))
  10739. (user-error "Please indicate a target file in the refile path")
  10740. (when (org-string-nw-p re)
  10741. (setq buffer (if (markerp pos)
  10742. (marker-buffer pos)
  10743. (or (find-buffer-visiting file)
  10744. (find-file-noselect file))))
  10745. (with-current-buffer buffer
  10746. (org-with-wide-buffer
  10747. (goto-char pos)
  10748. (beginning-of-line 1)
  10749. (unless (looking-at-p re)
  10750. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10751. (defun org-refile-new-child (parent-target child)
  10752. "Use refile target PARENT-TARGET to add new CHILD below it."
  10753. (unless parent-target
  10754. (error "Cannot find parent for new node"))
  10755. (let ((file (nth 1 parent-target))
  10756. (pos (nth 3 parent-target))
  10757. level)
  10758. (with-current-buffer (or (find-buffer-visiting file)
  10759. (find-file-noselect file))
  10760. (org-with-wide-buffer
  10761. (if pos
  10762. (goto-char pos)
  10763. (goto-char (point-max))
  10764. (unless (bolp) (newline)))
  10765. (when (looking-at org-outline-regexp)
  10766. (setq level (funcall outline-level))
  10767. (org-end-of-subtree t t))
  10768. (org-back-over-empty-lines)
  10769. (insert "\n" (make-string
  10770. (if pos (org-get-valid-level level 1) 1) ?*)
  10771. " " child "\n")
  10772. (beginning-of-line 0)
  10773. (list (concat (car parent-target) "/" child) file "" (point))))))
  10774. (defun org-olpath-completing-read (prompt collection &rest args)
  10775. "Read an outline path like a file name."
  10776. (let ((thetable collection))
  10777. (apply #'completing-read
  10778. prompt
  10779. (lambda (string predicate &optional flag)
  10780. (cond
  10781. ((eq flag nil) (try-completion string thetable))
  10782. ((eq flag t)
  10783. (let ((l (length string)))
  10784. (mapcar (lambda (x)
  10785. (let ((r (substring x l))
  10786. (f (if (string-match " ([^)]*)$" x)
  10787. (match-string 0 x)
  10788. "")))
  10789. (if (string-match "/" r)
  10790. (concat string (substring r 0 (match-end 0)) f)
  10791. x)))
  10792. (all-completions string thetable predicate))))
  10793. ;; Exact match?
  10794. ((eq flag 'lambda) (assoc string thetable))))
  10795. args)))
  10796. ;;;; Dynamic blocks
  10797. (defun org-find-dblock (name)
  10798. "Find the first dynamic block with name NAME in the buffer.
  10799. If not found, stay at current position and return nil."
  10800. (let ((case-fold-search t) pos)
  10801. (save-excursion
  10802. (goto-char (point-min))
  10803. (setq pos (and (re-search-forward
  10804. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10805. (match-beginning 0))))
  10806. (when pos (goto-char pos))
  10807. pos))
  10808. (defun org-create-dblock (plist)
  10809. "Create a dynamic block section, with parameters taken from PLIST.
  10810. PLIST must contain a :name entry which is used as the name of the block."
  10811. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10812. (end-of-line 1)
  10813. (newline))
  10814. (let ((col (current-column))
  10815. (name (plist-get plist :name)))
  10816. (insert "#+BEGIN: " name)
  10817. (while plist
  10818. (if (eq (car plist) :name)
  10819. (setq plist (cddr plist))
  10820. (insert " " (prin1-to-string (pop plist)))))
  10821. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10822. (beginning-of-line -2)))
  10823. (defun org-prepare-dblock ()
  10824. "Prepare dynamic block for refresh.
  10825. This empties the block, puts the cursor at the insert position and returns
  10826. the property list including an extra property :name with the block name."
  10827. (unless (looking-at org-dblock-start-re)
  10828. (user-error "Not at a dynamic block"))
  10829. (let* ((begdel (1+ (match-end 0)))
  10830. (name (org-no-properties (match-string 1)))
  10831. (params (append (list :name name)
  10832. (read (concat "(" (match-string 3) ")")))))
  10833. (save-excursion
  10834. (beginning-of-line 1)
  10835. (skip-chars-forward " \t")
  10836. (setq params (plist-put params :indentation-column (current-column))))
  10837. (unless (re-search-forward org-dblock-end-re nil t)
  10838. (error "Dynamic block not terminated"))
  10839. (setq params
  10840. (append params
  10841. (list :content (buffer-substring
  10842. begdel (match-beginning 0)))))
  10843. (delete-region begdel (match-beginning 0))
  10844. (goto-char begdel)
  10845. (open-line 1)
  10846. params))
  10847. (defun org-map-dblocks (&optional command)
  10848. "Apply COMMAND to all dynamic blocks in the current buffer.
  10849. If COMMAND is not given, use `org-update-dblock'."
  10850. (let ((cmd (or command 'org-update-dblock)))
  10851. (save-excursion
  10852. (goto-char (point-min))
  10853. (while (re-search-forward org-dblock-start-re nil t)
  10854. (goto-char (match-beginning 0))
  10855. (save-excursion
  10856. (condition-case nil
  10857. (funcall cmd)
  10858. (error (message "Error during update of dynamic block"))))
  10859. (unless (re-search-forward org-dblock-end-re nil t)
  10860. (error "Dynamic block not terminated"))))))
  10861. (defun org-dblock-update (&optional arg)
  10862. "User command for updating dynamic blocks.
  10863. Update the dynamic block at point. With prefix ARG, update all dynamic
  10864. blocks in the buffer."
  10865. (interactive "P")
  10866. (if arg
  10867. (org-update-all-dblocks)
  10868. (or (looking-at org-dblock-start-re)
  10869. (org-beginning-of-dblock))
  10870. (org-update-dblock)))
  10871. (defun org-update-dblock ()
  10872. "Update the dynamic block at point.
  10873. This means to empty the block, parse for parameters and then call
  10874. the correct writing function."
  10875. (interactive)
  10876. (save-excursion
  10877. (let* ((win (selected-window))
  10878. (pos (point))
  10879. (line (org-current-line))
  10880. (params (org-prepare-dblock))
  10881. (name (plist-get params :name))
  10882. (indent (plist-get params :indentation-column))
  10883. (cmd (intern (concat "org-dblock-write:" name))))
  10884. (message "Updating dynamic block `%s' at line %d..." name line)
  10885. (funcall cmd params)
  10886. (message "Updating dynamic block `%s' at line %d...done" name line)
  10887. (goto-char pos)
  10888. (when (and indent (> indent 0))
  10889. (setq indent (make-string indent ?\ ))
  10890. (save-excursion
  10891. (select-window win)
  10892. (org-beginning-of-dblock)
  10893. (forward-line 1)
  10894. (while (not (looking-at org-dblock-end-re))
  10895. (insert indent)
  10896. (beginning-of-line 2))
  10897. (when (looking-at org-dblock-end-re)
  10898. (and (looking-at "[ \t]+")
  10899. (replace-match ""))
  10900. (insert indent)))))))
  10901. (defun org-beginning-of-dblock ()
  10902. "Find the beginning of the dynamic block at point.
  10903. Error if there is no such block at point."
  10904. (let ((pos (point))
  10905. beg)
  10906. (end-of-line 1)
  10907. (if (and (re-search-backward org-dblock-start-re nil t)
  10908. (setq beg (match-beginning 0))
  10909. (re-search-forward org-dblock-end-re nil t)
  10910. (> (match-end 0) pos))
  10911. (goto-char beg)
  10912. (goto-char pos)
  10913. (error "Not in a dynamic block"))))
  10914. (defun org-update-all-dblocks ()
  10915. "Update all dynamic blocks in the buffer.
  10916. This function can be used in a hook."
  10917. (interactive)
  10918. (when (derived-mode-p 'org-mode)
  10919. (org-map-dblocks 'org-update-dblock)))
  10920. ;;;; Completion
  10921. (declare-function org-export-backend-options "ox" (cl-x) t)
  10922. (defun org-get-export-keywords ()
  10923. "Return a list of all currently understood export keywords.
  10924. Export keywords include options, block names, attributes and
  10925. keywords relative to each registered export back-end."
  10926. (let (keywords)
  10927. (dolist (backend
  10928. (bound-and-true-p org-export-registered-backends)
  10929. (delq nil keywords))
  10930. ;; Back-end name (for keywords, like #+LATEX:)
  10931. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  10932. (dolist (option-entry (org-export-backend-options backend))
  10933. ;; Back-end options.
  10934. (push (nth 1 option-entry) keywords)))))
  10935. (defconst org-options-keywords
  10936. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  10937. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  10938. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  10939. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  10940. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  10941. (defcustom org-structure-template-alist
  10942. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  10943. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  10944. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  10945. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  10946. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  10947. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  10948. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  10949. ("L" "#+LaTeX: ")
  10950. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  10951. ("H" "#+HTML: ")
  10952. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  10953. ("A" "#+ASCII: ")
  10954. ("i" "#+INDEX: ?")
  10955. ("I" "#+INCLUDE: %file ?"))
  10956. "Structure completion elements.
  10957. This is a list of abbreviation keys and values. The value gets inserted
  10958. if you type `<' followed by the key and then press the completion key,
  10959. usually `TAB'. %file will be replaced by a file name after prompting
  10960. for the file using completion. The cursor will be placed at the position
  10961. of the `?' in the template.
  10962. There are two templates for each key, the first uses the original Org syntax,
  10963. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  10964. the default when the /org-mtags.el/ module has been loaded. See also the
  10965. variable `org-mtags-prefer-muse-templates'."
  10966. :group 'org-completion
  10967. :type '(repeat
  10968. (list
  10969. (string :tag "Key")
  10970. (string :tag "Template")))
  10971. :version "26.1"
  10972. :package-version '(Org . "8.3"))
  10973. (defun org-try-structure-completion ()
  10974. "Try to complete a structure template before point.
  10975. This looks for strings like \"<e\" on an otherwise empty line and
  10976. expands them."
  10977. (let ((l (buffer-substring (point-at-bol) (point)))
  10978. a)
  10979. (when (and (looking-at "[ \t]*$")
  10980. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  10981. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  10982. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  10983. (match-beginning 1)) a)
  10984. t)))
  10985. (defun org-complete-expand-structure-template (start cell)
  10986. "Expand a structure template."
  10987. (let ((rpl (nth 1 cell))
  10988. (ind ""))
  10989. (delete-region start (point))
  10990. (when (string-match "\\`[ \t]*#\\+" rpl)
  10991. (cond
  10992. ((bolp))
  10993. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  10994. (setq ind (buffer-substring (point-at-bol) (point))))
  10995. (t (newline))))
  10996. (setq start (point))
  10997. (when (string-match "%file" rpl)
  10998. (setq rpl (replace-match
  10999. (concat
  11000. "\""
  11001. (save-match-data
  11002. (abbreviate-file-name (read-file-name "Include file: ")))
  11003. "\"")
  11004. t t rpl)))
  11005. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11006. (concat "\n" ind)))
  11007. (insert rpl)
  11008. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11009. ;;;; TODO, DEADLINE, Comments
  11010. (defun org-toggle-comment ()
  11011. "Change the COMMENT state of an entry."
  11012. (interactive)
  11013. (save-excursion
  11014. (org-back-to-heading)
  11015. (let ((case-fold-search nil))
  11016. (looking-at org-complex-heading-regexp))
  11017. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11018. (skip-chars-forward " \t")
  11019. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11020. (if (org-in-commented-heading-p t)
  11021. (delete-region (point)
  11022. (progn (search-forward " " (line-end-position) 'move)
  11023. (skip-chars-forward " \t")
  11024. (point)))
  11025. (insert org-comment-string)
  11026. (unless (eolp) (insert " ")))))
  11027. (defvar org-last-todo-state-is-todo nil
  11028. "This is non-nil when the last TODO state change led to a TODO state.
  11029. If the last change removed the TODO tag or switched to DONE, then
  11030. this is nil.")
  11031. (defvar org-setting-tags nil) ; dynamically skipped
  11032. (defvar org-todo-setup-filter-hook nil
  11033. "Hook for functions that pre-filter todo specs.
  11034. Each function takes a todo spec and returns either nil or the spec
  11035. transformed into canonical form." )
  11036. (defvar org-todo-get-default-hook nil
  11037. "Hook for functions that get a default item for todo.
  11038. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11039. nil or a string to be used for the todo mark." )
  11040. (defvar org-agenda-headline-snapshot-before-repeat)
  11041. (defun org-current-effective-time ()
  11042. "Return current time adjusted for `org-extend-today-until' variable."
  11043. (let* ((ct (org-current-time))
  11044. (dct (decode-time ct))
  11045. (ct1
  11046. (cond
  11047. (org-use-last-clock-out-time-as-effective-time
  11048. (or (org-clock-get-last-clock-out-time) ct))
  11049. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11050. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11051. (t ct))))
  11052. ct1))
  11053. (defun org-todo-yesterday (&optional arg)
  11054. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11055. (interactive "P")
  11056. (if (eq major-mode 'org-agenda-mode)
  11057. (apply 'org-agenda-todo-yesterday arg)
  11058. (let* ((org-use-effective-time t)
  11059. (hour (nth 2 (decode-time (org-current-time))))
  11060. (org-extend-today-until (1+ hour)))
  11061. (org-todo arg))))
  11062. (defvar org-block-entry-blocking ""
  11063. "First entry preventing the TODO state change.")
  11064. (defun org-cancel-repeater ()
  11065. "Cancel a repeater by setting its numeric value to zero."
  11066. (interactive)
  11067. (save-excursion
  11068. (org-back-to-heading t)
  11069. (let ((bound1 (point))
  11070. (bound0 (save-excursion (outline-next-heading) (point))))
  11071. (when (and (re-search-forward
  11072. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11073. org-deadline-time-regexp "\\)\\|\\("
  11074. org-ts-regexp "\\)")
  11075. bound0 t)
  11076. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11077. bound1 t))
  11078. (replace-match "0" t nil nil 1)))))
  11079. (defvar org-state)
  11080. (defvar org-blocked-by-checkboxes)
  11081. (defun org-todo (&optional arg)
  11082. "Change the TODO state of an item.
  11083. The state of an item is given by a keyword at the start of the heading,
  11084. like
  11085. *** TODO Write paper
  11086. *** DONE Call mom
  11087. The different keywords are specified in the variable `org-todo-keywords'.
  11088. By default the available states are \"TODO\" and \"DONE\". So, for this
  11089. example: when the item starts with TODO, it is changed to DONE.
  11090. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11091. DONE are present, add TODO at the beginning of the heading.
  11092. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11093. state.
  11094. With numeric prefix ARG, switch to that state.
  11095. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11096. next set of TODO \
  11097. keywords (nextset).
  11098. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11099. prefix, circumvent any state blocking.
  11100. With a numeric prefix arg of 0, inhibit note taking for the change.
  11101. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11102. When called through ELisp, arg is also interpreted in the following way:
  11103. `none' -> empty state
  11104. \"\" -> switch to empty state
  11105. `done' -> switch to DONE
  11106. `nextset' -> switch to the next set of keywords
  11107. `previousset' -> switch to the previous set of keywords
  11108. \"WAITING\" -> switch to the specified keyword, but only if it
  11109. really is a member of `org-todo-keywords'."
  11110. (interactive "P")
  11111. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11112. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11113. 'region-start-level 'region))
  11114. org-loop-over-headlines-in-active-region)
  11115. (org-map-entries
  11116. `(org-todo ,arg)
  11117. org-loop-over-headlines-in-active-region
  11118. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11119. (when (equal arg '(16)) (setq arg 'nextset))
  11120. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11121. (let ((org-blocker-hook org-blocker-hook)
  11122. commentp
  11123. case-fold-search)
  11124. (when (equal arg '(64))
  11125. (setq arg nil org-blocker-hook nil))
  11126. (when (and org-blocker-hook
  11127. (or org-inhibit-blocking
  11128. (org-entry-get nil "NOBLOCKING")))
  11129. (setq org-blocker-hook nil))
  11130. (save-excursion
  11131. (catch 'exit
  11132. (org-back-to-heading t)
  11133. (when (org-in-commented-heading-p t)
  11134. (org-toggle-comment)
  11135. (setq commentp t))
  11136. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11137. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11138. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11139. (let* ((match-data (match-data))
  11140. (startpos (point-at-bol))
  11141. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11142. (org-log-done org-log-done)
  11143. (org-log-repeat org-log-repeat)
  11144. (org-todo-log-states org-todo-log-states)
  11145. (org-inhibit-logging
  11146. (if (equal arg 0)
  11147. (progn (setq arg nil) 'note) org-inhibit-logging))
  11148. (this (match-string 1))
  11149. (hl-pos (match-beginning 0))
  11150. (head (org-get-todo-sequence-head this))
  11151. (ass (assoc head org-todo-kwd-alist))
  11152. (interpret (nth 1 ass))
  11153. (done-word (nth 3 ass))
  11154. (final-done-word (nth 4 ass))
  11155. (org-last-state (or this ""))
  11156. (completion-ignore-case t)
  11157. (member (member this org-todo-keywords-1))
  11158. (tail (cdr member))
  11159. (org-state (cond
  11160. ((and org-todo-key-trigger
  11161. (or (and (equal arg '(4))
  11162. (eq org-use-fast-todo-selection 'prefix))
  11163. (and (not arg) org-use-fast-todo-selection
  11164. (not (eq org-use-fast-todo-selection
  11165. 'prefix)))))
  11166. ;; Use fast selection.
  11167. (org-fast-todo-selection))
  11168. ((and (equal arg '(4))
  11169. (or (not org-use-fast-todo-selection)
  11170. (not org-todo-key-trigger)))
  11171. ;; Read a state with completion.
  11172. (completing-read
  11173. "State: " (mapcar #'list org-todo-keywords-1)
  11174. nil t))
  11175. ((eq arg 'right)
  11176. (if this
  11177. (if tail (car tail) nil)
  11178. (car org-todo-keywords-1)))
  11179. ((eq arg 'left)
  11180. (unless (equal member org-todo-keywords-1)
  11181. (if this
  11182. (nth (- (length org-todo-keywords-1)
  11183. (length tail) 2)
  11184. org-todo-keywords-1)
  11185. (org-last org-todo-keywords-1))))
  11186. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11187. (setq arg nil))) ;hack to fall back to cycling
  11188. (arg
  11189. ;; User or caller requests a specific state.
  11190. (cond
  11191. ((equal arg "") nil)
  11192. ((eq arg 'none) nil)
  11193. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11194. ((eq arg 'nextset)
  11195. (or (car (cdr (member head org-todo-heads)))
  11196. (car org-todo-heads)))
  11197. ((eq arg 'previousset)
  11198. (let ((org-todo-heads (reverse org-todo-heads)))
  11199. (or (car (cdr (member head org-todo-heads)))
  11200. (car org-todo-heads))))
  11201. ((car (member arg org-todo-keywords-1)))
  11202. ((stringp arg)
  11203. (user-error "State `%s' not valid in this file" arg))
  11204. ((nth (1- (prefix-numeric-value arg))
  11205. org-todo-keywords-1))))
  11206. ((null member) (or head (car org-todo-keywords-1)))
  11207. ((equal this final-done-word) nil) ;-> make empty
  11208. ((null tail) nil) ;-> first entry
  11209. ((memq interpret '(type priority))
  11210. (if (eq this-command last-command)
  11211. (car tail)
  11212. (if (> (length tail) 0)
  11213. (or done-word (car org-done-keywords))
  11214. nil)))
  11215. (t
  11216. (car tail))))
  11217. (org-state (or
  11218. (run-hook-with-args-until-success
  11219. 'org-todo-get-default-hook org-state org-last-state)
  11220. org-state))
  11221. (next (if org-state (concat " " org-state " ") " "))
  11222. (change-plist (list :type 'todo-state-change :from this :to org-state
  11223. :position startpos))
  11224. dolog now-done-p)
  11225. (when org-blocker-hook
  11226. (let (org-blocked-by-checkboxes block-reason)
  11227. (setq org-last-todo-state-is-todo
  11228. (not (member this org-done-keywords)))
  11229. (unless (save-excursion
  11230. (save-match-data
  11231. (org-with-wide-buffer
  11232. (run-hook-with-args-until-failure
  11233. 'org-blocker-hook change-plist))))
  11234. (setq block-reason (if org-blocked-by-checkboxes
  11235. "contained checkboxes"
  11236. (format "\"%s\"" org-block-entry-blocking)))
  11237. (if (called-interactively-p 'interactive)
  11238. (user-error "TODO state change from %s to %s blocked (by %s)"
  11239. this org-state block-reason)
  11240. ;; Fail silently.
  11241. (message "TODO state change from %s to %s blocked (by %s)"
  11242. this org-state block-reason)
  11243. (throw 'exit nil)))))
  11244. (store-match-data match-data)
  11245. (replace-match next t t)
  11246. (cond ((equal this org-state)
  11247. (message "TODO state was already %s" (org-trim next)))
  11248. ((pos-visible-in-window-p hl-pos)
  11249. (message "TODO state changed to %s" (org-trim next))))
  11250. (unless head
  11251. (setq head (org-get-todo-sequence-head org-state)
  11252. ass (assoc head org-todo-kwd-alist)
  11253. interpret (nth 1 ass)
  11254. done-word (nth 3 ass)
  11255. final-done-word (nth 4 ass)))
  11256. (when (memq arg '(nextset previousset))
  11257. (message "Keyword-Set %d/%d: %s"
  11258. (- (length org-todo-sets) -1
  11259. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11260. (length org-todo-sets)
  11261. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11262. (setq org-last-todo-state-is-todo
  11263. (not (member org-state org-done-keywords)))
  11264. (setq now-done-p (and (member org-state org-done-keywords)
  11265. (not (member this org-done-keywords))))
  11266. (and logging (org-local-logging logging))
  11267. (when (and (or org-todo-log-states org-log-done)
  11268. (not (eq org-inhibit-logging t))
  11269. (not (memq arg '(nextset previousset))))
  11270. ;; We need to look at recording a time and note.
  11271. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11272. (nth 2 (assoc this org-todo-log-states))))
  11273. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11274. (setq dolog 'time))
  11275. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11276. (and org-state
  11277. (member org-state org-not-done-keywords)
  11278. (not (member this org-not-done-keywords))))
  11279. ;; This is now a todo state and was not one before
  11280. ;; If there was a CLOSED time stamp, get rid of it.
  11281. (org-add-planning-info nil nil 'closed))
  11282. (when (and now-done-p org-log-done)
  11283. ;; It is now done, and it was not done before.
  11284. (org-add-planning-info 'closed (org-current-effective-time))
  11285. (when (and (not dolog) (eq 'note org-log-done))
  11286. (org-add-log-setup 'done org-state this 'note)))
  11287. (when (and org-state dolog)
  11288. ;; This is a non-nil state, and we need to log it.
  11289. (org-add-log-setup 'state org-state this dolog)))
  11290. ;; Fixup tag positioning.
  11291. (org-todo-trigger-tag-changes org-state)
  11292. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11293. (when org-provide-todo-statistics
  11294. (org-update-parent-todo-statistics))
  11295. (run-hooks 'org-after-todo-state-change-hook)
  11296. (when (and arg (not (member org-state org-done-keywords)))
  11297. (setq head (org-get-todo-sequence-head org-state)))
  11298. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11299. ;; Do we need to trigger a repeat?
  11300. (when now-done-p
  11301. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11302. ;; This is for the agenda, take a snapshot of the headline.
  11303. (save-match-data
  11304. (setq org-agenda-headline-snapshot-before-repeat
  11305. (org-get-heading))))
  11306. (org-auto-repeat-maybe org-state))
  11307. ;; Fixup cursor location if close to the keyword.
  11308. (when (and (outline-on-heading-p)
  11309. (not (bolp))
  11310. (save-excursion (beginning-of-line 1)
  11311. (looking-at org-todo-line-regexp))
  11312. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11313. (goto-char (or (match-end 2) (match-end 1)))
  11314. (and (looking-at " ") (just-one-space)))
  11315. (when org-trigger-hook
  11316. (save-excursion
  11317. (run-hook-with-args 'org-trigger-hook change-plist)))
  11318. (when commentp (org-toggle-comment))))))))
  11319. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11320. "Block turning an entry into a TODO, using the hierarchy.
  11321. This checks whether the current task should be blocked from state
  11322. changes. Such blocking occurs when:
  11323. 1. The task has children which are not all in a completed state.
  11324. 2. A task has a parent with the property :ORDERED:, and there
  11325. are siblings prior to the current task with incomplete
  11326. status.
  11327. 3. The parent of the task is blocked because it has siblings that should
  11328. be done first, or is child of a block grandparent TODO entry."
  11329. (if (not org-enforce-todo-dependencies)
  11330. t ; if locally turned off don't block
  11331. (catch 'dont-block
  11332. ;; If this is not a todo state change, or if this entry is already DONE,
  11333. ;; do not block
  11334. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11335. (member (plist-get change-plist :from)
  11336. (cons 'done org-done-keywords))
  11337. (member (plist-get change-plist :to)
  11338. (cons 'todo org-not-done-keywords))
  11339. (not (plist-get change-plist :to)))
  11340. (throw 'dont-block t))
  11341. ;; If this task has children, and any are undone, it's blocked
  11342. (save-excursion
  11343. (org-back-to-heading t)
  11344. (let ((this-level (funcall outline-level)))
  11345. (outline-next-heading)
  11346. (let ((child-level (funcall outline-level)))
  11347. (while (and (not (eobp))
  11348. (> child-level this-level))
  11349. ;; this todo has children, check whether they are all
  11350. ;; completed
  11351. (when (and (not (org-entry-is-done-p))
  11352. (org-entry-is-todo-p))
  11353. (setq org-block-entry-blocking (org-get-heading))
  11354. (throw 'dont-block nil))
  11355. (outline-next-heading)
  11356. (setq child-level (funcall outline-level))))))
  11357. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11358. ;; any previous siblings are undone, it's blocked
  11359. (save-excursion
  11360. (org-back-to-heading t)
  11361. (let* ((pos (point))
  11362. (parent-pos (and (org-up-heading-safe) (point)))
  11363. (case-fold-search nil))
  11364. (unless parent-pos (throw 'dont-block t)) ; no parent
  11365. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11366. (forward-line 1)
  11367. (re-search-forward org-not-done-heading-regexp pos t))
  11368. (setq org-block-entry-blocking (match-string 0))
  11369. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11370. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11371. (while t
  11372. (goto-char parent-pos)
  11373. (unless (looking-at org-not-done-heading-regexp)
  11374. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11375. (setq pos (point))
  11376. (setq parent-pos (and (org-up-heading-safe) (point)))
  11377. (unless parent-pos (throw 'dont-block t)) ; no parent
  11378. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11379. (forward-line 1)
  11380. (re-search-forward org-not-done-heading-regexp pos t)
  11381. (setq org-block-entry-blocking (org-get-heading)))
  11382. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11383. (defcustom org-track-ordered-property-with-tag nil
  11384. "Should the ORDERED property also be shown as a tag?
  11385. The ORDERED property decides if an entry should require subtasks to be
  11386. completed in sequence. Since a property is not very visible, setting
  11387. this option means that toggling the ORDERED property with the command
  11388. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11389. not relevant for the behavior, but it makes things more visible.
  11390. Note that toggling the tag with tags commands will not change the property
  11391. and therefore not influence behavior!
  11392. This can be t, meaning the tag ORDERED should be used, It can also be a
  11393. string to select a different tag for this task."
  11394. :group 'org-todo
  11395. :type '(choice
  11396. (const :tag "No tracking" nil)
  11397. (const :tag "Track with ORDERED tag" t)
  11398. (string :tag "Use other tag")))
  11399. (defun org-toggle-ordered-property ()
  11400. "Toggle the ORDERED property of the current entry.
  11401. For better visibility, you can track the value of this property with a tag.
  11402. See variable `org-track-ordered-property-with-tag'."
  11403. (interactive)
  11404. (let* ((t1 org-track-ordered-property-with-tag)
  11405. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11406. (save-excursion
  11407. (org-back-to-heading)
  11408. (if (org-entry-get nil "ORDERED")
  11409. (progn
  11410. (org-delete-property "ORDERED")
  11411. (and tag (org-toggle-tag tag 'off))
  11412. (message "Subtasks can be completed in arbitrary order"))
  11413. (org-entry-put nil "ORDERED" "t")
  11414. (and tag (org-toggle-tag tag 'on))
  11415. (message "Subtasks must be completed in sequence")))))
  11416. (defun org-block-todo-from-checkboxes (change-plist)
  11417. "Block turning an entry into a TODO, using checkboxes.
  11418. This checks whether the current task should be blocked from state
  11419. changes because there are unchecked boxes in this entry."
  11420. (if (not org-enforce-todo-checkbox-dependencies)
  11421. t ; if locally turned off don't block
  11422. (catch 'dont-block
  11423. ;; If this is not a todo state change, or if this entry is already DONE,
  11424. ;; do not block
  11425. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11426. (member (plist-get change-plist :from)
  11427. (cons 'done org-done-keywords))
  11428. (member (plist-get change-plist :to)
  11429. (cons 'todo org-not-done-keywords))
  11430. (not (plist-get change-plist :to)))
  11431. (throw 'dont-block t))
  11432. ;; If this task has checkboxes that are not checked, it's blocked
  11433. (save-excursion
  11434. (org-back-to-heading t)
  11435. (let ((beg (point)) end)
  11436. (outline-next-heading)
  11437. (setq end (point))
  11438. (goto-char beg)
  11439. (when (org-list-search-forward
  11440. (concat (org-item-beginning-re)
  11441. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11442. "\\[[- ]\\]")
  11443. end t)
  11444. (when (boundp 'org-blocked-by-checkboxes)
  11445. (setq org-blocked-by-checkboxes t))
  11446. (throw 'dont-block nil))))
  11447. t))) ; do not block
  11448. (defun org-entry-blocked-p ()
  11449. "Non-nil if entry at point is blocked."
  11450. (and (not (org-entry-get nil "NOBLOCKING"))
  11451. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11452. (not (run-hook-with-args-until-failure
  11453. 'org-blocker-hook
  11454. (list :type 'todo-state-change
  11455. :position (point)
  11456. :from 'todo
  11457. :to 'done)))))
  11458. (defun org-update-statistics-cookies (all)
  11459. "Update the statistics cookie, either from TODO or from checkboxes.
  11460. This should be called with the cursor in a line with a statistics
  11461. cookie. When called with a \\[universal-argument] prefix, update
  11462. all statistics cookies in the buffer."
  11463. (interactive "P")
  11464. (if all
  11465. (progn
  11466. (org-update-checkbox-count 'all)
  11467. (org-map-entries 'org-update-parent-todo-statistics))
  11468. (if (not (org-at-heading-p))
  11469. (org-update-checkbox-count)
  11470. (let ((pos (point-marker))
  11471. end l1 l2)
  11472. (ignore-errors (org-back-to-heading t))
  11473. (if (not (org-at-heading-p))
  11474. (org-update-checkbox-count)
  11475. (setq l1 (org-outline-level))
  11476. (setq end (save-excursion
  11477. (outline-next-heading)
  11478. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11479. (point)))
  11480. (if (and (save-excursion
  11481. (re-search-forward
  11482. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11483. (not (save-excursion (re-search-forward
  11484. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11485. (org-update-checkbox-count)
  11486. (if (and l2 (> l2 l1))
  11487. (progn
  11488. (goto-char end)
  11489. (org-update-parent-todo-statistics))
  11490. (goto-char pos)
  11491. (beginning-of-line 1)
  11492. (while (re-search-forward
  11493. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11494. (point-at-eol) t)
  11495. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11496. (goto-char pos)
  11497. (move-marker pos nil)))))
  11498. (defvar org-entry-property-inherited-from) ;; defined below
  11499. (defun org-update-parent-todo-statistics ()
  11500. "Update any statistics cookie in the parent of the current headline.
  11501. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11502. the entire subtree and this will travel up the hierarchy and update
  11503. statistics everywhere."
  11504. (let* ((prop (save-excursion (org-up-heading-safe)
  11505. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11506. (recursive (or (not org-hierarchical-todo-statistics)
  11507. (and prop (string-match "\\<recursive\\>" prop))))
  11508. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11509. 0))
  11510. (first t)
  11511. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11512. level ltoggle l1 new ndel
  11513. (cnt-all 0) (cnt-done 0) is-percent kwd
  11514. checkbox-beg cookie-present)
  11515. (catch 'exit
  11516. (save-excursion
  11517. (beginning-of-line 1)
  11518. (setq ltoggle (funcall outline-level))
  11519. ;; Three situations are to consider:
  11520. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11521. ;; to the top-level ancestor on the headline;
  11522. ;; 2. If parent has "recursive" property, repeat up to the
  11523. ;; headline setting that property, taking inheritance into
  11524. ;; account;
  11525. ;; 3. Else, move up to direct parent and proceed only once.
  11526. (while (and (setq level (org-up-heading-safe))
  11527. (or recursive first)
  11528. (>= (point) lim))
  11529. (setq first nil cookie-present nil)
  11530. (unless (and level
  11531. (not (string-match
  11532. "\\<checkbox\\>"
  11533. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11534. "")))))
  11535. (throw 'exit nil))
  11536. (while (re-search-forward box-re (point-at-eol) t)
  11537. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11538. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11539. (save-match-data
  11540. (unless (outline-next-heading) (throw 'exit nil))
  11541. (while (and (looking-at org-complex-heading-regexp)
  11542. (> (setq l1 (length (match-string 1))) level))
  11543. (setq kwd (and (or recursive (= l1 ltoggle))
  11544. (match-string 2)))
  11545. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11546. (and (eq org-provide-todo-statistics t)
  11547. (or (member kwd org-done-keywords)))
  11548. (and (listp org-provide-todo-statistics)
  11549. (stringp (car org-provide-todo-statistics))
  11550. (or (member kwd org-provide-todo-statistics)
  11551. (member kwd org-done-keywords)))
  11552. (and (listp org-provide-todo-statistics)
  11553. (listp (car org-provide-todo-statistics))
  11554. (or (member kwd (car org-provide-todo-statistics))
  11555. (and (member kwd org-done-keywords)
  11556. (member kwd (cadr org-provide-todo-statistics))))))
  11557. (setq cnt-all (1+ cnt-all))
  11558. (and (eq org-provide-todo-statistics t)
  11559. kwd
  11560. (setq cnt-all (1+ cnt-all))))
  11561. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11562. (member kwd org-done-keywords))
  11563. (and (listp org-provide-todo-statistics)
  11564. (listp (car org-provide-todo-statistics))
  11565. (member kwd org-done-keywords)
  11566. (member kwd (cadr org-provide-todo-statistics)))
  11567. (and (listp org-provide-todo-statistics)
  11568. (stringp (car org-provide-todo-statistics))
  11569. (member kwd org-done-keywords)))
  11570. (setq cnt-done (1+ cnt-done)))
  11571. (outline-next-heading)))
  11572. (setq new
  11573. (if is-percent
  11574. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11575. (max 1 cnt-all)))
  11576. (format "[%d/%d]" cnt-done cnt-all))
  11577. ndel (- (match-end 0) checkbox-beg))
  11578. (goto-char checkbox-beg)
  11579. (insert new)
  11580. (delete-region (point) (+ (point) ndel))
  11581. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11582. (when cookie-present
  11583. (run-hook-with-args 'org-after-todo-statistics-hook
  11584. cnt-done (- cnt-all cnt-done))))))
  11585. (run-hooks 'org-todo-statistics-hook)))
  11586. (defvar org-after-todo-statistics-hook nil
  11587. "Hook that is called after a TODO statistics cookie has been updated.
  11588. Each function is called with two arguments: the number of not-done entries
  11589. and the number of done entries.
  11590. For example, the following function, when added to this hook, will switch
  11591. an entry to DONE when all children are done, and back to TODO when new
  11592. entries are set to a TODO status. Note that this hook is only called
  11593. when there is a statistics cookie in the headline!
  11594. (defun org-summary-todo (n-done n-not-done)
  11595. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11596. (let (org-log-done org-log-states) ; turn off logging
  11597. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11598. ")
  11599. (defvar org-todo-statistics-hook nil
  11600. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11601. This hook runs even if there is no statistics cookie present, in which case
  11602. `org-after-todo-statistics-hook' would not run.")
  11603. (defun org-todo-trigger-tag-changes (state)
  11604. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11605. (let ((l org-todo-state-tags-triggers)
  11606. changes)
  11607. (when (or (not state) (equal state ""))
  11608. (setq changes (append changes (cdr (assoc "" l)))))
  11609. (when (and (stringp state) (> (length state) 0))
  11610. (setq changes (append changes (cdr (assoc state l)))))
  11611. (when (member state org-not-done-keywords)
  11612. (setq changes (append changes (cdr (assq 'todo l)))))
  11613. (when (member state org-done-keywords)
  11614. (setq changes (append changes (cdr (assq 'done l)))))
  11615. (dolist (c changes)
  11616. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11617. (defun org-local-logging (value)
  11618. "Get logging settings from a property VALUE."
  11619. ;; Directly set the variables, they are already local.
  11620. (setq org-log-done nil
  11621. org-log-repeat nil
  11622. org-todo-log-states nil)
  11623. (dolist (w (org-split-string value))
  11624. (let (a)
  11625. (cond
  11626. ((setq a (assoc w org-startup-options))
  11627. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11628. (set (nth 1 a) (nth 2 a))))
  11629. ((setq a (org-extract-log-state-settings w))
  11630. (and (member (car a) org-todo-keywords-1)
  11631. (push a org-todo-log-states)))))))
  11632. (defun org-get-todo-sequence-head (kwd)
  11633. "Return the head of the TODO sequence to which KWD belongs.
  11634. If KWD is not set, check if there is a text property remembering the
  11635. right sequence."
  11636. (let (p)
  11637. (cond
  11638. ((not kwd)
  11639. (or (get-text-property (point-at-bol) 'org-todo-head)
  11640. (progn
  11641. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11642. nil (point-at-eol)))
  11643. (get-text-property p 'org-todo-head))))
  11644. ((not (member kwd org-todo-keywords-1))
  11645. (car org-todo-keywords-1))
  11646. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11647. (defun org-fast-todo-selection ()
  11648. "Fast TODO keyword selection with single keys.
  11649. Returns the new TODO keyword, or nil if no state change should occur."
  11650. (let* ((fulltable org-todo-key-alist)
  11651. (done-keywords org-done-keywords) ;; needed for the faces.
  11652. (maxlen (apply 'max (mapcar
  11653. (lambda (x)
  11654. (if (stringp (car x)) (string-width (car x)) 0))
  11655. fulltable)))
  11656. (expert nil)
  11657. (fwidth (+ maxlen 3 1 3))
  11658. (ncol (/ (- (window-width) 4) fwidth))
  11659. tg cnt e c tbl
  11660. groups ingroup)
  11661. (save-excursion
  11662. (save-window-excursion
  11663. (if expert
  11664. (set-buffer (get-buffer-create " *Org todo*"))
  11665. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11666. (erase-buffer)
  11667. (setq-local org-done-keywords done-keywords)
  11668. (setq tbl fulltable cnt 0)
  11669. (while (setq e (pop tbl))
  11670. (cond
  11671. ((equal e '(:startgroup))
  11672. (push '() groups) (setq ingroup t)
  11673. (unless (= cnt 0)
  11674. (setq cnt 0)
  11675. (insert "\n"))
  11676. (insert "{ "))
  11677. ((equal e '(:endgroup))
  11678. (setq ingroup nil cnt 0)
  11679. (insert "}\n"))
  11680. ((equal e '(:newline))
  11681. (unless (= cnt 0)
  11682. (setq cnt 0)
  11683. (insert "\n")
  11684. (setq e (car tbl))
  11685. (while (equal (car tbl) '(:newline))
  11686. (insert "\n")
  11687. (setq tbl (cdr tbl)))))
  11688. (t
  11689. (setq tg (car e) c (cdr e))
  11690. (when ingroup (push tg (car groups)))
  11691. (setq tg (org-add-props tg nil 'face
  11692. (org-get-todo-face tg)))
  11693. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11694. (insert "[" c "] " tg (make-string
  11695. (- fwidth 4 (length tg)) ?\ ))
  11696. (when (= (setq cnt (1+ cnt)) ncol)
  11697. (insert "\n")
  11698. (when ingroup (insert " "))
  11699. (setq cnt 0)))))
  11700. (insert "\n")
  11701. (goto-char (point-min))
  11702. (unless expert (org-fit-window-to-buffer))
  11703. (message "[a-z..]:Set [SPC]:clear")
  11704. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11705. (cond
  11706. ((or (= c ?\C-g)
  11707. (and (= c ?q) (not (rassoc c fulltable))))
  11708. (setq quit-flag t))
  11709. ((= c ?\ ) nil)
  11710. ((setq e (rassoc c fulltable) tg (car e))
  11711. tg)
  11712. (t (setq quit-flag t)))))))
  11713. (defun org-entry-is-todo-p ()
  11714. (member (org-get-todo-state) org-not-done-keywords))
  11715. (defun org-entry-is-done-p ()
  11716. (member (org-get-todo-state) org-done-keywords))
  11717. (defun org-get-todo-state ()
  11718. "Return the TODO keyword of the current subtree."
  11719. (save-excursion
  11720. (org-back-to-heading t)
  11721. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11722. (match-end 2)
  11723. (match-string 2))))
  11724. (defun org-at-date-range-p (&optional inactive-ok)
  11725. "Non-nil if point is inside a date range.
  11726. When optional argument INACTIVE-OK is non-nil, also consider
  11727. inactive time ranges.
  11728. When this function returns a non-nil value, match data is set
  11729. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11730. on INACTIVE-OK."
  11731. (interactive)
  11732. (save-excursion
  11733. (catch 'exit
  11734. (let ((pos (point)))
  11735. (skip-chars-backward "^[<\r\n")
  11736. (skip-chars-backward "<[")
  11737. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11738. (>= (match-end 0) pos)
  11739. (throw 'exit t))
  11740. (skip-chars-backward "^<[\r\n")
  11741. (skip-chars-backward "<[")
  11742. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11743. (>= (match-end 0) pos)
  11744. (throw 'exit t)))
  11745. nil)))
  11746. (defun org-get-repeat (&optional timestamp)
  11747. "Check if there is a time-stamp with repeater in this entry.
  11748. Return the repeater, as a string, or nil. Also return nil when
  11749. this function is called before first heading.
  11750. When optional argument TIMESTAMP is a string, extract the
  11751. repeater from there instead."
  11752. (save-match-data
  11753. (cond (timestamp
  11754. (and (string-match org-repeat-re timestamp)
  11755. (match-string-no-properties 1 timestamp)))
  11756. ((org-before-first-heading-p) nil)
  11757. (t
  11758. (save-excursion
  11759. (org-back-to-heading t)
  11760. (let ((end (org-entry-end-position)))
  11761. (catch :repeat
  11762. (while (re-search-forward org-repeat-re end t)
  11763. (when (save-match-data (org-at-timestamp-p 'agenda))
  11764. (throw :repeat (match-string-no-properties 1)))))))))))
  11765. (defvar org-last-changed-timestamp)
  11766. (defvar org-last-inserted-timestamp)
  11767. (defvar org-log-post-message)
  11768. (defvar org-log-note-purpose)
  11769. (defvar org-log-note-how nil)
  11770. (defvar org-log-note-extra)
  11771. (defun org-auto-repeat-maybe (done-word)
  11772. "Check if the current headline contains a repeated time-stamp.
  11773. If yes, set TODO state back to what it was and change the base date
  11774. of repeating deadline/scheduled time stamps to new date.
  11775. This function is run automatically after each state change to a DONE state."
  11776. (let* ((repeat (org-get-repeat))
  11777. (aa (assoc org-last-state org-todo-kwd-alist))
  11778. (interpret (nth 1 aa))
  11779. (head (nth 2 aa))
  11780. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11781. (msg "Entry repeats: ")
  11782. (org-log-done nil)
  11783. (org-todo-log-states nil)
  11784. (end (copy-marker (org-entry-end-position))))
  11785. (unwind-protect
  11786. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11787. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11788. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11789. org-todo-repeat-to-state)))
  11790. (org-todo (cond
  11791. ((and to-state (member to-state org-todo-keywords-1))
  11792. to-state)
  11793. ((eq interpret 'type) org-last-state)
  11794. (head)
  11795. (t 'none))))
  11796. (org-back-to-heading t)
  11797. (org-add-planning-info nil nil 'closed)
  11798. ;; When `org-log-repeat' is non-nil or entry contains
  11799. ;; a clock, set LAST_REPEAT property.
  11800. (when (or org-log-repeat
  11801. (catch :clock
  11802. (while (re-search-forward org-clock-line-re end t)
  11803. (when (org-at-clock-log-p) (throw :clock t)))))
  11804. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11805. (org-time-stamp-format t t)
  11806. (current-time))))
  11807. (when org-log-repeat
  11808. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11809. (memq 'org-add-log-note post-command-hook))
  11810. ;; We are already setup for some record.
  11811. (when (eq org-log-repeat 'note)
  11812. ;; Make sure we take a note, not only a time stamp.
  11813. (setq org-log-note-how 'note))
  11814. ;; Set up for taking a record.
  11815. (org-add-log-setup 'state
  11816. (or done-word (car org-done-keywords))
  11817. org-last-state
  11818. org-log-repeat)))
  11819. (let ((planning-re (regexp-opt
  11820. (list org-scheduled-string org-deadline-string))))
  11821. (while (re-search-forward org-ts-regexp end t)
  11822. (let* ((ts (match-string 0))
  11823. (planning? (org-at-planning-p))
  11824. (type (if (not planning?) "Plain:"
  11825. (save-excursion
  11826. (re-search-backward
  11827. planning-re (line-beginning-position) t)
  11828. (match-string 0)))))
  11829. (cond
  11830. ;; Ignore fake time-stamps (e.g., within comments).
  11831. ((not (org-at-timestamp-p 'agenda)))
  11832. ;; Time-stamps without a repeater are usually
  11833. ;; skipped. However, a SCHEDULED time-stamp without
  11834. ;; one is removed, as they are no longer relevant.
  11835. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11836. ts))
  11837. (when (equal type org-scheduled-string)
  11838. (org-remove-timestamp-with-keyword type)))
  11839. (t
  11840. (let ((n (string-to-number (match-string 2 ts)))
  11841. (what (match-string 3 ts)))
  11842. (when (equal what "w") (setq n (* n 7) what "d"))
  11843. (when (and (equal what "h")
  11844. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11845. ts)))
  11846. (user-error
  11847. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11848. has been set"
  11849. n))
  11850. ;; Preparation, see if we need to modify the start
  11851. ;; date for the change.
  11852. (when (match-end 1)
  11853. (let ((time (save-match-data
  11854. (org-time-string-to-time ts))))
  11855. (cond
  11856. ((equal (match-string 1 ts) ".")
  11857. ;; Shift starting date to today
  11858. (org-timestamp-change
  11859. (- (org-today) (time-to-days time))
  11860. 'day))
  11861. ((equal (match-string 1 ts) "+")
  11862. (let ((nshiftmax 10)
  11863. (nshift 0))
  11864. (while (or (= nshift 0)
  11865. (not (time-less-p (current-time) time)))
  11866. (when (= (cl-incf nshift) nshiftmax)
  11867. (or (y-or-n-p
  11868. (format "%d repeater intervals were not \
  11869. enough to shift date past today. Continue? "
  11870. nshift))
  11871. (user-error "Abort")))
  11872. (org-timestamp-change n (cdr (assoc what whata)))
  11873. (org-in-regexp org-ts-regexp3)
  11874. (setq ts (match-string 1))
  11875. (setq time
  11876. (save-match-data
  11877. (org-time-string-to-time ts)))))
  11878. (org-timestamp-change (- n) (cdr (assoc what whata)))
  11879. ;; Rematch, so that we have everything in place
  11880. ;; for the real shift.
  11881. (org-in-regexp org-ts-regexp3)
  11882. (setq ts (match-string 1))
  11883. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  11884. ts)))))
  11885. (save-excursion
  11886. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  11887. (setq msg
  11888. (concat
  11889. msg type " " org-last-changed-timestamp " "))))))))
  11890. (setq org-log-post-message msg)
  11891. (message "%s" msg))
  11892. (set-marker end nil))))
  11893. (defun org-show-todo-tree (arg)
  11894. "Make a compact tree which shows all headlines marked with TODO.
  11895. The tree will show the lines where the regexp matches, and all higher
  11896. headlines above the match.
  11897. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  11898. With a numeric prefix N, construct a sparse tree for the Nth element
  11899. of `org-todo-keywords-1'."
  11900. (interactive "P")
  11901. (let ((case-fold-search nil)
  11902. (kwd-re
  11903. (cond ((null arg) org-not-done-regexp)
  11904. ((equal arg '(4))
  11905. (let ((kwd
  11906. (completing-read "Keyword (or KWD1|KWD2|...): "
  11907. (mapcar #'list org-todo-keywords-1))))
  11908. (concat "\\("
  11909. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  11910. "\\)\\>")))
  11911. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  11912. (regexp-quote (nth (1- (prefix-numeric-value arg))
  11913. org-todo-keywords-1)))
  11914. (t (user-error "Invalid prefix argument: %s" arg)))))
  11915. (message "%d TODO entries found"
  11916. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  11917. (defun org--deadline-or-schedule (arg type time)
  11918. "Insert DEADLINE or SCHEDULE information in current entry.
  11919. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  11920. `org-schedule' for information about ARG and TIME arguments."
  11921. (let* ((deadline? (eq type 'deadline))
  11922. (keyword (if deadline? org-deadline-string org-scheduled-string))
  11923. (log (if deadline? org-log-redeadline org-log-reschedule))
  11924. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  11925. (old-date-time (and old-date (org-time-string-to-time old-date)))
  11926. ;; Save repeater cookie from either TIME or current scheduled
  11927. ;; time stamp. We are going to insert it back at the end of
  11928. ;; the process.
  11929. (repeater (or (and (org-string-nw-p time)
  11930. ;; We use `org-repeat-re' because we need
  11931. ;; to tell the difference between a real
  11932. ;; repeater and a time delta, e.g. "+2d".
  11933. (string-match org-repeat-re time)
  11934. (match-string 1 time))
  11935. (and (org-string-nw-p old-date)
  11936. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  11937. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  11938. old-date)
  11939. (match-string 1 old-date)))))
  11940. (pcase arg
  11941. (`(4)
  11942. (when (and old-date log)
  11943. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  11944. nil old-date log))
  11945. (org-remove-timestamp-with-keyword keyword)
  11946. (message (if deadline? "Item no longer has a deadline."
  11947. "Item is no longer scheduled.")))
  11948. (`(16)
  11949. (save-excursion
  11950. (org-back-to-heading t)
  11951. (let ((regexp (if deadline? org-deadline-time-regexp
  11952. org-scheduled-time-regexp)))
  11953. (if (not (re-search-forward regexp (line-end-position 2) t))
  11954. (user-error (if deadline? "No deadline information to update"
  11955. "No scheduled information to update"))
  11956. (let* ((rpl0 (match-string 1))
  11957. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  11958. (msg (if deadline? "Warn starting from" "Delay until")))
  11959. (replace-match
  11960. (concat keyword
  11961. " <" rpl
  11962. (format " -%dd"
  11963. (abs (- (time-to-days
  11964. (save-match-data
  11965. (org-read-date
  11966. nil t nil msg old-date-time)))
  11967. (time-to-days old-date-time))))
  11968. ">") t t))))))
  11969. (_
  11970. (org-add-planning-info type time 'closed)
  11971. (when (and old-date
  11972. log
  11973. (not (equal old-date org-last-inserted-timestamp)))
  11974. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  11975. org-last-inserted-timestamp
  11976. old-date
  11977. log))
  11978. (when repeater
  11979. (save-excursion
  11980. (org-back-to-heading t)
  11981. (when (re-search-forward
  11982. (concat keyword " " org-last-inserted-timestamp)
  11983. (line-end-position 2)
  11984. t)
  11985. (goto-char (1- (match-end 0)))
  11986. (insert " " repeater)
  11987. (setq org-last-inserted-timestamp
  11988. (concat (substring org-last-inserted-timestamp 0 -1)
  11989. " " repeater
  11990. (substring org-last-inserted-timestamp -1))))))
  11991. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  11992. org-last-inserted-timestamp)))))
  11993. (defun org-deadline (arg &optional time)
  11994. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  11995. With one universal prefix argument, remove any deadline from the item.
  11996. With two universal prefix arguments, prompt for a warning delay.
  11997. With argument TIME, set the deadline at the corresponding date. TIME
  11998. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  11999. (interactive "P")
  12000. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12001. (org-map-entries
  12002. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12003. nil
  12004. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12005. 'region-start-level
  12006. 'region)
  12007. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12008. (org--deadline-or-schedule arg 'deadline time)))
  12009. (defun org-schedule (arg &optional time)
  12010. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12011. With one universal prefix argument, remove any scheduling date from the item.
  12012. With two universal prefix arguments, prompt for a delay cookie.
  12013. With argument TIME, scheduled at the corresponding date. TIME can
  12014. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12015. (interactive "P")
  12016. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12017. (org-map-entries
  12018. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12019. nil
  12020. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12021. 'region-start-level
  12022. 'region)
  12023. (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12024. (org--deadline-or-schedule arg 'scheduled time)))
  12025. (defun org-get-scheduled-time (pom &optional inherit)
  12026. "Get the scheduled time as a time tuple, of a format suitable
  12027. for calling org-schedule with, or if there is no scheduling,
  12028. returns nil."
  12029. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12030. (when time
  12031. (apply 'encode-time (org-parse-time-string time)))))
  12032. (defun org-get-deadline-time (pom &optional inherit)
  12033. "Get the deadline as a time tuple, of a format suitable for
  12034. calling org-deadline with, or if there is no scheduling, returns
  12035. nil."
  12036. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12037. (when time
  12038. (apply 'encode-time (org-parse-time-string time)))))
  12039. (defun org-remove-timestamp-with-keyword (keyword)
  12040. "Remove all time stamps with KEYWORD in the current entry."
  12041. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12042. beg)
  12043. (save-excursion
  12044. (org-back-to-heading t)
  12045. (setq beg (point))
  12046. (outline-next-heading)
  12047. (while (re-search-backward re beg t)
  12048. (replace-match "")
  12049. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12050. (equal (char-before) ?\ ))
  12051. (backward-delete-char 1)
  12052. (when (string-match "^[ \t]*$" (buffer-substring
  12053. (point-at-bol) (point-at-eol)))
  12054. (delete-region (point-at-bol)
  12055. (min (point-max) (1+ (point-at-eol))))))))))
  12056. (defvar org-time-was-given) ; dynamically scoped parameter
  12057. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12058. (defun org-at-planning-p ()
  12059. "Non-nil when point is on a planning info line."
  12060. ;; This is as accurate and faster than `org-element-at-point' since
  12061. ;; planning info location is fixed in the section.
  12062. (org-with-wide-buffer
  12063. (beginning-of-line)
  12064. (and (looking-at-p org-planning-line-re)
  12065. (eq (point)
  12066. (ignore-errors
  12067. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12068. (org-back-to-heading t)
  12069. (org-with-limited-levels (org-back-to-heading t)))
  12070. (line-beginning-position 2))))))
  12071. (defun org-add-planning-info (what &optional time &rest remove)
  12072. "Insert new timestamp with keyword in the planning line.
  12073. WHAT indicates what kind of time stamp to add. It is a symbol
  12074. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12075. the time to use. If none is given, the user is prompted for
  12076. a date. REMOVE indicates what kind of entries to remove. An old
  12077. WHAT entry will also be removed."
  12078. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12079. (catch 'exit
  12080. (when (and (memq what '(scheduled deadline))
  12081. (or (not time)
  12082. (and (stringp time)
  12083. (string-match "^[-+]+[0-9]" time))))
  12084. ;; Try to get a default date/time from existing timestamp
  12085. (save-excursion
  12086. (org-back-to-heading t)
  12087. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12088. (when (re-search-forward (if (eq what 'scheduled)
  12089. org-scheduled-time-regexp
  12090. org-deadline-time-regexp)
  12091. end t)
  12092. (setq ts (match-string 1)
  12093. default-time (apply 'encode-time (org-parse-time-string ts))
  12094. default-input (and ts (org-get-compact-tod ts)))))))
  12095. (when what
  12096. (setq time
  12097. (if (stringp time)
  12098. ;; This is a string (relative or absolute), set
  12099. ;; proper date.
  12100. (apply #'encode-time
  12101. (org-read-date-analyze
  12102. time default-time (decode-time default-time)))
  12103. ;; If necessary, get the time from the user
  12104. (or time (org-read-date nil 'to-time nil nil
  12105. default-time default-input)))))
  12106. (org-with-wide-buffer
  12107. (org-back-to-heading t)
  12108. (forward-line)
  12109. (unless (bolp) (insert "\n"))
  12110. (cond ((looking-at-p org-planning-line-re)
  12111. ;; Move to current indentation.
  12112. (skip-chars-forward " \t")
  12113. ;; Check if we have to remove something.
  12114. (dolist (type (if what (cons what remove) remove))
  12115. (save-excursion
  12116. (when (re-search-forward
  12117. (cl-case type
  12118. (closed org-closed-time-regexp)
  12119. (deadline org-deadline-time-regexp)
  12120. (scheduled org-scheduled-time-regexp)
  12121. (otherwise
  12122. (error "Invalid planning type: %s" type)))
  12123. (line-end-position) t)
  12124. ;; Delete until next keyword or end of line.
  12125. (delete-region
  12126. (match-beginning 0)
  12127. (if (re-search-forward org-keyword-time-not-clock-regexp
  12128. (line-end-position)
  12129. t)
  12130. (match-beginning 0)
  12131. (line-end-position))))))
  12132. ;; If there is nothing more to add and no more keyword
  12133. ;; is left, remove the line completely.
  12134. (if (and (looking-at-p "[ \t]*$") (not what))
  12135. (delete-region (line-beginning-position)
  12136. (line-beginning-position 2))
  12137. ;; If we removed last keyword, do not leave trailing
  12138. ;; white space at the end of line.
  12139. (let ((p (point)))
  12140. (save-excursion
  12141. (end-of-line)
  12142. (unless (= (skip-chars-backward " \t" p) 0)
  12143. (delete-region (point) (line-end-position)))))))
  12144. ((not what) (throw 'exit nil)) ; Nothing to do.
  12145. (t (insert-before-markers "\n")
  12146. (backward-char 1)
  12147. (when org-adapt-indentation
  12148. (indent-to-column (1+ (org-outline-level))))))
  12149. (when what
  12150. ;; Insert planning keyword.
  12151. (insert (cl-case what
  12152. (closed org-closed-string)
  12153. (deadline org-deadline-string)
  12154. (scheduled org-scheduled-string)
  12155. (otherwise (error "Invalid planning type: %s" what)))
  12156. " ")
  12157. ;; Insert associated timestamp.
  12158. (let ((ts (org-insert-time-stamp
  12159. time
  12160. (or org-time-was-given
  12161. (and (eq what 'closed) org-log-done-with-time))
  12162. (eq what 'closed)
  12163. nil nil (list org-end-time-was-given))))
  12164. (unless (eolp) (insert " "))
  12165. ts))))))
  12166. (defvar org-log-note-marker (make-marker)
  12167. "Marker pointing at the entry where the note is to be inserted.")
  12168. (defvar org-log-note-purpose nil)
  12169. (defvar org-log-note-state nil)
  12170. (defvar org-log-note-previous-state nil)
  12171. (defvar org-log-note-extra nil)
  12172. (defvar org-log-note-window-configuration nil)
  12173. (defvar org-log-note-return-to (make-marker))
  12174. (defvar org-log-note-effective-time nil
  12175. "Remembered current time so that dynamically scoped
  12176. `org-extend-today-until' affects timestamps in state change log")
  12177. (defvar org-log-post-message nil
  12178. "Message to be displayed after a log note has been stored.
  12179. The auto-repeater uses this.")
  12180. (defun org-add-note ()
  12181. "Add a note to the current entry.
  12182. This is done in the same way as adding a state change note."
  12183. (interactive)
  12184. (org-add-log-setup 'note))
  12185. (defun org-log-beginning (&optional create)
  12186. "Return expected start of log notes in current entry.
  12187. When optional argument CREATE is non-nil, the function creates
  12188. a drawer to store notes, if necessary. Returned position ignores
  12189. narrowing."
  12190. (org-with-wide-buffer
  12191. (let ((drawer (org-log-into-drawer)))
  12192. (cond
  12193. (drawer
  12194. (org-end-of-meta-data)
  12195. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12196. (end (if (org-at-heading-p) (point)
  12197. (save-excursion (outline-next-heading) (point))))
  12198. (case-fold-search t))
  12199. (catch 'exit
  12200. ;; Try to find existing drawer.
  12201. (while (re-search-forward regexp end t)
  12202. (let ((element (org-element-at-point)))
  12203. (when (eq (org-element-type element) 'drawer)
  12204. (let ((cend (org-element-property :contents-end element)))
  12205. (when (and (not org-log-states-order-reversed) cend)
  12206. (goto-char cend)))
  12207. (throw 'exit nil))))
  12208. ;; No drawer found. Create one, if permitted.
  12209. (when create
  12210. (unless (bolp) (insert "\n"))
  12211. (let ((beg (point)))
  12212. (insert ":" drawer ":\n:END:\n")
  12213. (org-indent-region beg (point)))
  12214. (end-of-line -1)))))
  12215. (t
  12216. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12217. (skip-chars-forward " \t\n")
  12218. (beginning-of-line)
  12219. (unless org-log-states-order-reversed
  12220. (org-skip-over-state-notes)
  12221. (skip-chars-backward " \t\n")
  12222. (forward-line)))))
  12223. (if (bolp) (point) (line-beginning-position 2))))
  12224. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12225. "Set up the post command hook to take a note.
  12226. If this is about to TODO state change, the new state is expected in STATE.
  12227. HOW is an indicator what kind of note should be created.
  12228. EXTRA is additional text that will be inserted into the notes buffer."
  12229. (move-marker org-log-note-marker (point))
  12230. (setq org-log-note-purpose purpose
  12231. org-log-note-state state
  12232. org-log-note-previous-state prev-state
  12233. org-log-note-how how
  12234. org-log-note-extra extra
  12235. org-log-note-effective-time (org-current-effective-time))
  12236. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12237. (defun org-skip-over-state-notes ()
  12238. "Skip past the list of State notes in an entry."
  12239. (when (ignore-errors (goto-char (org-in-item-p)))
  12240. (let* ((struct (org-list-struct))
  12241. (prevs (org-list-prevs-alist struct))
  12242. (regexp
  12243. (concat "[ \t]*- +"
  12244. (replace-regexp-in-string
  12245. " +" " +"
  12246. (org-replace-escapes
  12247. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12248. `(("%d" . ,org-ts-regexp-inactive)
  12249. ("%D" . ,org-ts-regexp)
  12250. ("%s" . "\"\\S-+\"")
  12251. ("%S" . "\"\\S-+\"")
  12252. ("%t" . ,org-ts-regexp-inactive)
  12253. ("%T" . ,org-ts-regexp)
  12254. ("%u" . ".*?")
  12255. ("%U" . ".*?")))))))
  12256. (while (looking-at-p regexp)
  12257. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12258. (org-list-get-item-end (point) struct)))))))
  12259. (defun org-add-log-note (&optional _purpose)
  12260. "Pop up a window for taking a note, and add this note later."
  12261. (remove-hook 'post-command-hook 'org-add-log-note)
  12262. (setq org-log-note-window-configuration (current-window-configuration))
  12263. (delete-other-windows)
  12264. (move-marker org-log-note-return-to (point))
  12265. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12266. (goto-char org-log-note-marker)
  12267. (org-switch-to-buffer-other-window "*Org Note*")
  12268. (erase-buffer)
  12269. (if (memq org-log-note-how '(time state))
  12270. (let (current-prefix-arg) (org-store-log-note))
  12271. (let ((org-inhibit-startup t)) (org-mode))
  12272. (insert (format "# Insert note for %s.
  12273. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12274. (cond
  12275. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12276. ((eq org-log-note-purpose 'done) "closed todo item")
  12277. ((eq org-log-note-purpose 'state)
  12278. (format "state change from \"%s\" to \"%s\""
  12279. (or org-log-note-previous-state "")
  12280. (or org-log-note-state "")))
  12281. ((eq org-log-note-purpose 'reschedule)
  12282. "rescheduling")
  12283. ((eq org-log-note-purpose 'delschedule)
  12284. "no longer scheduled")
  12285. ((eq org-log-note-purpose 'redeadline)
  12286. "changing deadline")
  12287. ((eq org-log-note-purpose 'deldeadline)
  12288. "removing deadline")
  12289. ((eq org-log-note-purpose 'refile)
  12290. "refiling")
  12291. ((eq org-log-note-purpose 'note)
  12292. "this entry")
  12293. (t (error "This should not happen")))))
  12294. (when org-log-note-extra (insert org-log-note-extra))
  12295. (setq-local org-finish-function 'org-store-log-note)
  12296. (run-hooks 'org-log-buffer-setup-hook)))
  12297. (defvar org-note-abort nil) ; dynamically scoped
  12298. (defun org-store-log-note ()
  12299. "Finish taking a log note, and insert it to where it belongs."
  12300. (let ((txt (prog1 (buffer-string)
  12301. (kill-buffer)))
  12302. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12303. lines)
  12304. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12305. (setq txt (replace-match "" t t txt)))
  12306. (when (string-match "\\s-+\\'" txt)
  12307. (setq txt (replace-match "" t t txt)))
  12308. (setq lines (org-split-string txt "\n"))
  12309. (when (org-string-nw-p note)
  12310. (setq note
  12311. (org-replace-escapes
  12312. note
  12313. (list (cons "%u" (user-login-name))
  12314. (cons "%U" user-full-name)
  12315. (cons "%t" (format-time-string
  12316. (org-time-stamp-format 'long 'inactive)
  12317. org-log-note-effective-time))
  12318. (cons "%T" (format-time-string
  12319. (org-time-stamp-format 'long nil)
  12320. org-log-note-effective-time))
  12321. (cons "%d" (format-time-string
  12322. (org-time-stamp-format nil 'inactive)
  12323. org-log-note-effective-time))
  12324. (cons "%D" (format-time-string
  12325. (org-time-stamp-format nil nil)
  12326. org-log-note-effective-time))
  12327. (cons "%s" (cond
  12328. ((not org-log-note-state) "")
  12329. ((string-match-p org-ts-regexp
  12330. org-log-note-state)
  12331. (format "\"[%s]\""
  12332. (substring org-log-note-state 1 -1)))
  12333. (t (format "\"%s\"" org-log-note-state))))
  12334. (cons "%S"
  12335. (cond
  12336. ((not org-log-note-previous-state) "")
  12337. ((string-match-p org-ts-regexp
  12338. org-log-note-previous-state)
  12339. (format "\"[%s]\""
  12340. (substring
  12341. org-log-note-previous-state 1 -1)))
  12342. (t (format "\"%s\""
  12343. org-log-note-previous-state)))))))
  12344. (when lines (setq note (concat note " \\\\")))
  12345. (push note lines))
  12346. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12347. (with-current-buffer (marker-buffer org-log-note-marker)
  12348. (org-with-wide-buffer
  12349. ;; Find location for the new note.
  12350. (goto-char org-log-note-marker)
  12351. (set-marker org-log-note-marker nil)
  12352. ;; Note associated to a clock is to be located right after
  12353. ;; the clock. Do not move point.
  12354. (unless (eq org-log-note-purpose 'clock-out)
  12355. (goto-char (org-log-beginning t)))
  12356. ;; Make sure point is at the beginning of an empty line.
  12357. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12358. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12359. ;; In an existing list, add a new item at the top level.
  12360. ;; Otherwise, indent line like a regular one.
  12361. (let ((itemp (org-in-item-p)))
  12362. (if itemp
  12363. (indent-line-to
  12364. (let ((struct (save-excursion
  12365. (goto-char itemp) (org-list-struct))))
  12366. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12367. (org-indent-line)))
  12368. (insert (org-list-bullet-string "-") (pop lines))
  12369. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12370. (dolist (line lines)
  12371. (insert "\n")
  12372. (indent-line-to ind)
  12373. (insert line)))
  12374. (message "Note stored")
  12375. (org-back-to-heading t)
  12376. (org-cycle-hide-drawers 'children))
  12377. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12378. ;; from within `org-add-log-note' because `buffer-undo-list'
  12379. ;; is then modified outside of `org-with-remote-undo'.
  12380. (when (eq this-command 'org-agenda-todo)
  12381. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12382. ;; Don't add undo information when called from `org-agenda-todo'.
  12383. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12384. (set-window-configuration org-log-note-window-configuration)
  12385. (with-current-buffer (marker-buffer org-log-note-return-to)
  12386. (goto-char org-log-note-return-to))
  12387. (move-marker org-log-note-return-to nil)
  12388. (when org-log-post-message (message "%s" org-log-post-message))))
  12389. (defun org-remove-empty-drawer-at (pos)
  12390. "Remove an empty drawer at position POS.
  12391. POS may also be a marker."
  12392. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12393. (org-with-wide-buffer
  12394. (goto-char pos)
  12395. (let ((drawer (org-element-at-point)))
  12396. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12397. (not (org-element-property :contents-begin drawer)))
  12398. (delete-region (org-element-property :begin drawer)
  12399. (progn (goto-char (org-element-property :end drawer))
  12400. (skip-chars-backward " \r\t\n")
  12401. (forward-line)
  12402. (point))))))))
  12403. (defvar org-ts-type nil)
  12404. (defun org-sparse-tree (&optional arg type)
  12405. "Create a sparse tree, prompt for the details.
  12406. This command can create sparse trees. You first need to select the type
  12407. of match used to create the tree:
  12408. t Show all TODO entries.
  12409. T Show entries with a specific TODO keyword.
  12410. m Show entries selected by a tags/property match.
  12411. p Enter a property name and its value (both with completion on existing
  12412. names/values) and show entries with that property.
  12413. r Show entries matching a regular expression (`/' can be used as well).
  12414. b Show deadlines and scheduled items before a date.
  12415. a Show deadlines and scheduled items after a date.
  12416. d Show deadlines due within `org-deadline-warning-days'.
  12417. D Show deadlines and scheduled items between a date range."
  12418. (interactive "P")
  12419. (setq type (or type org-sparse-tree-default-date-type))
  12420. (setq org-ts-type type)
  12421. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12422. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12423. \[c]ycle through date types: %s"
  12424. (cl-case type
  12425. (all "all timestamps")
  12426. (scheduled "only scheduled")
  12427. (deadline "only deadline")
  12428. (active "only active timestamps")
  12429. (inactive "only inactive timestamps")
  12430. (closed "with a closed time-stamp")
  12431. (otherwise "scheduled/deadline")))
  12432. (let ((answer (read-char-exclusive)))
  12433. (cl-case answer
  12434. (?c
  12435. (org-sparse-tree
  12436. arg
  12437. (cadr
  12438. (memq type '(nil all scheduled deadline active inactive closed)))))
  12439. (?d (call-interactively 'org-check-deadlines))
  12440. (?b (call-interactively 'org-check-before-date))
  12441. (?a (call-interactively 'org-check-after-date))
  12442. (?D (call-interactively 'org-check-dates-range))
  12443. (?t (call-interactively 'org-show-todo-tree))
  12444. (?T (org-show-todo-tree '(4)))
  12445. (?m (call-interactively 'org-match-sparse-tree))
  12446. ((?p ?P)
  12447. (let* ((kwd (completing-read
  12448. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12449. (value (completing-read
  12450. "Value: " (mapcar #'list (org-property-values kwd)))))
  12451. (unless (string-match "\\`{.*}\\'" value)
  12452. (setq value (concat "\"" value "\"")))
  12453. (org-match-sparse-tree arg (concat kwd "=" value))))
  12454. ((?r ?R ?/) (call-interactively 'org-occur))
  12455. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12456. (defvar-local org-occur-highlights nil
  12457. "List of overlays used for occur matches.")
  12458. (defvar-local org-occur-parameters nil
  12459. "Parameters of the active org-occur calls.
  12460. This is a list, each call to org-occur pushes as cons cell,
  12461. containing the regular expression and the callback, onto the list.
  12462. The list can contain several entries if `org-occur' has been called
  12463. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12464. will only contain one set of parameters. When the highlights are
  12465. removed (for example with `C-c C-c', or with the next edit (depending
  12466. on `org-remove-highlights-with-change'), this variable is emptied
  12467. as well.")
  12468. (defun org-occur (regexp &optional keep-previous callback)
  12469. "Make a compact tree which shows all matches of REGEXP.
  12470. The tree will show the lines where the regexp matches, and any other context
  12471. defined in `org-show-context-detail', which see.
  12472. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12473. done by a previous call to `org-occur' will be kept, to allow stacking of
  12474. calls to this command.
  12475. Optional argument CALLBACK can be a function of no argument. In this case,
  12476. it is called with point at the end of the match, match data being set
  12477. accordingly. Current match is shown only if the return value is non-nil.
  12478. The function must neither move point nor alter narrowing."
  12479. (interactive "sRegexp: \nP")
  12480. (when (equal regexp "")
  12481. (user-error "Regexp cannot be empty"))
  12482. (unless keep-previous
  12483. (org-remove-occur-highlights nil nil t))
  12484. (push (cons regexp callback) org-occur-parameters)
  12485. (let ((cnt 0))
  12486. (save-excursion
  12487. (goto-char (point-min))
  12488. (when (or (not keep-previous) ; do not want to keep
  12489. (not org-occur-highlights)) ; no previous matches
  12490. ;; hide everything
  12491. (org-overview))
  12492. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12493. (isearch-no-upper-case-p regexp t)
  12494. org-occur-case-fold-search)))
  12495. (while (re-search-forward regexp nil t)
  12496. (when (or (not callback)
  12497. (save-match-data (funcall callback)))
  12498. (setq cnt (1+ cnt))
  12499. (when org-highlight-sparse-tree-matches
  12500. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12501. (org-show-context 'occur-tree)))))
  12502. (when org-remove-highlights-with-change
  12503. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12504. nil 'local))
  12505. (unless org-sparse-tree-open-archived-trees
  12506. (org-hide-archived-subtrees (point-min) (point-max)))
  12507. (run-hooks 'org-occur-hook)
  12508. (when (called-interactively-p 'interactive)
  12509. (message "%d match(es) for regexp %s" cnt regexp))
  12510. cnt))
  12511. (defun org-occur-next-match (&optional n _reset)
  12512. "Function for `next-error-function' to find sparse tree matches.
  12513. N is the number of matches to move, when negative move backwards.
  12514. This function always goes back to the starting point when no
  12515. match is found."
  12516. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12517. (search-func (if (< n 0)
  12518. 'previous-single-char-property-change
  12519. 'next-single-char-property-change))
  12520. (n (abs n))
  12521. (pos (point))
  12522. p1)
  12523. (catch 'exit
  12524. (while (setq p1 (funcall search-func (point) 'org-type))
  12525. (when (equal p1 limit)
  12526. (goto-char pos)
  12527. (user-error "No more matches"))
  12528. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12529. (setq n (1- n))
  12530. (when (= n 0)
  12531. (goto-char p1)
  12532. (throw 'exit (point))))
  12533. (goto-char p1))
  12534. (goto-char p1)
  12535. (user-error "No more matches"))))
  12536. (defun org-show-context (&optional key)
  12537. "Make sure point and context are visible.
  12538. Optional argument KEY, when non-nil, is a symbol. See
  12539. `org-show-context-detail' for allowed values and how much is to
  12540. be shown."
  12541. (org-show-set-visibility
  12542. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12543. ((cdr (assq key org-show-context-detail)))
  12544. (t (cdr (assq 'default org-show-context-detail))))))
  12545. (defun org-show-set-visibility (detail)
  12546. "Set visibility around point according to DETAIL.
  12547. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12548. `tree', `canonical' or t. See `org-show-context-detail' for more
  12549. information."
  12550. ;; Show current heading and possibly its entry, following headline
  12551. ;; or all children.
  12552. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12553. (org-flag-heading nil)
  12554. (org-show-entry)
  12555. ;; If point is hidden within a drawer or a block, make sure to
  12556. ;; expose it.
  12557. (dolist (o (overlays-at (point)))
  12558. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12559. (delete-overlay o)))
  12560. (unless (org-before-first-heading-p)
  12561. (org-with-limited-levels
  12562. (cl-case detail
  12563. ((tree canonical t) (org-show-children))
  12564. ((nil minimal ancestors))
  12565. (t (save-excursion
  12566. (outline-next-heading)
  12567. (org-flag-heading nil)))))))
  12568. ;; Show all siblings.
  12569. (when (eq detail 'lineage) (org-show-siblings))
  12570. ;; Show ancestors, possibly with their children.
  12571. (when (memq detail '(ancestors lineage tree canonical t))
  12572. (save-excursion
  12573. (while (org-up-heading-safe)
  12574. (org-flag-heading nil)
  12575. (when (memq detail '(canonical t)) (org-show-entry))
  12576. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12577. (defvar org-reveal-start-hook nil
  12578. "Hook run before revealing a location.")
  12579. (defun org-reveal (&optional siblings)
  12580. "Show current entry, hierarchy above it, and the following headline.
  12581. This can be used to show a consistent set of context around
  12582. locations exposed with `org-show-context'.
  12583. With optional argument SIBLINGS, on each level of the hierarchy all
  12584. siblings are shown. This repairs the tree structure to what it would
  12585. look like when opened with hierarchical calls to `org-cycle'.
  12586. With a \\[universal-argument] \\[universal-argument] prefix, \
  12587. go to the parent and show the entire tree."
  12588. (interactive "P")
  12589. (run-hooks 'org-reveal-start-hook)
  12590. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12591. ((equal siblings '(16))
  12592. (save-excursion
  12593. (when (org-up-heading-safe)
  12594. (org-show-subtree)
  12595. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12596. (t (org-show-set-visibility 'lineage))))
  12597. (defun org-highlight-new-match (beg end)
  12598. "Highlight from BEG to END and mark the highlight is an occur headline."
  12599. (let ((ov (make-overlay beg end)))
  12600. (overlay-put ov 'face 'secondary-selection)
  12601. (overlay-put ov 'org-type 'org-occur)
  12602. (push ov org-occur-highlights)))
  12603. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12604. "Remove the occur highlights from the buffer.
  12605. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12606. from the `before-change-functions' in the current buffer."
  12607. (interactive)
  12608. (unless org-inhibit-highlight-removal
  12609. (mapc #'delete-overlay org-occur-highlights)
  12610. (setq org-occur-highlights nil)
  12611. (setq org-occur-parameters nil)
  12612. (unless noremove
  12613. (remove-hook 'before-change-functions
  12614. 'org-remove-occur-highlights 'local))))
  12615. ;;;; Priorities
  12616. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12617. "Regular expression matching the priority indicator.")
  12618. (defvar org-remove-priority-next-time nil)
  12619. (defun org-priority-up ()
  12620. "Increase the priority of the current item."
  12621. (interactive)
  12622. (org-priority 'up))
  12623. (defun org-priority-down ()
  12624. "Decrease the priority of the current item."
  12625. (interactive)
  12626. (org-priority 'down))
  12627. (defun org-priority (&optional action _show)
  12628. "Change the priority of an item.
  12629. ACTION can be `set', `up', `down', or a character."
  12630. (interactive "P")
  12631. (if (equal action '(4))
  12632. (org-show-priority)
  12633. (unless org-enable-priority-commands
  12634. (user-error "Priority commands are disabled"))
  12635. (setq action (or action 'set))
  12636. (let (current new news have remove)
  12637. (save-excursion
  12638. (org-back-to-heading t)
  12639. (when (looking-at org-priority-regexp)
  12640. (setq current (string-to-char (match-string 2))
  12641. have t))
  12642. (cond
  12643. ((eq action 'remove)
  12644. (setq remove t new ?\ ))
  12645. ((or (eq action 'set)
  12646. (integerp action))
  12647. (if (not (eq action 'set))
  12648. (setq new action)
  12649. (message "Priority %c-%c, SPC to remove: "
  12650. org-highest-priority org-lowest-priority)
  12651. (save-match-data
  12652. (setq new (read-char-exclusive))))
  12653. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12654. (= (upcase org-lowest-priority) org-lowest-priority))
  12655. (setq new (upcase new)))
  12656. (cond ((equal new ?\ ) (setq remove t))
  12657. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12658. (user-error "Priority must be between `%c' and `%c'"
  12659. org-highest-priority org-lowest-priority))))
  12660. ((eq action 'up)
  12661. (setq new (if have
  12662. (1- current) ; normal cycling
  12663. ;; last priority was empty
  12664. (if (eq last-command this-command)
  12665. org-lowest-priority ; wrap around empty to lowest
  12666. ;; default
  12667. (if org-priority-start-cycle-with-default
  12668. org-default-priority
  12669. (1- org-default-priority))))))
  12670. ((eq action 'down)
  12671. (setq new (if have
  12672. (1+ current) ; normal cycling
  12673. ;; last priority was empty
  12674. (if (eq last-command this-command)
  12675. org-highest-priority ; wrap around empty to highest
  12676. ;; default
  12677. (if org-priority-start-cycle-with-default
  12678. org-default-priority
  12679. (1+ org-default-priority))))))
  12680. (t (user-error "Invalid action")))
  12681. (when (or (< (upcase new) org-highest-priority)
  12682. (> (upcase new) org-lowest-priority))
  12683. (if (and (memq action '(up down))
  12684. (not have) (not (eq last-command this-command)))
  12685. ;; `new' is from default priority
  12686. (error
  12687. "The default can not be set, see `org-default-priority' why")
  12688. ;; normal cycling: `new' is beyond highest/lowest priority
  12689. ;; and is wrapped around to the empty priority
  12690. (setq remove t)))
  12691. (setq news (format "%c" new))
  12692. (if have
  12693. (if remove
  12694. (replace-match "" t t nil 1)
  12695. (replace-match news t t nil 2))
  12696. (if remove
  12697. (user-error "No priority cookie found in line")
  12698. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12699. (if (match-end 2)
  12700. (progn
  12701. (goto-char (match-end 2))
  12702. (insert " [#" news "]"))
  12703. (goto-char (match-beginning 3))
  12704. (insert "[#" news "] "))))
  12705. (org-set-tags nil 'align))
  12706. (if remove
  12707. (message "Priority removed")
  12708. (message "Priority of current item set to %s" news)))))
  12709. (defun org-show-priority ()
  12710. "Show the priority of the current item.
  12711. This priority is composed of the main priority given with the [#A] cookies,
  12712. and by additional input from the age of a schedules or deadline entry."
  12713. (interactive)
  12714. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12715. (org-get-at-bol 'priority)
  12716. (save-excursion
  12717. (save-match-data
  12718. (beginning-of-line)
  12719. (and (looking-at org-heading-regexp)
  12720. (org-get-priority (match-string 0))))))))
  12721. (message "Priority is %d" (if pri pri -1000))))
  12722. (defun org-get-priority (s)
  12723. "Find priority cookie and return priority."
  12724. (save-match-data
  12725. (if (functionp org-get-priority-function)
  12726. (funcall org-get-priority-function)
  12727. (if (not (string-match org-priority-regexp s))
  12728. (* 1000 (- org-lowest-priority org-default-priority))
  12729. (* 1000 (- org-lowest-priority
  12730. (string-to-char (match-string 2 s))))))))
  12731. ;;;; Tags
  12732. (defvar org-agenda-archives-mode)
  12733. (defvar org-map-continue-from nil
  12734. "Position from where mapping should continue.
  12735. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12736. (defvar org-scanner-tags nil
  12737. "The current tag list while the tags scanner is running.")
  12738. (defvar org-trust-scanner-tags nil
  12739. "Should `org-get-tags-at' use the tags for the scanner.
  12740. This is for internal dynamical scoping only.
  12741. When this is non-nil, the function `org-get-tags-at' will return the value
  12742. of `org-scanner-tags' instead of building the list by itself. This
  12743. can lead to large speed-ups when the tags scanner is used in a file with
  12744. many entries, and when the list of tags is retrieved, for example to
  12745. obtain a list of properties. Building the tags list for each entry in such
  12746. a file becomes an N^2 operation - but with this variable set, it scales
  12747. as N.")
  12748. (defvar org--matcher-tags-todo-only nil)
  12749. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12750. "Scan headline tags with inheritance and produce output ACTION.
  12751. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12752. or `agenda' to produce an entry list for an agenda view. It can also be
  12753. a Lisp form or a function that should be called at each matched headline, in
  12754. this case the return value is a list of all return values from these calls.
  12755. MATCHER is a function accepting three arguments, returning
  12756. a non-nil value whenever a given set of tags qualifies a headline
  12757. for inclusion. See `org-make-tags-matcher' for more information.
  12758. As a special case, it can also be set to t (respectively nil) in
  12759. order to match all (respectively none) headline.
  12760. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12761. keyword are included in the output.
  12762. START-LEVEL can be a string with asterisks, reducing the scope to
  12763. headlines matching this string."
  12764. (require 'org-agenda)
  12765. (let* ((re (concat "^"
  12766. (if start-level
  12767. ;; Get the correct level to match
  12768. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12769. org-outline-regexp)
  12770. " *\\(\\<\\("
  12771. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12772. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12773. (props (list 'face 'default
  12774. 'done-face 'org-agenda-done
  12775. 'undone-face 'default
  12776. 'mouse-face 'highlight
  12777. 'org-not-done-regexp org-not-done-regexp
  12778. 'org-todo-regexp org-todo-regexp
  12779. 'org-complex-heading-regexp org-complex-heading-regexp
  12780. 'help-echo
  12781. (format "mouse-2 or RET jump to org file %s"
  12782. (abbreviate-file-name
  12783. (or (buffer-file-name (buffer-base-buffer))
  12784. (buffer-name (buffer-base-buffer)))))))
  12785. (org-map-continue-from nil)
  12786. lspos tags tags-list
  12787. (tags-alist (list (cons 0 org-file-tags)))
  12788. (llast 0) rtn rtn1 level category i txt
  12789. todo marker entry priority
  12790. ts-date ts-date-type ts-date-pair)
  12791. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12792. (setq action (list 'lambda nil action)))
  12793. (save-excursion
  12794. (goto-char (point-min))
  12795. (when (eq action 'sparse-tree)
  12796. (org-overview)
  12797. (org-remove-occur-highlights))
  12798. (while (let (case-fold-search)
  12799. (re-search-forward re nil t))
  12800. (setq org-map-continue-from nil)
  12801. (catch :skip
  12802. (setq todo
  12803. ;; TODO: is the 1-2 difference a bug?
  12804. (when (match-end 1) (match-string-no-properties 2))
  12805. tags (when (match-end 4) (match-string-no-properties 4)))
  12806. (goto-char (setq lspos (match-beginning 0)))
  12807. (setq level (org-reduced-level (org-outline-level))
  12808. category (org-get-category))
  12809. (when (eq action 'agenda)
  12810. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12811. ts-date (car ts-date-pair)
  12812. ts-date-type (cdr ts-date-pair)))
  12813. (setq i llast llast level)
  12814. ;; remove tag lists from same and sublevels
  12815. (while (>= i level)
  12816. (when (setq entry (assoc i tags-alist))
  12817. (setq tags-alist (delete entry tags-alist)))
  12818. (setq i (1- i)))
  12819. ;; add the next tags
  12820. (when tags
  12821. (setq tags (org-split-string tags ":")
  12822. tags-alist
  12823. (cons (cons level tags) tags-alist)))
  12824. ;; compile tags for current headline
  12825. (setq tags-list
  12826. (if org-use-tag-inheritance
  12827. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12828. tags)
  12829. org-scanner-tags tags-list)
  12830. (when org-use-tag-inheritance
  12831. (setcdr (car tags-alist)
  12832. (mapcar (lambda (x)
  12833. (setq x (copy-sequence x))
  12834. (org-add-prop-inherited x))
  12835. (cdar tags-alist))))
  12836. (when (and tags org-use-tag-inheritance
  12837. (or (not (eq t org-use-tag-inheritance))
  12838. org-tags-exclude-from-inheritance))
  12839. ;; Selective inheritance, remove uninherited ones.
  12840. (setcdr (car tags-alist)
  12841. (org-remove-uninherited-tags (cdar tags-alist))))
  12842. (when (and
  12843. ;; eval matcher only when the todo condition is OK
  12844. (and (or (not todo-only) (member todo org-not-done-keywords))
  12845. (if (functionp matcher)
  12846. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12847. (funcall matcher todo tags-list level))
  12848. matcher))
  12849. ;; Call the skipper, but return t if it does not
  12850. ;; skip, so that the `and' form continues evaluating.
  12851. (progn
  12852. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12853. t)
  12854. ;; Check if timestamps are deselecting this entry
  12855. (or (not todo-only)
  12856. (and (member todo org-not-done-keywords)
  12857. (or (not org-agenda-tags-todo-honor-ignore-options)
  12858. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12859. ;; select this headline
  12860. (cond
  12861. ((eq action 'sparse-tree)
  12862. (and org-highlight-sparse-tree-matches
  12863. (org-get-heading) (match-end 0)
  12864. (org-highlight-new-match
  12865. (match-beginning 1) (match-end 1)))
  12866. (org-show-context 'tags-tree))
  12867. ((eq action 'agenda)
  12868. (setq txt (org-agenda-format-item
  12869. ""
  12870. (concat
  12871. (if (eq org-tags-match-list-sublevels 'indented)
  12872. (make-string (1- level) ?.) "")
  12873. (org-get-heading))
  12874. (make-string level ?\s)
  12875. category
  12876. tags-list)
  12877. priority (org-get-priority txt))
  12878. (goto-char lspos)
  12879. (setq marker (org-agenda-new-marker))
  12880. (org-add-props txt props
  12881. 'org-marker marker 'org-hd-marker marker 'org-category category
  12882. 'todo-state todo
  12883. 'ts-date ts-date
  12884. 'priority priority
  12885. 'type (concat "tagsmatch" ts-date-type))
  12886. (push txt rtn))
  12887. ((functionp action)
  12888. (setq org-map-continue-from nil)
  12889. (save-excursion
  12890. (setq rtn1 (funcall action))
  12891. (push rtn1 rtn)))
  12892. (t (user-error "Invalid action")))
  12893. ;; if we are to skip sublevels, jump to end of subtree
  12894. (unless org-tags-match-list-sublevels
  12895. (org-end-of-subtree t)
  12896. (backward-char 1))))
  12897. ;; Get the correct position from where to continue
  12898. (if org-map-continue-from
  12899. (goto-char org-map-continue-from)
  12900. (and (= (point) lspos) (end-of-line 1)))))
  12901. (when (and (eq action 'sparse-tree)
  12902. (not org-sparse-tree-open-archived-trees))
  12903. (org-hide-archived-subtrees (point-min) (point-max)))
  12904. (nreverse rtn)))
  12905. (defun org-remove-uninherited-tags (tags)
  12906. "Remove all tags that are not inherited from the list TAGS."
  12907. (cond
  12908. ((eq org-use-tag-inheritance t)
  12909. (if org-tags-exclude-from-inheritance
  12910. (org-delete-all org-tags-exclude-from-inheritance tags)
  12911. tags))
  12912. ((not org-use-tag-inheritance) nil)
  12913. ((stringp org-use-tag-inheritance)
  12914. (delq nil (mapcar
  12915. (lambda (x)
  12916. (if (and (string-match org-use-tag-inheritance x)
  12917. (not (member x org-tags-exclude-from-inheritance)))
  12918. x nil))
  12919. tags)))
  12920. ((listp org-use-tag-inheritance)
  12921. (delq nil (mapcar
  12922. (lambda (x)
  12923. (if (member x org-use-tag-inheritance) x nil))
  12924. tags)))))
  12925. (defun org-match-sparse-tree (&optional todo-only match)
  12926. "Create a sparse tree according to tags string MATCH.
  12927. MATCH is a string with match syntax. It can contain a selection
  12928. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  12929. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  12930. those. See the manual for details.
  12931. If optional argument TODO-ONLY is non-nil, only select lines that
  12932. are also TODO tasks."
  12933. (interactive "P")
  12934. (org-agenda-prepare-buffers (list (current-buffer)))
  12935. (let ((org--matcher-tags-todo-only todo-only))
  12936. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  12937. org--matcher-tags-todo-only)))
  12938. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  12939. (defvar org-cached-props nil)
  12940. (defun org-cached-entry-get (pom property)
  12941. (if (or (eq t org-use-property-inheritance)
  12942. (and (stringp org-use-property-inheritance)
  12943. (let ((case-fold-search t))
  12944. (string-match-p org-use-property-inheritance property)))
  12945. (and (listp org-use-property-inheritance)
  12946. (member-ignore-case property org-use-property-inheritance)))
  12947. ;; Caching is not possible, check it directly.
  12948. (org-entry-get pom property 'inherit)
  12949. ;; Get all properties, so we can do complicated checks easily.
  12950. (cdr (assoc-string property
  12951. (or org-cached-props
  12952. (setq org-cached-props (org-entry-properties pom)))
  12953. t))))
  12954. (defun org-global-tags-completion-table (&optional files)
  12955. "Return the list of all tags in all agenda buffer/files.
  12956. Optional FILES argument is a list of files which can be used
  12957. instead of the agenda files."
  12958. (save-excursion
  12959. (org-uniquify
  12960. (delq nil
  12961. (apply #'append
  12962. (mapcar
  12963. (lambda (file)
  12964. (set-buffer (find-file-noselect file))
  12965. (mapcar (lambda (x)
  12966. (and (stringp (car-safe x))
  12967. (list (car-safe x))))
  12968. (or org-current-tag-alist (org-get-buffer-tags))))
  12969. (if (car-safe files) files
  12970. (org-agenda-files))))))))
  12971. (defun org-make-tags-matcher (match)
  12972. "Create the TAGS/TODO matcher form for the selection string MATCH.
  12973. Returns a cons of the selection string MATCH and a function
  12974. implementing the matcher.
  12975. The matcher is to be called at an Org entry, with point on the
  12976. headline, and returns non-nil if the entry matches the selection
  12977. string MATCH. It must be called with three arguments: the TODO
  12978. keyword at the entry (or nil if none), the list of all tags at
  12979. the entry including inherited ones and the reduced level of the
  12980. headline. Additionally, the category of the entry, if any, must
  12981. be specified as the text property `org-category' on the headline.
  12982. This function sets the variable `org--matcher-tags-todo-only' to
  12983. a non-nil value if the matcher restricts matching to TODO
  12984. entries, otherwise it is not touched.
  12985. See also `org-scan-tags'."
  12986. (unless match
  12987. ;; Get a new match request, with completion against the global
  12988. ;; tags table and the local tags in current buffer.
  12989. (let ((org-last-tags-completion-table
  12990. (org-uniquify
  12991. (delq nil (append (org-get-buffer-tags)
  12992. (org-global-tags-completion-table))))))
  12993. (setq match
  12994. (completing-read
  12995. "Match: "
  12996. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  12997. (let ((match0 match)
  12998. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  12999. (start 0)
  13000. tagsmatch todomatch tagsmatcher todomatcher)
  13001. ;; Expand group tags.
  13002. (setq match (org-tags-expand match))
  13003. ;; Check if there is a TODO part of this match, which would be the
  13004. ;; part after a "/". To make sure that this slash is not part of
  13005. ;; a property value to be matched against, we also check that
  13006. ;; there is no / after that slash. First, find the last slash.
  13007. (let ((s 0))
  13008. (while (string-match "/+" match s)
  13009. (setq start (match-beginning 0))
  13010. (setq s (match-end 0))))
  13011. (if (and (string-match "/+" match start)
  13012. (not (string-match-p "\"" match start)))
  13013. ;; Match contains also a TODO-matching request.
  13014. (progn
  13015. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13016. (setq todomatch (substring match (match-end 0)))
  13017. (when (string-prefix-p "!" todomatch)
  13018. (setq org--matcher-tags-todo-only t)
  13019. (setq todomatch (substring todomatch 1)))
  13020. (when (string-match "\\`\\s-*\\'" todomatch)
  13021. (setq todomatch nil)))
  13022. ;; Only matching tags.
  13023. (setq tagsmatch match)
  13024. (setq todomatch nil))
  13025. ;; Make the tags matcher.
  13026. (when (org-string-nw-p tagsmatch)
  13027. (let ((orlist nil)
  13028. (orterms (org-split-string tagsmatch "|"))
  13029. term)
  13030. (while (setq term (pop orterms))
  13031. (while (and (equal (substring term -1) "\\") orterms)
  13032. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13033. (while (string-match re term)
  13034. (let* ((rest (substring term (match-end 0)))
  13035. (minus (and (match-end 1)
  13036. (equal (match-string 1 term) "-")))
  13037. (tag (save-match-data
  13038. (replace-regexp-in-string
  13039. "\\\\-" "-" (match-string 2 term))))
  13040. (regexp (eq (string-to-char tag) ?{))
  13041. (levelp (match-end 4))
  13042. (propp (match-end 5))
  13043. (mm
  13044. (cond
  13045. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13046. (levelp
  13047. `(,(org-op-to-function (match-string 3 term))
  13048. level
  13049. ,(string-to-number (match-string 4 term))))
  13050. (propp
  13051. (let* ((gv (pcase (upcase (match-string 5 term))
  13052. ("CATEGORY"
  13053. '(get-text-property (point) 'org-category))
  13054. ("TODO" 'todo)
  13055. (p `(org-cached-entry-get nil ,p))))
  13056. (pv (match-string 7 term))
  13057. (regexp (eq (string-to-char pv) ?{))
  13058. (strp (eq (string-to-char pv) ?\"))
  13059. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13060. (po (org-op-to-function (match-string 6 term)
  13061. (if timep 'time strp))))
  13062. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13063. (when timep (setq pv (org-matcher-time pv)))
  13064. (cond ((and regexp (eq po 'org<>))
  13065. `(not (string-match ,pv (or ,gv ""))))
  13066. (regexp `(string-match ,pv (or ,gv "")))
  13067. (strp `(,po (or ,gv "") ,pv))
  13068. (t
  13069. `(,po
  13070. (string-to-number (or ,gv ""))
  13071. ,(string-to-number pv))))))
  13072. (t `(member ,tag tags-list)))))
  13073. (push (if minus `(not ,mm) mm) tagsmatcher)
  13074. (setq term rest)))
  13075. (push `(and ,@tagsmatcher) orlist)
  13076. (setq tagsmatcher nil))
  13077. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13078. ;; Make the TODO matcher.
  13079. (when (org-string-nw-p todomatch)
  13080. (let ((orlist nil))
  13081. (dolist (term (org-split-string todomatch "|"))
  13082. (while (string-match re term)
  13083. (let* ((minus (and (match-end 1)
  13084. (equal (match-string 1 term) "-")))
  13085. (kwd (match-string 2 term))
  13086. (regexp (eq (string-to-char kwd) ?{))
  13087. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13088. `(equal todo ,kwd))))
  13089. (push (if minus `(not ,mm) mm) todomatcher))
  13090. (setq term (substring term (match-end 0))))
  13091. (push (if (> (length todomatcher) 1)
  13092. (cons 'and todomatcher)
  13093. (car todomatcher))
  13094. orlist)
  13095. (setq todomatcher nil))
  13096. (setq todomatcher (cons 'or orlist))))
  13097. ;; Return the string and function of the matcher. If no
  13098. ;; tags-specific or todo-specific matcher exists, match
  13099. ;; everything.
  13100. (let ((matcher (if (and tagsmatcher todomatcher)
  13101. `(and ,tagsmatcher ,todomatcher)
  13102. (or tagsmatcher todomatcher t))))
  13103. (when org--matcher-tags-todo-only
  13104. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13105. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13106. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13107. "Expand group tags in MATCH.
  13108. This replaces every group tag in MATCH with a regexp tag search.
  13109. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13110. will be replaced like this:
  13111. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13112. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13113. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13114. Replacing by a regexp preserves the structure of the match.
  13115. E.g., this expansion
  13116. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13117. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13118. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13119. A group tag in MATCH can contain regular expressions of its own.
  13120. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13121. will be replaced like this:
  13122. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13123. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13124. assumed to be a single group tag, and the function will return
  13125. the list of tags in this group.
  13126. When DOWNCASE is non-nil, expand downcased TAGS."
  13127. (if org-group-tags
  13128. (let* ((case-fold-search t)
  13129. (stable org-mode-syntax-table)
  13130. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13131. (taggroups (if downcased
  13132. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13133. taggroups)
  13134. taggroups))
  13135. (taggroups-keys (mapcar #'car taggroups))
  13136. (return-match (if downcased (downcase match) match))
  13137. (count 0)
  13138. (work-already-expanded tags-already-expanded)
  13139. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13140. ;; @ and _ are allowed as word-components in tags.
  13141. (modify-syntax-entry ?@ "w" stable)
  13142. (modify-syntax-entry ?_ "w" stable)
  13143. ;; Temporarily replace regexp-expressions in the match-expression.
  13144. (while (string-match "{.+?}" return-match)
  13145. (cl-incf count)
  13146. (push (match-string 0 return-match) regexps-in-match)
  13147. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13148. (while (and taggroups-keys
  13149. (with-syntax-table stable
  13150. (string-match
  13151. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13152. (regexp-opt taggroups-keys) "\\>\\)")
  13153. return-match)))
  13154. (let* ((dir (match-string 1 return-match))
  13155. (tag (match-string 2 return-match))
  13156. (tag (if downcased (downcase tag) tag)))
  13157. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13158. (member tag work-already-expanded))
  13159. (setq tags-in-group (assoc tag taggroups))
  13160. (push tag work-already-expanded)
  13161. ;; Recursively expand each tag in the group, if the tag hasn't
  13162. ;; already been expanded. Restore the match-data after all recursive calls.
  13163. (save-match-data
  13164. (let (tags-expanded)
  13165. (dolist (x (cdr tags-in-group))
  13166. (if (and (member x taggroups-keys)
  13167. (not (member x work-already-expanded)))
  13168. (setq tags-expanded
  13169. (delete-dups
  13170. (append
  13171. (org-tags-expand x t downcased
  13172. work-already-expanded)
  13173. tags-expanded)))
  13174. (setq tags-expanded
  13175. (append (list x) tags-expanded)))
  13176. (setq work-already-expanded
  13177. (delete-dups
  13178. (append tags-expanded
  13179. work-already-expanded))))
  13180. (setq tags-in-group
  13181. (delete-dups (cons (car tags-in-group)
  13182. tags-expanded)))))
  13183. ;; Filter tag-regexps from tags.
  13184. (setq regexp-in-group-escaped
  13185. (delq nil (mapcar (lambda (x)
  13186. (if (stringp x)
  13187. (and (equal "{" (substring x 0 1))
  13188. (equal "}" (substring x -1))
  13189. x)
  13190. x))
  13191. tags-in-group))
  13192. regexp-in-group
  13193. (mapcar (lambda (x)
  13194. (substring x 1 -1))
  13195. regexp-in-group-escaped)
  13196. tags-in-group
  13197. (delq nil (mapcar (lambda (x)
  13198. (if (stringp x)
  13199. (and (not (equal "{" (substring x 0 1)))
  13200. (not (equal "}" (substring x -1)))
  13201. x)
  13202. x))
  13203. tags-in-group)))
  13204. ;; If single-as-list, do no more in the while-loop.
  13205. (if (not single-as-list)
  13206. (progn
  13207. (when regexp-in-group
  13208. (setq regexp-in-group
  13209. (concat "\\|"
  13210. (mapconcat 'identity regexp-in-group
  13211. "\\|"))))
  13212. (setq tags-in-group
  13213. (concat dir
  13214. "{\\<"
  13215. (regexp-opt tags-in-group)
  13216. "\\>"
  13217. regexp-in-group
  13218. "}"))
  13219. (when (stringp tags-in-group)
  13220. (org-add-props tags-in-group '(grouptag t)))
  13221. (setq return-match
  13222. (replace-match tags-in-group t t return-match)))
  13223. (setq tags-in-group
  13224. (append regexp-in-group-escaped tags-in-group))))
  13225. (setq taggroups-keys (delete tag taggroups-keys))))
  13226. ;; Add the regular expressions back into the match-expression again.
  13227. (while regexps-in-match
  13228. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13229. (pop regexps-in-match)
  13230. return-match t t))
  13231. (cl-decf count))
  13232. (if single-as-list
  13233. (if tags-in-group tags-in-group (list return-match))
  13234. return-match))
  13235. (if single-as-list
  13236. (list (if downcased (downcase match) match))
  13237. match)))
  13238. (defun org-op-to-function (op &optional stringp)
  13239. "Turn an operator into the appropriate function."
  13240. (setq op
  13241. (cond
  13242. ((equal op "<" ) '(< string< org-time<))
  13243. ((equal op ">" ) '(> org-string> org-time>))
  13244. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13245. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13246. ((member op '("=" "==")) '(= string= org-time=))
  13247. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13248. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13249. (defun org<> (a b) (not (= a b)))
  13250. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13251. (defun org-string>= (a b) (not (string< a b)))
  13252. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13253. (defun org-string<> (a b) (not (string= a b)))
  13254. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13255. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13256. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13257. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13258. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13259. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13260. (defun org-2ft (s)
  13261. "Convert S to a floating point time.
  13262. If S is already a number, just return it. If it is a string, parse
  13263. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13264. (cond
  13265. ((numberp s) s)
  13266. ((stringp s)
  13267. (condition-case nil
  13268. (float-time (apply 'encode-time (org-parse-time-string s)))
  13269. (error 0.)))
  13270. (t 0.)))
  13271. (defun org-time-today ()
  13272. "Time in seconds today at 0:00.
  13273. Returns the float number of seconds since the beginning of the
  13274. epoch to the beginning of today (00:00)."
  13275. (float-time (apply 'encode-time
  13276. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13277. (defun org-matcher-time (s)
  13278. "Interpret a time comparison value."
  13279. (save-match-data
  13280. (cond
  13281. ((string= s "<now>") (float-time))
  13282. ((string= s "<today>") (org-time-today))
  13283. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13284. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13285. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13286. (+ (org-time-today)
  13287. (* (string-to-number (match-string 1 s))
  13288. (cdr (assoc (match-string 2 s)
  13289. '(("d" . 86400.0) ("w" . 604800.0)
  13290. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13291. (t (org-2ft s)))))
  13292. (defun org-match-any-p (re list)
  13293. "Does re match any element of list?"
  13294. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13295. (delq nil list))
  13296. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13297. (defvar org-tags-overlay (make-overlay 1 1))
  13298. (delete-overlay org-tags-overlay)
  13299. (defun org-get-local-tags-at (&optional pos)
  13300. "Get a list of tags defined in the current headline."
  13301. (org-get-tags-at pos 'local))
  13302. (defun org-get-local-tags ()
  13303. "Get a list of tags defined in the current headline."
  13304. (org-get-tags-at nil 'local))
  13305. (defun org-get-tags-at (&optional pos local)
  13306. "Get a list of all headline tags applicable at POS.
  13307. POS defaults to point. If tags are inherited, the list contains
  13308. the targets in the same sequence as the headlines appear, i.e.
  13309. the tags of the current headline come last.
  13310. When LOCAL is non-nil, only return tags from the current headline,
  13311. ignore inherited ones."
  13312. (interactive)
  13313. (if (and org-trust-scanner-tags
  13314. (or (not pos) (equal pos (point)))
  13315. (not local))
  13316. org-scanner-tags
  13317. (let (tags ltags lastpos parent)
  13318. (save-excursion
  13319. (save-restriction
  13320. (widen)
  13321. (goto-char (or pos (point)))
  13322. (save-match-data
  13323. (catch 'done
  13324. (condition-case nil
  13325. (progn
  13326. (org-back-to-heading t)
  13327. (while (not (equal lastpos (point)))
  13328. (setq lastpos (point))
  13329. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13330. (setq ltags (org-split-string
  13331. (match-string-no-properties 1) ":"))
  13332. (when parent
  13333. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13334. (setq tags (append
  13335. (if parent
  13336. (org-remove-uninherited-tags ltags)
  13337. ltags)
  13338. tags)))
  13339. (or org-use-tag-inheritance (throw 'done t))
  13340. (when local (throw 'done t))
  13341. (or (org-up-heading-safe) (error nil))
  13342. (setq parent t)))
  13343. (error nil)))))
  13344. (if local
  13345. tags
  13346. (reverse (delete-dups
  13347. (reverse (append
  13348. (org-remove-uninherited-tags
  13349. org-file-tags)
  13350. tags)))))))))
  13351. (defun org-add-prop-inherited (s)
  13352. (add-text-properties 0 (length s) '(inherited t) s)
  13353. s)
  13354. (defun org-toggle-tag (tag &optional onoff)
  13355. "Toggle the tag TAG for the current line.
  13356. If ONOFF is `on' or `off', don't toggle but set to this state."
  13357. (let (res current)
  13358. (save-excursion
  13359. (org-back-to-heading t)
  13360. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13361. (point-at-eol) t)
  13362. (progn
  13363. (setq current (match-string 1))
  13364. (replace-match ""))
  13365. (setq current ""))
  13366. (setq current (nreverse (org-split-string current ":")))
  13367. (cond
  13368. ((eq onoff 'on)
  13369. (setq res t)
  13370. (or (member tag current) (push tag current)))
  13371. ((eq onoff 'off)
  13372. (or (not (member tag current)) (setq current (delete tag current))))
  13373. (t (if (member tag current)
  13374. (setq current (delete tag current))
  13375. (setq res t)
  13376. (push tag current))))
  13377. (end-of-line 1)
  13378. (if current
  13379. (progn
  13380. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13381. (org-set-tags nil t))
  13382. (delete-horizontal-space))
  13383. (run-hooks 'org-after-tags-change-hook))
  13384. res))
  13385. (defun org--align-tags-here (to-col)
  13386. "Align tags on the current headline to TO-COL.
  13387. Assume point is on a headline."
  13388. (let ((pos (point)))
  13389. (beginning-of-line)
  13390. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13391. (>= pos (match-beginning 2)))
  13392. ;; No tags or point within tags: do not align.
  13393. (goto-char pos)
  13394. (goto-char (match-beginning 1))
  13395. (let ((shift (max (- (if (>= to-col 0) to-col
  13396. (- (abs to-col) (string-width (match-string 2))))
  13397. (current-column))
  13398. 1)))
  13399. (replace-match (make-string shift ?\s) nil nil nil 1)
  13400. ;; Preserve initial position, if possible. In any case, stop
  13401. ;; before tags.
  13402. (when (< pos (point)) (goto-char pos))))))
  13403. (defun org-set-tags-command (&optional arg just-align)
  13404. "Call the set-tags command for the current entry."
  13405. (interactive "P")
  13406. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13407. (org-set-tags arg just-align)
  13408. (save-excursion
  13409. (unless (and (org-region-active-p)
  13410. org-loop-over-headlines-in-active-region)
  13411. (org-back-to-heading t))
  13412. (org-set-tags arg just-align))))
  13413. (defun org-set-tags-to (data)
  13414. "Set the tags of the current entry to DATA, replacing the current tags.
  13415. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13416. If DATA is nil or the empty string, any tags will be removed."
  13417. (interactive "sTags: ")
  13418. (setq data
  13419. (cond
  13420. ((eq data nil) "")
  13421. ((equal data "") "")
  13422. ((stringp data)
  13423. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13424. ":"))
  13425. ((listp data)
  13426. (concat ":" (mapconcat 'identity data ":") ":"))))
  13427. (when data
  13428. (save-excursion
  13429. (org-back-to-heading t)
  13430. (when (let ((case-fold-search nil))
  13431. (looking-at org-complex-heading-regexp))
  13432. (if (match-end 5)
  13433. (progn
  13434. (goto-char (match-beginning 5))
  13435. (insert data)
  13436. (delete-region (point) (point-at-eol))
  13437. (org-set-tags nil 'align))
  13438. (goto-char (point-at-eol))
  13439. (insert " " data)
  13440. (org-set-tags nil 'align)))
  13441. (beginning-of-line 1)
  13442. (when (looking-at ".*?\\([ \t]+\\)$")
  13443. (delete-region (match-beginning 1) (match-end 1))))))
  13444. (defun org-align-all-tags ()
  13445. "Align the tags in all headings."
  13446. (interactive)
  13447. (save-excursion
  13448. (or (ignore-errors (org-back-to-heading t))
  13449. (outline-next-heading))
  13450. (if (org-at-heading-p)
  13451. (org-set-tags t)
  13452. (message "No headings"))))
  13453. (defvar org-indent-indentation-per-level)
  13454. (defun org-set-tags (&optional arg just-align)
  13455. "Set the tags for the current headline.
  13456. With prefix ARG, realign all tags in headings in the current buffer.
  13457. When JUST-ALIGN is non-nil, only align tags."
  13458. (interactive "P")
  13459. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13460. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13461. 'region-start-level
  13462. 'region))
  13463. org-loop-over-headlines-in-active-region)
  13464. (org-map-entries
  13465. ;; We don't use ARG and JUST-ALIGN here because these args
  13466. ;; are not useful when looping over headlines.
  13467. #'org-set-tags
  13468. org-loop-over-headlines-in-active-region
  13469. cl
  13470. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13471. (let ((org-setting-tags t))
  13472. (if arg
  13473. (save-excursion
  13474. (goto-char (point-min))
  13475. (while (re-search-forward org-outline-regexp-bol nil t)
  13476. (org-set-tags nil t)
  13477. (end-of-line))
  13478. (message "All tags realigned to column %d" org-tags-column))
  13479. (let* ((current (org-get-tags-string))
  13480. (tags
  13481. (if just-align current
  13482. ;; Get a new set of tags from the user.
  13483. (save-excursion
  13484. (let* ((seen)
  13485. (table
  13486. (setq
  13487. org-last-tags-completion-table
  13488. ;; Uniquify tags in alists, yet preserve
  13489. ;; structure (i.e., keywords).
  13490. (delq nil
  13491. (mapcar
  13492. (lambda (pair)
  13493. (let ((head (car pair)))
  13494. (cond ((symbolp head) pair)
  13495. ((member head seen) nil)
  13496. (t (push head seen)
  13497. pair))))
  13498. (append
  13499. (or org-current-tag-alist
  13500. (org-get-buffer-tags))
  13501. (and
  13502. org-complete-tags-always-offer-all-agenda-tags
  13503. (org-global-tags-completion-table
  13504. (org-agenda-files))))))))
  13505. (current-tags (org-split-string current ":"))
  13506. (inherited-tags
  13507. (nreverse (nthcdr (length current-tags)
  13508. (nreverse (org-get-tags-at))))))
  13509. (replace-regexp-in-string
  13510. "\\([-+&]+\\|,\\)"
  13511. ":"
  13512. (if (or (eq t org-use-fast-tag-selection)
  13513. (and org-use-fast-tag-selection
  13514. (delq nil (mapcar #'cdr table))))
  13515. (org-fast-tag-selection
  13516. current-tags inherited-tags table
  13517. (and org-fast-tag-selection-include-todo
  13518. org-todo-key-alist))
  13519. (let ((org-add-colon-after-tag-completion
  13520. (< 1 (length table))))
  13521. (org-trim
  13522. (completing-read
  13523. "Tags: "
  13524. #'org-tags-completion-function
  13525. nil nil current 'org-tags-history))))))))))
  13526. (when org-tags-sort-function
  13527. (setq tags
  13528. (mapconcat
  13529. #'identity
  13530. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13531. org-tags-sort-function)
  13532. ":")))
  13533. (if (or (string= ":" tags)
  13534. (string= "::" tags))
  13535. (setq tags ""))
  13536. (if (not (org-string-nw-p tags)) (setq tags "")
  13537. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13538. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13539. ;; Insert new tags at the correct column.
  13540. (unless (equal current tags)
  13541. (save-excursion
  13542. (beginning-of-line)
  13543. (let ((case-fold-search nil))
  13544. (looking-at org-complex-heading-regexp))
  13545. ;; Remove current tags, if any.
  13546. (when (match-end 5) (replace-match "" nil nil nil 5))
  13547. ;; Insert new tags, if any. Otherwise, remove trailing
  13548. ;; white spaces.
  13549. (end-of-line)
  13550. (if (not (equal tags ""))
  13551. ;; When text is being inserted on an invisible
  13552. ;; region boundary, it can be inadvertently sucked
  13553. ;; into invisibility.
  13554. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13555. (skip-chars-backward " \t")
  13556. (delete-region (point) (line-end-position)))))
  13557. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13558. ;; is on.
  13559. (unless (equal tags "")
  13560. (let* ((level (save-excursion
  13561. (beginning-of-line)
  13562. (skip-chars-forward "\\*")))
  13563. (offset (if (bound-and-true-p org-indent-mode)
  13564. (* (1- org-indent-indentation-per-level)
  13565. (1- level))
  13566. 0))
  13567. (tags-column
  13568. (+ org-tags-column
  13569. (if (> org-tags-column 0) (- offset) offset))))
  13570. (org--align-tags-here tags-column))))
  13571. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13572. (defun org-change-tag-in-region (beg end tag off)
  13573. "Add or remove TAG for each entry in the region.
  13574. This works in the agenda, and also in an Org buffer."
  13575. (interactive
  13576. (list (region-beginning) (region-end)
  13577. (let ((org-last-tags-completion-table
  13578. (if (derived-mode-p 'org-mode)
  13579. (org-uniquify
  13580. (delq nil (append (org-get-buffer-tags)
  13581. (org-global-tags-completion-table))))
  13582. (org-global-tags-completion-table))))
  13583. (completing-read
  13584. "Tag: " 'org-tags-completion-function nil nil nil
  13585. 'org-tags-history))
  13586. (progn
  13587. (message "[s]et or [r]emove? ")
  13588. (equal (read-char-exclusive) ?r))))
  13589. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13590. (let ((agendap (equal major-mode 'org-agenda-mode))
  13591. l1 l2 m buf pos newhead (cnt 0))
  13592. (goto-char end)
  13593. (setq l2 (1- (org-current-line)))
  13594. (goto-char beg)
  13595. (setq l1 (org-current-line))
  13596. (cl-loop for l from l1 to l2 do
  13597. (org-goto-line l)
  13598. (setq m (get-text-property (point) 'org-hd-marker))
  13599. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13600. (and agendap m))
  13601. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13602. pos (if agendap m (point)))
  13603. (with-current-buffer buf
  13604. (save-excursion
  13605. (save-restriction
  13606. (goto-char pos)
  13607. (setq cnt (1+ cnt))
  13608. (org-toggle-tag tag (if off 'off 'on))
  13609. (setq newhead (org-get-heading)))))
  13610. (and agendap (org-agenda-change-all-lines newhead m))))
  13611. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13612. (defun org-tags-completion-function (string _predicate &optional flag)
  13613. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13614. (confirm (lambda (x) (stringp (car x)))))
  13615. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13616. (setq s1 (match-string 1 string)
  13617. s2 (match-string 2 string))
  13618. (setq s1 "" s2 string))
  13619. (cond
  13620. ((eq flag nil)
  13621. ;; try completion
  13622. (setq rtn (try-completion s2 ctable confirm))
  13623. (when (stringp rtn)
  13624. (setq rtn
  13625. (concat s1 s2 (substring rtn (length s2))
  13626. (if (and org-add-colon-after-tag-completion
  13627. (assoc rtn ctable))
  13628. ":" ""))))
  13629. rtn)
  13630. ((eq flag t)
  13631. ;; all-completions
  13632. (all-completions s2 ctable confirm))
  13633. ((eq flag 'lambda)
  13634. ;; exact match?
  13635. (assoc s2 ctable)))))
  13636. (defun org-fast-tag-insert (kwd tags face &optional end)
  13637. "Insert KDW, and the TAGS, the latter with face FACE.
  13638. Also insert END."
  13639. (insert (format "%-12s" (concat kwd ":"))
  13640. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13641. (or end "")))
  13642. (defun org-fast-tag-show-exit (flag)
  13643. (save-excursion
  13644. (org-goto-line 3)
  13645. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13646. (replace-match ""))
  13647. (when flag
  13648. (end-of-line 1)
  13649. (org-move-to-column (- (window-width) 19) t)
  13650. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13651. (defun org-set-current-tags-overlay (current prefix)
  13652. "Add an overlay to CURRENT tag with PREFIX."
  13653. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13654. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13655. (org-overlay-display org-tags-overlay (concat prefix s))))
  13656. (defvar org-last-tag-selection-key nil)
  13657. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13658. "Fast tag selection with single keys.
  13659. CURRENT is the current list of tags in the headline, INHERITED is the
  13660. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13661. possibly with grouping information. TODO-TABLE is a similar table with
  13662. TODO keywords, should these have keys assigned to them.
  13663. If the keys are nil, a-z are automatically assigned.
  13664. Returns the new tags string, or nil to not change the current settings."
  13665. (let* ((fulltable (append table todo-table))
  13666. (maxlen (apply 'max (mapcar
  13667. (lambda (x)
  13668. (if (stringp (car x)) (string-width (car x)) 0))
  13669. fulltable)))
  13670. (buf (current-buffer))
  13671. (expert (eq org-fast-tag-selection-single-key 'expert))
  13672. (buffer-tags nil)
  13673. (fwidth (+ maxlen 3 1 3))
  13674. (ncol (/ (- (window-width) 4) fwidth))
  13675. (i-face 'org-done)
  13676. (c-face 'org-todo)
  13677. tg cnt e c char c1 c2 ntable tbl rtn
  13678. ov-start ov-end ov-prefix
  13679. (exit-after-next org-fast-tag-selection-single-key)
  13680. (done-keywords org-done-keywords)
  13681. groups ingroup intaggroup)
  13682. (save-excursion
  13683. (beginning-of-line 1)
  13684. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13685. (setq ov-start (match-beginning 1)
  13686. ov-end (match-end 1)
  13687. ov-prefix "")
  13688. (setq ov-start (1- (point-at-eol))
  13689. ov-end (1+ ov-start))
  13690. (skip-chars-forward "^\n\r")
  13691. (setq ov-prefix
  13692. (concat
  13693. (buffer-substring (1- (point)) (point))
  13694. (if (> (current-column) org-tags-column)
  13695. " "
  13696. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13697. (move-overlay org-tags-overlay ov-start ov-end)
  13698. (save-window-excursion
  13699. (if expert
  13700. (set-buffer (get-buffer-create " *Org tags*"))
  13701. (delete-other-windows)
  13702. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13703. (org-switch-to-buffer-other-window " *Org tags*"))
  13704. (erase-buffer)
  13705. (setq-local org-done-keywords done-keywords)
  13706. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13707. (org-fast-tag-insert "Current" current c-face "\n\n")
  13708. (org-fast-tag-show-exit exit-after-next)
  13709. (org-set-current-tags-overlay current ov-prefix)
  13710. (setq tbl fulltable char ?a cnt 0)
  13711. (while (setq e (pop tbl))
  13712. (cond
  13713. ((eq (car e) :startgroup)
  13714. (push '() groups) (setq ingroup t)
  13715. (unless (zerop cnt)
  13716. (setq cnt 0)
  13717. (insert "\n"))
  13718. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13719. ((eq (car e) :endgroup)
  13720. (setq ingroup nil cnt 0)
  13721. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13722. ((eq (car e) :startgrouptag)
  13723. (setq intaggroup t)
  13724. (unless (zerop cnt)
  13725. (setq cnt 0)
  13726. (insert "\n"))
  13727. (insert "[ "))
  13728. ((eq (car e) :endgrouptag)
  13729. (setq intaggroup nil cnt 0)
  13730. (insert "]\n"))
  13731. ((equal e '(:newline))
  13732. (unless (zerop cnt)
  13733. (setq cnt 0)
  13734. (insert "\n")
  13735. (setq e (car tbl))
  13736. (while (equal (car tbl) '(:newline))
  13737. (insert "\n")
  13738. (setq tbl (cdr tbl)))))
  13739. ((equal e '(:grouptags)) (insert " : "))
  13740. (t
  13741. (setq tg (copy-sequence (car e)) c2 nil)
  13742. (if (cdr e)
  13743. (setq c (cdr e))
  13744. ;; automatically assign a character.
  13745. (setq c1 (string-to-char
  13746. (downcase (substring
  13747. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13748. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13749. (while (or (rassoc char ntable) (rassoc char table))
  13750. (setq char (1+ char)))
  13751. (setq c2 c1))
  13752. (setq c (or c2 char)))
  13753. (when ingroup (push tg (car groups)))
  13754. (setq tg (org-add-props tg nil 'face
  13755. (cond
  13756. ((not (assoc tg table))
  13757. (org-get-todo-face tg))
  13758. ((member tg current) c-face)
  13759. ((member tg inherited) i-face))))
  13760. (when (equal (caar tbl) :grouptags)
  13761. (org-add-props tg nil 'face 'org-tag-group))
  13762. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13763. (insert "[" c "] " tg (make-string
  13764. (- fwidth 4 (length tg)) ?\ ))
  13765. (push (cons tg c) ntable)
  13766. (when (= (cl-incf cnt) ncol)
  13767. (insert "\n")
  13768. (when (or ingroup intaggroup) (insert " "))
  13769. (setq cnt 0)))))
  13770. (setq ntable (nreverse ntable))
  13771. (insert "\n")
  13772. (goto-char (point-min))
  13773. (unless expert (org-fit-window-to-buffer))
  13774. (setq rtn
  13775. (catch 'exit
  13776. (while t
  13777. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13778. (if (not groups) "no " "")
  13779. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13780. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13781. (setq org-last-tag-selection-key c)
  13782. (cond
  13783. ((= c ?\r) (throw 'exit t))
  13784. ((= c ?!)
  13785. (setq groups (not groups))
  13786. (goto-char (point-min))
  13787. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13788. ((= c ?\C-c)
  13789. (if (not expert)
  13790. (org-fast-tag-show-exit
  13791. (setq exit-after-next (not exit-after-next)))
  13792. (setq expert nil)
  13793. (delete-other-windows)
  13794. (set-window-buffer (split-window-vertically) " *Org tags*")
  13795. (org-switch-to-buffer-other-window " *Org tags*")
  13796. (org-fit-window-to-buffer)))
  13797. ((or (= c ?\C-g)
  13798. (and (= c ?q) (not (rassoc c ntable))))
  13799. (delete-overlay org-tags-overlay)
  13800. (setq quit-flag t))
  13801. ((= c ?\ )
  13802. (setq current nil)
  13803. (when exit-after-next (setq exit-after-next 'now)))
  13804. ((= c ?\t)
  13805. (condition-case nil
  13806. (setq tg (completing-read
  13807. "Tag: "
  13808. (or buffer-tags
  13809. (with-current-buffer buf
  13810. (setq buffer-tags
  13811. (org-get-buffer-tags))))))
  13812. (quit (setq tg "")))
  13813. (when (string-match "\\S-" tg)
  13814. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13815. (if (member tg current)
  13816. (setq current (delete tg current))
  13817. (push tg current)))
  13818. (when exit-after-next (setq exit-after-next 'now)))
  13819. ((setq e (rassoc c todo-table) tg (car e))
  13820. (with-current-buffer buf
  13821. (save-excursion (org-todo tg)))
  13822. (when exit-after-next (setq exit-after-next 'now)))
  13823. ((setq e (rassoc c ntable) tg (car e))
  13824. (if (member tg current)
  13825. (setq current (delete tg current))
  13826. (cl-loop for g in groups do
  13827. (when (member tg g)
  13828. (dolist (x g) (setq current (delete x current)))))
  13829. (push tg current))
  13830. (when exit-after-next (setq exit-after-next 'now))))
  13831. ;; Create a sorted list
  13832. (setq current
  13833. (sort current
  13834. (lambda (a b)
  13835. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13836. (when (eq exit-after-next 'now) (throw 'exit t))
  13837. (goto-char (point-min))
  13838. (beginning-of-line 2)
  13839. (delete-region (point) (point-at-eol))
  13840. (org-fast-tag-insert "Current" current c-face)
  13841. (org-set-current-tags-overlay current ov-prefix)
  13842. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13843. (setq tg (match-string 1))
  13844. (add-text-properties
  13845. (match-beginning 1) (match-end 1)
  13846. (list 'face
  13847. (cond
  13848. ((member tg current) c-face)
  13849. ((member tg inherited) i-face)
  13850. (t (get-text-property (match-beginning 1) 'face))))))
  13851. (goto-char (point-min)))))
  13852. (delete-overlay org-tags-overlay)
  13853. (if rtn
  13854. (mapconcat 'identity current ":")
  13855. nil))))
  13856. (defun org-get-tags-string ()
  13857. "Get the TAGS string in the current headline."
  13858. (unless (org-at-heading-p t)
  13859. (user-error "Not on a heading"))
  13860. (save-excursion
  13861. (beginning-of-line 1)
  13862. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13863. (match-string-no-properties 1)
  13864. "")))
  13865. (defun org-get-tags ()
  13866. "Get the list of tags specified in the current headline."
  13867. (org-split-string (org-get-tags-string) ":"))
  13868. (defun org-get-buffer-tags ()
  13869. "Get a table of all tags used in the buffer, for completion."
  13870. (org-with-wide-buffer
  13871. (goto-char (point-min))
  13872. (let ((tag-re (concat org-outline-regexp-bol
  13873. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  13874. tags)
  13875. (while (re-search-forward tag-re nil t)
  13876. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  13877. (push tag tags)))
  13878. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  13879. ;;;; The mapping API
  13880. (defvar org-agenda-skip-comment-trees)
  13881. (defvar org-agenda-skip-function)
  13882. (defun org-map-entries (func &optional match scope &rest skip)
  13883. "Call FUNC at each headline selected by MATCH in SCOPE.
  13884. FUNC is a function or a lisp form. The function will be called without
  13885. arguments, with the cursor positioned at the beginning of the headline.
  13886. The return values of all calls to the function will be collected and
  13887. returned as a list.
  13888. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  13889. does not need to preserve point. After evaluation, the cursor will be
  13890. moved to the end of the line (presumably of the headline of the
  13891. processed entry) and search continues from there. Under some
  13892. circumstances, this may not produce the wanted results. For example,
  13893. if you have removed (e.g. archived) the current (sub)tree it could
  13894. mean that the next entry will be skipped entirely. In such cases, you
  13895. can specify the position from where search should continue by making
  13896. FUNC set the variable `org-map-continue-from' to the desired buffer
  13897. position.
  13898. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  13899. Only headlines that are matched by this query will be considered during
  13900. the iteration. When MATCH is nil or t, all headlines will be
  13901. visited by the iteration.
  13902. SCOPE determines the scope of this command. It can be any of:
  13903. nil The current buffer, respecting the restriction if any
  13904. tree The subtree started with the entry at point
  13905. region The entries within the active region, if any
  13906. region-start-level
  13907. The entries within the active region, but only those at
  13908. the same level than the first one.
  13909. file The current buffer, without restriction
  13910. file-with-archives
  13911. The current buffer, and any archives associated with it
  13912. agenda All agenda files
  13913. agenda-with-archives
  13914. All agenda files with any archive files associated with them
  13915. \(file1 file2 ...)
  13916. If this is a list, all files in the list will be scanned
  13917. The remaining args are treated as settings for the skipping facilities of
  13918. the scanner. The following items can be given here:
  13919. archive skip trees with the archive tag
  13920. comment skip trees with the COMMENT keyword
  13921. function or Emacs Lisp form:
  13922. will be used as value for `org-agenda-skip-function', so
  13923. whenever the function returns a position, FUNC will not be
  13924. called for that entry and search will continue from the
  13925. position returned
  13926. If your function needs to retrieve the tags including inherited tags
  13927. at the *current* entry, you can use the value of the variable
  13928. `org-scanner-tags' which will be much faster than getting the value
  13929. with `org-get-tags-at'. If your function gets properties with
  13930. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  13931. to t around the call to `org-entry-properties' to get the same speedup.
  13932. Note that if your function moves around to retrieve tags and properties at
  13933. a *different* entry, you cannot use these techniques."
  13934. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  13935. (not (org-region-active-p)))
  13936. (let* ((org-agenda-archives-mode nil) ; just to make sure
  13937. (org-agenda-skip-archived-trees (memq 'archive skip))
  13938. (org-agenda-skip-comment-trees (memq 'comment skip))
  13939. (org-agenda-skip-function
  13940. (car (org-delete-all '(comment archive) skip)))
  13941. (org-tags-match-list-sublevels t)
  13942. (start-level (eq scope 'region-start-level))
  13943. matcher res
  13944. org-todo-keywords-for-agenda
  13945. org-done-keywords-for-agenda
  13946. org-todo-keyword-alist-for-agenda
  13947. org-tag-alist-for-agenda
  13948. org--matcher-tags-todo-only)
  13949. (cond
  13950. ((eq match t) (setq matcher t))
  13951. ((eq match nil) (setq matcher t))
  13952. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  13953. (save-excursion
  13954. (save-restriction
  13955. (cond ((eq scope 'tree)
  13956. (org-back-to-heading t)
  13957. (org-narrow-to-subtree)
  13958. (setq scope nil))
  13959. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  13960. (org-region-active-p))
  13961. ;; If needed, set start-level to a string like "2"
  13962. (when start-level
  13963. (save-excursion
  13964. (goto-char (region-beginning))
  13965. (unless (org-at-heading-p) (outline-next-heading))
  13966. (setq start-level (org-current-level))))
  13967. (narrow-to-region (region-beginning)
  13968. (save-excursion
  13969. (goto-char (region-end))
  13970. (unless (and (bolp) (org-at-heading-p))
  13971. (outline-next-heading))
  13972. (point)))
  13973. (setq scope nil)))
  13974. (if (not scope)
  13975. (progn
  13976. (org-agenda-prepare-buffers
  13977. (and buffer-file-name (list buffer-file-name)))
  13978. (setq res
  13979. (org-scan-tags
  13980. func matcher org--matcher-tags-todo-only start-level)))
  13981. ;; Get the right scope
  13982. (cond
  13983. ((and scope (listp scope) (symbolp (car scope)))
  13984. (setq scope (eval scope)))
  13985. ((eq scope 'agenda)
  13986. (setq scope (org-agenda-files t)))
  13987. ((eq scope 'agenda-with-archives)
  13988. (setq scope (org-agenda-files t))
  13989. (setq scope (org-add-archive-files scope)))
  13990. ((eq scope 'file)
  13991. (setq scope (and buffer-file-name (list buffer-file-name))))
  13992. ((eq scope 'file-with-archives)
  13993. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  13994. (org-agenda-prepare-buffers scope)
  13995. (dolist (file scope)
  13996. (with-current-buffer (org-find-base-buffer-visiting file)
  13997. (org-with-wide-buffer
  13998. (goto-char (point-min))
  13999. (setq res
  14000. (append
  14001. res
  14002. (org-scan-tags
  14003. func matcher org--matcher-tags-todo-only)))))))))
  14004. res)))
  14005. ;;; Properties API
  14006. (defconst org-special-properties
  14007. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14008. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14009. "The special properties valid in Org mode.
  14010. These are properties that are not defined in the property drawer,
  14011. but in some other way.")
  14012. (defconst org-default-properties
  14013. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14014. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14015. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14016. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14017. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14018. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14019. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14020. "Some properties that are used by Org mode for various purposes.
  14021. Being in this list makes sure that they are offered for completion.")
  14022. (defun org--valid-property-p (property)
  14023. "Non nil when string PROPERTY is a valid property name."
  14024. (not
  14025. (or (equal property "")
  14026. (string-match-p "\\s-" property))))
  14027. (defun org--update-property-plist (key val props)
  14028. "Associate KEY to VAL in alist PROPS.
  14029. Modifications are made by side-effect. Return new alist."
  14030. (let* ((appending (string= (substring key -1) "+"))
  14031. (key (if appending (substring key 0 -1) key))
  14032. (old (assoc-string key props t)))
  14033. (if (not old) (cons (cons key val) props)
  14034. (setcdr old (if appending (concat (cdr old) " " val) val))
  14035. props)))
  14036. (defun org-get-property-block (&optional beg force)
  14037. "Return the (beg . end) range of the body of the property drawer.
  14038. BEG is the beginning of the current subtree, or of the part
  14039. before the first headline. If it is not given, it will be found.
  14040. If the drawer does not exist, create it if FORCE is non-nil, or
  14041. return nil."
  14042. (org-with-wide-buffer
  14043. (when beg (goto-char beg))
  14044. (unless (org-before-first-heading-p)
  14045. (let ((beg (cond (beg)
  14046. ((or (not (featurep 'org-inlinetask))
  14047. (org-inlinetask-in-task-p))
  14048. (org-back-to-heading t))
  14049. (t (org-with-limited-levels (org-back-to-heading t))))))
  14050. (forward-line)
  14051. (when (looking-at-p org-planning-line-re) (forward-line))
  14052. (cond ((looking-at org-property-drawer-re)
  14053. (forward-line)
  14054. (cons (point) (progn (goto-char (match-end 0))
  14055. (line-beginning-position))))
  14056. (force
  14057. (goto-char beg)
  14058. (org-insert-property-drawer)
  14059. (let ((pos (save-excursion (search-forward ":END:")
  14060. (line-beginning-position))))
  14061. (cons pos pos))))))))
  14062. (defun org-at-property-p ()
  14063. "Non-nil when point is inside a property drawer.
  14064. See `org-property-re' for match data, if applicable."
  14065. (save-excursion
  14066. (beginning-of-line)
  14067. (and (looking-at org-property-re)
  14068. (let ((property-drawer (save-match-data (org-get-property-block))))
  14069. (and property-drawer
  14070. (>= (point) (car property-drawer))
  14071. (< (point) (cdr property-drawer)))))))
  14072. (defun org-property-action ()
  14073. "Do an action on properties."
  14074. (interactive)
  14075. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14076. (let ((c (read-char-exclusive)))
  14077. (cl-case c
  14078. (?s (call-interactively #'org-set-property))
  14079. (?d (call-interactively #'org-delete-property))
  14080. (?D (call-interactively #'org-delete-property-globally))
  14081. (?c (call-interactively #'org-compute-property-at-point))
  14082. (otherwise (user-error "No such property action %c" c)))))
  14083. (defun org-inc-effort ()
  14084. "Increment the value of the effort property in the current entry."
  14085. (interactive)
  14086. (org-set-effort nil t))
  14087. (defvar org-clock-effort) ; Defined in org-clock.el.
  14088. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14089. (defun org-set-effort (&optional value increment)
  14090. "Set the effort property of the current entry.
  14091. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14092. 10th allowed value.
  14093. When INCREMENT is non-nil, set the property to the next allowed value."
  14094. (interactive "P")
  14095. (when (equal value 0) (setq value 10))
  14096. (let* ((completion-ignore-case t)
  14097. (prop org-effort-property)
  14098. (cur (org-entry-get nil prop))
  14099. (allowed (org-property-get-allowed-values nil prop 'table))
  14100. (existing (mapcar 'list (org-property-values prop)))
  14101. (heading (nth 4 (org-heading-components)))
  14102. rpl
  14103. (val (cond
  14104. ((stringp value) value)
  14105. ((and allowed (integerp value))
  14106. (or (car (nth (1- value) allowed))
  14107. (car (org-last allowed))))
  14108. ((and allowed increment)
  14109. (or (cl-caadr (member (list cur) allowed))
  14110. (user-error "Allowed effort values are not set")))
  14111. (allowed
  14112. (message "Select 1-9,0, [RET%s]: %s"
  14113. (if cur (concat "=" cur) "")
  14114. (mapconcat 'car allowed " "))
  14115. (setq rpl (read-char-exclusive))
  14116. (if (equal rpl ?\r)
  14117. cur
  14118. (setq rpl (- rpl ?0))
  14119. (when (equal rpl 0) (setq rpl 10))
  14120. (if (and (> rpl 0) (<= rpl (length allowed)))
  14121. (car (nth (1- rpl) allowed))
  14122. (org-completing-read "Effort: " allowed nil))))
  14123. (t
  14124. (org-completing-read
  14125. (concat "Effort" (and cur (string-match "\\S-" cur)
  14126. (concat " [" cur "]"))
  14127. ": ")
  14128. existing nil nil "" nil cur)))))
  14129. (unless (equal (org-entry-get nil prop) val)
  14130. (org-entry-put nil prop val))
  14131. (org-refresh-property
  14132. '((effort . identity)
  14133. (effort-minutes . org-duration-to-minutes))
  14134. val)
  14135. (when (equal heading (bound-and-true-p org-clock-current-task))
  14136. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14137. (org-clock-update-mode-line))
  14138. (message "%s is now %s" prop val)))
  14139. (defun org-entry-properties (&optional pom which)
  14140. "Get all properties of the current entry.
  14141. When POM is a buffer position, get all properties from the entry
  14142. there instead.
  14143. This includes the TODO keyword, the tags, time strings for
  14144. deadline, scheduled, and clocking, and any additional properties
  14145. defined in the entry.
  14146. If WHICH is nil or `all', get all properties. If WHICH is
  14147. `special' or `standard', only get that subclass. If WHICH is
  14148. a string, only get that property.
  14149. Return value is an alist. Keys are properties, as upcased
  14150. strings."
  14151. (org-with-point-at pom
  14152. (when (and (derived-mode-p 'org-mode)
  14153. (ignore-errors (org-back-to-heading t)))
  14154. (catch 'exit
  14155. (let* ((beg (point))
  14156. (specific (and (stringp which) (upcase which)))
  14157. (which (cond ((not specific) which)
  14158. ((member specific org-special-properties) 'special)
  14159. (t 'standard)))
  14160. props)
  14161. ;; Get the special properties, like TODO and TAGS.
  14162. (when (memq which '(nil all special))
  14163. (when (or (not specific) (string= specific "CLOCKSUM"))
  14164. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14165. (when clocksum
  14166. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  14167. props)))
  14168. (when specific (throw 'exit props)))
  14169. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14170. (let ((clocksumt (get-text-property (point)
  14171. :org-clock-minutes-today)))
  14172. (when clocksumt
  14173. (push (cons "CLOCKSUM_T"
  14174. (org-duration-from-minutes clocksumt))
  14175. props)))
  14176. (when specific (throw 'exit props)))
  14177. (when (or (not specific) (string= specific "ITEM"))
  14178. (let ((case-fold-search nil))
  14179. (when (looking-at org-complex-heading-regexp)
  14180. (push (cons "ITEM"
  14181. (let ((title (match-string-no-properties 4)))
  14182. (if (org-string-nw-p title)
  14183. (org-remove-tabs title)
  14184. "")))
  14185. props)))
  14186. (when specific (throw 'exit props)))
  14187. (when (or (not specific) (string= specific "TODO"))
  14188. (let ((case-fold-search nil))
  14189. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14190. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14191. (when specific (throw 'exit props)))
  14192. (when (or (not specific) (string= specific "PRIORITY"))
  14193. (push (cons "PRIORITY"
  14194. (if (looking-at org-priority-regexp)
  14195. (match-string-no-properties 2)
  14196. (char-to-string org-default-priority)))
  14197. props)
  14198. (when specific (throw 'exit props)))
  14199. (when (or (not specific) (string= specific "FILE"))
  14200. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14201. props)
  14202. (when specific (throw 'exit props)))
  14203. (when (or (not specific) (string= specific "TAGS"))
  14204. (let ((value (org-string-nw-p (org-get-tags-string))))
  14205. (when value (push (cons "TAGS" value) props)))
  14206. (when specific (throw 'exit props)))
  14207. (when (or (not specific) (string= specific "ALLTAGS"))
  14208. (let ((value (org-get-tags-at)))
  14209. (when value
  14210. (push (cons "ALLTAGS"
  14211. (format ":%s:" (mapconcat #'identity value ":")))
  14212. props)))
  14213. (when specific (throw 'exit props)))
  14214. (when (or (not specific) (string= specific "BLOCKED"))
  14215. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14216. (when specific (throw 'exit props)))
  14217. (when (or (not specific)
  14218. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14219. (forward-line)
  14220. (when (looking-at-p org-planning-line-re)
  14221. (end-of-line)
  14222. (let ((bol (line-beginning-position))
  14223. ;; Backward compatibility: time keywords used to
  14224. ;; be configurable (before 8.3). Make sure we
  14225. ;; get the correct keyword.
  14226. (key-assoc `(("CLOSED" . ,org-closed-string)
  14227. ("DEADLINE" . ,org-deadline-string)
  14228. ("SCHEDULED" . ,org-scheduled-string))))
  14229. (dolist (pair (if specific (list (assoc specific key-assoc))
  14230. key-assoc))
  14231. (save-excursion
  14232. (when (search-backward (cdr pair) bol t)
  14233. (goto-char (match-end 0))
  14234. (skip-chars-forward " \t")
  14235. (and (looking-at org-ts-regexp-both)
  14236. (push (cons (car pair)
  14237. (match-string-no-properties 0))
  14238. props)))))))
  14239. (when specific (throw 'exit props)))
  14240. (when (or (not specific)
  14241. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14242. (let ((find-ts
  14243. (lambda (end ts)
  14244. ;; Fix next time-stamp before END. TS is the
  14245. ;; list of time-stamps found so far.
  14246. (let ((ts ts)
  14247. (regexp (cond
  14248. ((string= specific "TIMESTAMP")
  14249. org-ts-regexp)
  14250. ((string= specific "TIMESTAMP_IA")
  14251. org-ts-regexp-inactive)
  14252. ((assoc "TIMESTAMP_IA" ts)
  14253. org-ts-regexp)
  14254. ((assoc "TIMESTAMP" ts)
  14255. org-ts-regexp-inactive)
  14256. (t org-ts-regexp-both))))
  14257. (catch 'next
  14258. (while (re-search-forward regexp end t)
  14259. (backward-char)
  14260. (let ((object (org-element-context)))
  14261. ;; Accept to match timestamps in node
  14262. ;; properties, too.
  14263. (when (memq (org-element-type object)
  14264. '(node-property timestamp))
  14265. (let ((type
  14266. (org-element-property :type object)))
  14267. (cond
  14268. ((and (memq type '(active active-range))
  14269. (not (equal specific "TIMESTAMP_IA")))
  14270. (unless (assoc "TIMESTAMP" ts)
  14271. (push (cons "TIMESTAMP"
  14272. (org-element-property
  14273. :raw-value object))
  14274. ts)
  14275. (when specific (throw 'exit ts))))
  14276. ((and (memq type '(inactive inactive-range))
  14277. (not (string= specific "TIMESTAMP")))
  14278. (unless (assoc "TIMESTAMP_IA" ts)
  14279. (push (cons "TIMESTAMP_IA"
  14280. (org-element-property
  14281. :raw-value object))
  14282. ts)
  14283. (when specific (throw 'exit ts))))))
  14284. ;; Both timestamp types are found,
  14285. ;; move to next part.
  14286. (when (= (length ts) 2) (throw 'next ts)))))
  14287. ts)))))
  14288. (goto-char beg)
  14289. ;; First look for timestamps within headline.
  14290. (let ((ts (funcall find-ts (line-end-position) nil)))
  14291. (if (= (length ts) 2) (setq props (nconc ts props))
  14292. ;; Then find timestamps in the section, skipping
  14293. ;; planning line.
  14294. (let ((end (save-excursion (outline-next-heading))))
  14295. (forward-line)
  14296. (when (looking-at-p org-planning-line-re) (forward-line))
  14297. (setq props (nconc (funcall find-ts end ts) props))))))))
  14298. ;; Get the standard properties, like :PROP:.
  14299. (when (memq which '(nil all standard))
  14300. ;; If we are looking after a specific property, delegate
  14301. ;; to `org-entry-get', which is faster. However, make an
  14302. ;; exception for "CATEGORY", since it can be also set
  14303. ;; through keywords (i.e. #+CATEGORY).
  14304. (if (and specific (not (equal specific "CATEGORY")))
  14305. (let ((value (org-entry-get beg specific nil t)))
  14306. (throw 'exit (and value (list (cons specific value)))))
  14307. (let ((range (org-get-property-block beg)))
  14308. (when range
  14309. (let ((end (cdr range)) seen-base)
  14310. (goto-char (car range))
  14311. ;; Unlike to `org--update-property-plist', we
  14312. ;; handle the case where base values is found
  14313. ;; after its extension. We also forbid standard
  14314. ;; properties to be named as special properties.
  14315. (while (re-search-forward org-property-re end t)
  14316. (let* ((key (upcase (match-string-no-properties 2)))
  14317. (extendp (string-match-p "\\+\\'" key))
  14318. (key-base (if extendp (substring key 0 -1) key))
  14319. (value (match-string-no-properties 3)))
  14320. (cond
  14321. ((member-ignore-case key-base org-special-properties))
  14322. (extendp
  14323. (setq props
  14324. (org--update-property-plist key value props)))
  14325. ((member key seen-base))
  14326. (t (push key seen-base)
  14327. (let ((p (assoc-string key props t)))
  14328. (if p (setcdr p (concat value " " (cdr p)))
  14329. (push (cons key value) props))))))))))))
  14330. (unless (assoc "CATEGORY" props)
  14331. (push (cons "CATEGORY" (org-get-category beg)) props)
  14332. (when (string= specific "CATEGORY") (throw 'exit props)))
  14333. ;; Return value.
  14334. props)))))
  14335. (defun org--property-local-values (property literal-nil)
  14336. "Return value for PROPERTY in current entry.
  14337. Value is a list whose car is the base value for PROPERTY and cdr
  14338. a list of accumulated values. Return nil if neither is found in
  14339. the entry. Also return nil when PROPERTY is set to \"nil\",
  14340. unless LITERAL-NIL is non-nil."
  14341. (let ((range (org-get-property-block)))
  14342. (when range
  14343. (goto-char (car range))
  14344. (let* ((case-fold-search t)
  14345. (end (cdr range))
  14346. (value
  14347. ;; Base value.
  14348. (save-excursion
  14349. (let ((v (and (re-search-forward
  14350. (org-re-property property nil t) end t)
  14351. (match-string-no-properties 3))))
  14352. (list (if literal-nil v (org-not-nil v)))))))
  14353. ;; Find additional values.
  14354. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14355. (while (re-search-forward property+ end t)
  14356. (push (match-string-no-properties 3) value)))
  14357. ;; Return final values.
  14358. (and (not (equal value '(nil))) (nreverse value))))))
  14359. (defun org--property-global-value (property literal-nil)
  14360. "Return value for PROPERTY in current buffer.
  14361. Return value is a string. Return nil if property is not set
  14362. globally. Also return nil when PROPERTY is set to \"nil\",
  14363. unless LITERAL-NIL is non-nil."
  14364. (let ((global
  14365. (cdr (or (assoc-string property org-file-properties t)
  14366. (assoc-string property org-global-properties t)
  14367. (assoc-string property org-global-properties-fixed t)))))
  14368. (if literal-nil global (org-not-nil global))))
  14369. (defun org-entry-get (pom property &optional inherit literal-nil)
  14370. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14371. If INHERIT is non-nil and the entry does not have the property,
  14372. then also check higher levels of the hierarchy. If INHERIT is
  14373. the symbol `selective', use inheritance only if the setting in
  14374. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14375. If the property is present but empty, the return value is the
  14376. empty string. If the property is not present at all, nil is
  14377. returned. In any other case, return the value as a string.
  14378. Search is case-insensitive.
  14379. If LITERAL-NIL is set, return the string value \"nil\" as
  14380. a string, do not interpret it as the list atom nil. This is used
  14381. for inheritance when a \"nil\" value can supersede a non-nil
  14382. value higher up the hierarchy."
  14383. (org-with-point-at pom
  14384. (cond
  14385. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14386. ;; We need a special property. Use `org-entry-properties' to
  14387. ;; retrieve it, but specify the wanted property.
  14388. (cdr (assoc-string property (org-entry-properties nil property))))
  14389. ((and inherit
  14390. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14391. (org-entry-get-with-inheritance property literal-nil))
  14392. (t
  14393. (let* ((local (org--property-local-values property literal-nil))
  14394. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14395. (if literal-nil value (org-not-nil value)))))))
  14396. (defun org-property-or-variable-value (var &optional inherit)
  14397. "Check if there is a property fixing the value of VAR.
  14398. If yes, return this value. If not, return the current value of the variable."
  14399. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14400. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14401. (read prop)
  14402. (symbol-value var))))
  14403. (defun org-entry-delete (pom property)
  14404. "Delete PROPERTY from entry at point-or-marker POM.
  14405. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14406. non-nil when a property was removed."
  14407. (org-with-point-at pom
  14408. (pcase (org-get-property-block)
  14409. (`(,begin . ,origin)
  14410. (let* ((end (copy-marker origin))
  14411. (re (org-re-property
  14412. (concat (regexp-quote property) "\\+?") t t)))
  14413. (goto-char begin)
  14414. (while (re-search-forward re end t)
  14415. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14416. ;; If drawer is empty, remove it altogether.
  14417. (when (= begin end)
  14418. (delete-region (line-beginning-position 0)
  14419. (line-beginning-position 2)))
  14420. ;; Return non-nil if some property was removed.
  14421. (prog1 (/= end origin) (set-marker end nil))))
  14422. (_ nil))))
  14423. ;; Multi-values properties are properties that contain multiple values
  14424. ;; These values are assumed to be single words, separated by whitespace.
  14425. (defun org-entry-add-to-multivalued-property (pom property value)
  14426. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14427. (let* ((old (org-entry-get pom property))
  14428. (values (and old (org-split-string old "[ \t]"))))
  14429. (setq value (org-entry-protect-space value))
  14430. (unless (member value values)
  14431. (setq values (append values (list value)))
  14432. (org-entry-put pom property
  14433. (mapconcat 'identity values " ")))))
  14434. (defun org-entry-remove-from-multivalued-property (pom property value)
  14435. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14436. (let* ((old (org-entry-get pom property))
  14437. (values (and old (org-split-string old "[ \t]"))))
  14438. (setq value (org-entry-protect-space value))
  14439. (when (member value values)
  14440. (setq values (delete value values))
  14441. (org-entry-put pom property
  14442. (mapconcat 'identity values " ")))))
  14443. (defun org-entry-member-in-multivalued-property (pom property value)
  14444. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14445. (let* ((old (org-entry-get pom property))
  14446. (values (and old (org-split-string old "[ \t]"))))
  14447. (setq value (org-entry-protect-space value))
  14448. (member value values)))
  14449. (defun org-entry-get-multivalued-property (pom property)
  14450. "Return a list of values in a multivalued property."
  14451. (let* ((value (org-entry-get pom property))
  14452. (values (and value (org-split-string value "[ \t]"))))
  14453. (mapcar 'org-entry-restore-space values)))
  14454. (defun org-entry-put-multivalued-property (pom property &rest values)
  14455. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14456. VALUES should be a list of strings. Spaces will be protected."
  14457. (org-entry-put pom property
  14458. (mapconcat 'org-entry-protect-space values " "))
  14459. (let* ((value (org-entry-get pom property))
  14460. (values (and value (org-split-string value "[ \t]"))))
  14461. (mapcar 'org-entry-restore-space values)))
  14462. (defun org-entry-protect-space (s)
  14463. "Protect spaces and newline in string S."
  14464. (while (string-match " " s)
  14465. (setq s (replace-match "%20" t t s)))
  14466. (while (string-match "\n" s)
  14467. (setq s (replace-match "%0A" t t s)))
  14468. s)
  14469. (defun org-entry-restore-space (s)
  14470. "Restore spaces and newline in string S."
  14471. (while (string-match "%20" s)
  14472. (setq s (replace-match " " t t s)))
  14473. (while (string-match "%0A" s)
  14474. (setq s (replace-match "\n" t t s)))
  14475. s)
  14476. (defvar org-entry-property-inherited-from (make-marker)
  14477. "Marker pointing to the entry from where a property was inherited.
  14478. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14479. location of the entry where the inheritance search matched. If there was
  14480. no match, the marker will point nowhere.
  14481. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14482. is set.")
  14483. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14484. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14485. The search will stop at the first ancestor which has the property defined.
  14486. If the value found is \"nil\", return nil to show that the property
  14487. should be considered as undefined (this is the meaning of nil here).
  14488. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14489. (move-marker org-entry-property-inherited-from nil)
  14490. (org-with-wide-buffer
  14491. (let (value)
  14492. (catch 'exit
  14493. (while t
  14494. (let ((v (org--property-local-values property literal-nil)))
  14495. (when v
  14496. (setq value
  14497. (concat (mapconcat #'identity (delq nil v) " ")
  14498. (and value " ")
  14499. value)))
  14500. (cond
  14501. ((car v)
  14502. (org-back-to-heading t)
  14503. (move-marker org-entry-property-inherited-from (point))
  14504. (throw 'exit nil))
  14505. ((org-up-heading-safe))
  14506. (t
  14507. (let ((global (org--property-global-value property literal-nil)))
  14508. (cond ((not global))
  14509. (value (setq value (concat global " " value)))
  14510. (t (setq value global))))
  14511. (throw 'exit nil))))))
  14512. (if literal-nil value (org-not-nil value)))))
  14513. (defvar org-property-changed-functions nil
  14514. "Hook called when the value of a property has changed.
  14515. Each hook function should accept two arguments, the name of the property
  14516. and the new value.")
  14517. (defun org-entry-put (pom property value)
  14518. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14519. If the value is nil, it is converted to the empty string. If it
  14520. is not a string, an error is raised. Also raise an error on
  14521. invalid property names.
  14522. PROPERTY can be any regular property (see
  14523. `org-special-properties'). It can also be \"TODO\",
  14524. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14525. For the last two properties, VALUE may have any of the special
  14526. values \"earlier\" and \"later\". The function then increases or
  14527. decreases scheduled or deadline date by one day."
  14528. (cond ((null value) (setq value ""))
  14529. ((not (stringp value)) (error "Properties values should be strings"))
  14530. ((not (org--valid-property-p property))
  14531. (user-error "Invalid property name: \"%s\"" property)))
  14532. (org-with-point-at pom
  14533. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14534. (org-back-to-heading t)
  14535. (org-with-limited-levels (org-back-to-heading t)))
  14536. (let ((beg (point)))
  14537. (cond
  14538. ((equal property "TODO")
  14539. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14540. ((not (member value org-todo-keywords-1))
  14541. (user-error "\"%s\" is not a valid TODO state" value)))
  14542. (org-todo value)
  14543. (org-set-tags nil 'align))
  14544. ((equal property "PRIORITY")
  14545. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14546. (org-set-tags nil 'align))
  14547. ((equal property "SCHEDULED")
  14548. (forward-line)
  14549. (if (and (looking-at-p org-planning-line-re)
  14550. (re-search-forward
  14551. org-scheduled-time-regexp (line-end-position) t))
  14552. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14553. ((string= value "later") (org-timestamp-change 1 'day))
  14554. ((string= value "") (org-schedule '(4)))
  14555. (t (org-schedule nil value)))
  14556. (if (member value '("earlier" "later" ""))
  14557. (call-interactively #'org-schedule)
  14558. (org-schedule nil value))))
  14559. ((equal property "DEADLINE")
  14560. (forward-line)
  14561. (if (and (looking-at-p org-planning-line-re)
  14562. (re-search-forward
  14563. org-deadline-time-regexp (line-end-position) t))
  14564. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14565. ((string= value "later") (org-timestamp-change 1 'day))
  14566. ((string= value "") (org-deadline '(4)))
  14567. (t (org-deadline nil value)))
  14568. (if (member value '("earlier" "later" ""))
  14569. (call-interactively #'org-deadline)
  14570. (org-deadline nil value))))
  14571. ((member property org-special-properties)
  14572. (error "The %s property cannot be set with `org-entry-put'" property))
  14573. (t
  14574. (let* ((range (org-get-property-block beg 'force))
  14575. (end (cdr range))
  14576. (case-fold-search t))
  14577. (goto-char (car range))
  14578. (if (re-search-forward (org-re-property property nil t) end t)
  14579. (progn (delete-region (match-beginning 0) (match-end 0))
  14580. (goto-char (match-beginning 0)))
  14581. (goto-char end)
  14582. (insert "\n")
  14583. (backward-char))
  14584. (insert ":" property ":")
  14585. (when value (insert " " value))
  14586. (org-indent-line)))))
  14587. (run-hook-with-args 'org-property-changed-functions property value)))
  14588. (defun org-buffer-property-keys
  14589. (&optional specials defaults columns ignore-malformed)
  14590. "Get all property keys in the current buffer.
  14591. When SPECIALS is non-nil, also list the special properties that
  14592. reflect things like tags and TODO state.
  14593. When DEFAULTS is non-nil, also include properties that has
  14594. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14595. DESCRIPTION, LOCATION, and LOGGING and others.
  14596. When COLUMNS in non-nil, also include property names given in
  14597. COLUMN formats in the current buffer.
  14598. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14599. automatically performed, such drawers will be silently ignored."
  14600. (let ((case-fold-search t)
  14601. (props (append
  14602. (and specials org-special-properties)
  14603. (and defaults (cons org-effort-property org-default-properties))
  14604. nil)))
  14605. (org-with-wide-buffer
  14606. (goto-char (point-min))
  14607. (while (re-search-forward org-property-start-re nil t)
  14608. (let ((range (org-get-property-block)))
  14609. (catch 'skip
  14610. (unless range
  14611. (when (and (not ignore-malformed)
  14612. (not (org-before-first-heading-p))
  14613. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14614. (line-beginning-position))))
  14615. (org-get-property-block nil t))
  14616. (throw 'skip nil))
  14617. (goto-char (car range))
  14618. (let ((begin (car range))
  14619. (end (cdr range)))
  14620. ;; Make sure that found property block is not located
  14621. ;; before current point, as it would generate an infloop.
  14622. ;; It can happen, for example, in the following
  14623. ;; situation:
  14624. ;;
  14625. ;; * Headline
  14626. ;; :PROPERTIES:
  14627. ;; ...
  14628. ;; :END:
  14629. ;; *************** Inlinetask
  14630. ;; #+BEGIN_EXAMPLE
  14631. ;; :PROPERTIES:
  14632. ;; #+END_EXAMPLE
  14633. ;;
  14634. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14635. (while (< (point) end)
  14636. (let ((p (progn (looking-at org-property-re)
  14637. (match-string-no-properties 2))))
  14638. ;; Only add true property name, not extension symbol.
  14639. (push (if (not (string-match-p "\\+\\'" p)) p
  14640. (substring p 0 -1))
  14641. props))
  14642. (forward-line))))
  14643. (outline-next-heading)))
  14644. (when columns
  14645. (goto-char (point-min))
  14646. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14647. (let ((element (org-element-at-point)))
  14648. (when (memq (org-element-type element) '(keyword node-property))
  14649. (let ((value (org-element-property :value element))
  14650. (start 0))
  14651. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14652. (setq start (match-end 0))
  14653. (let ((p (match-string-no-properties 1 value)))
  14654. (unless (member-ignore-case p org-special-properties)
  14655. (push p props))))))))))
  14656. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14657. (defun org-property-values (key)
  14658. "List all non-nil values of property KEY in current buffer."
  14659. (org-with-wide-buffer
  14660. (goto-char (point-min))
  14661. (let ((case-fold-search t)
  14662. (re (org-re-property key))
  14663. values)
  14664. (while (re-search-forward re nil t)
  14665. (push (org-entry-get (point) key) values))
  14666. (delete-dups values))))
  14667. (defun org-insert-property-drawer ()
  14668. "Insert a property drawer into the current entry."
  14669. (org-with-wide-buffer
  14670. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14671. (org-back-to-heading t)
  14672. (org-with-limited-levels (org-back-to-heading t)))
  14673. (forward-line)
  14674. (when (looking-at-p org-planning-line-re) (forward-line))
  14675. (unless (looking-at-p org-property-drawer-re)
  14676. ;; Make sure we start editing a line from current entry, not from
  14677. ;; next one. It prevents extending text properties or overlays
  14678. ;; belonging to the latter.
  14679. (when (bolp) (backward-char))
  14680. (let ((begin (1+ (point)))
  14681. (inhibit-read-only t))
  14682. (insert "\n:PROPERTIES:\n:END:")
  14683. (when (eobp) (insert "\n"))
  14684. (org-indent-region begin (point))))))
  14685. (defun org-insert-drawer (&optional arg drawer)
  14686. "Insert a drawer at point.
  14687. When optional argument ARG is non-nil, insert a property drawer.
  14688. Optional argument DRAWER, when non-nil, is a string representing
  14689. drawer's name. Otherwise, the user is prompted for a name.
  14690. If a region is active, insert the drawer around that region
  14691. instead.
  14692. Point is left between drawer's boundaries."
  14693. (interactive "P")
  14694. (let* ((drawer (if arg "PROPERTIES"
  14695. (or drawer (read-from-minibuffer "Drawer: ")))))
  14696. (cond
  14697. ;; With C-u, fall back on `org-insert-property-drawer'
  14698. (arg (org-insert-property-drawer))
  14699. ;; Check validity of suggested drawer's name.
  14700. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14701. (user-error "Invalid drawer name"))
  14702. ;; With an active region, insert a drawer at point.
  14703. ((not (org-region-active-p))
  14704. (progn
  14705. (unless (bolp) (insert "\n"))
  14706. (insert (format ":%s:\n\n:END:\n" drawer))
  14707. (forward-line -2)))
  14708. ;; Otherwise, insert the drawer at point
  14709. (t
  14710. (let ((rbeg (region-beginning))
  14711. (rend (copy-marker (region-end))))
  14712. (unwind-protect
  14713. (progn
  14714. (goto-char rbeg)
  14715. (beginning-of-line)
  14716. (when (save-excursion
  14717. (re-search-forward org-outline-regexp-bol rend t))
  14718. (user-error "Drawers cannot contain headlines"))
  14719. ;; Position point at the beginning of the first
  14720. ;; non-blank line in region. Insert drawer's opening
  14721. ;; there, then indent it.
  14722. (org-skip-whitespace)
  14723. (beginning-of-line)
  14724. (insert ":" drawer ":\n")
  14725. (forward-line -1)
  14726. (indent-for-tab-command)
  14727. ;; Move point to the beginning of the first blank line
  14728. ;; after the last non-blank line in region. Insert
  14729. ;; drawer's closing, then indent it.
  14730. (goto-char rend)
  14731. (skip-chars-backward " \r\t\n")
  14732. (insert "\n:END:")
  14733. (deactivate-mark t)
  14734. (indent-for-tab-command)
  14735. (unless (eolp) (insert "\n")))
  14736. ;; Clear marker, whatever the outcome of insertion is.
  14737. (set-marker rend nil)))))))
  14738. (defvar org-property-set-functions-alist nil
  14739. "Property set function alist.
  14740. Each entry should have the following format:
  14741. (PROPERTY . READ-FUNCTION)
  14742. The read function will be called with the same argument as
  14743. `org-completing-read'.")
  14744. (defun org-set-property-function (property)
  14745. "Get the function that should be used to set PROPERTY.
  14746. This is computed according to `org-property-set-functions-alist'."
  14747. (or (cdr (assoc property org-property-set-functions-alist))
  14748. 'org-completing-read))
  14749. (defun org-read-property-value (property)
  14750. "Read PROPERTY value from user."
  14751. (let* ((completion-ignore-case t)
  14752. (allowed (org-property-get-allowed-values nil property 'table))
  14753. (cur (org-entry-get nil property))
  14754. (prompt (concat property " value"
  14755. (if (and cur (string-match "\\S-" cur))
  14756. (concat " [" cur "]") "") ": "))
  14757. (set-function (org-set-property-function property))
  14758. (val (if allowed
  14759. (funcall set-function prompt allowed nil
  14760. (not (get-text-property 0 'org-unrestricted
  14761. (caar allowed))))
  14762. (funcall set-function prompt
  14763. (mapcar 'list (org-property-values property))
  14764. nil nil "" nil cur))))
  14765. (org-trim val)))
  14766. (defvar org-last-set-property nil)
  14767. (defvar org-last-set-property-value nil)
  14768. (defun org-read-property-name ()
  14769. "Read a property name."
  14770. (let ((completion-ignore-case t)
  14771. (default-prop (or (and (org-at-property-p)
  14772. (match-string-no-properties 2))
  14773. org-last-set-property)))
  14774. (org-completing-read
  14775. (concat "Property"
  14776. (if default-prop (concat " [" default-prop "]") "")
  14777. ": ")
  14778. (mapcar #'list (org-buffer-property-keys nil t t))
  14779. nil nil nil nil default-prop)))
  14780. (defun org-set-property-and-value (use-last)
  14781. "Allow to set [PROPERTY]: [value] direction from prompt.
  14782. When use-default, don't even ask, just use the last
  14783. \"[PROPERTY]: [value]\" string from the history."
  14784. (interactive "P")
  14785. (let* ((completion-ignore-case t)
  14786. (pv (or (and use-last org-last-set-property-value)
  14787. (org-completing-read
  14788. "Enter a \"[Property]: [value]\" pair: "
  14789. nil nil nil nil nil
  14790. org-last-set-property-value)))
  14791. prop val)
  14792. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14793. (setq prop (match-string 1 pv)
  14794. val (match-string 2 pv))
  14795. (org-set-property prop val))))
  14796. (defun org-set-property (property value)
  14797. "In the current entry, set PROPERTY to VALUE.
  14798. When called interactively, this will prompt for a property name, offering
  14799. completion on existing and default properties. And then it will prompt
  14800. for a value, offering completion either on allowed values (via an inherited
  14801. xxx_ALL property) or on existing values in other instances of this property
  14802. in the current file.
  14803. Throw an error when trying to set a property with an invalid name."
  14804. (interactive (list nil nil))
  14805. (let ((property (or property (org-read-property-name))))
  14806. ;; `org-entry-put' also makes the following check, but this one
  14807. ;; avoids polluting `org-last-set-property' and
  14808. ;; `org-last-set-property-value' needlessly.
  14809. (unless (org--valid-property-p property)
  14810. (user-error "Invalid property name: \"%s\"" property))
  14811. (let ((value (or value (org-read-property-value property)))
  14812. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14813. (setq org-last-set-property property)
  14814. (setq org-last-set-property-value (concat property ": " value))
  14815. ;; Possibly postprocess the inserted value:
  14816. (when fn (setq value (funcall fn value)))
  14817. (unless (equal (org-entry-get nil property) value)
  14818. (org-entry-put nil property value)))))
  14819. (defun org-find-property (property &optional value)
  14820. "Find first entry in buffer that sets PROPERTY.
  14821. When optional argument VALUE is non-nil, only consider an entry
  14822. if it contains PROPERTY set to this value. If PROPERTY should be
  14823. explicitly set to nil, use string \"nil\" for VALUE.
  14824. Return position where the entry begins, or nil if there is no
  14825. such entry. If narrowing is in effect, only search the visible
  14826. part of the buffer."
  14827. (save-excursion
  14828. (goto-char (point-min))
  14829. (let ((case-fold-search t)
  14830. (re (org-re-property property nil (not value) value)))
  14831. (catch 'exit
  14832. (while (re-search-forward re nil t)
  14833. (when (if value (org-at-property-p)
  14834. (org-entry-get (point) property nil t))
  14835. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14836. (defun org-delete-property (property)
  14837. "In the current entry, delete PROPERTY."
  14838. (interactive
  14839. (let* ((completion-ignore-case t)
  14840. (cat (org-entry-get (point) "CATEGORY"))
  14841. (props0 (org-entry-properties nil 'standard))
  14842. (props (if cat props0
  14843. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14844. (prop (if (< 1 (length props))
  14845. (completing-read "Property: " props nil t)
  14846. (caar props))))
  14847. (list prop)))
  14848. (if (not property)
  14849. (message "No property to delete in this entry")
  14850. (org-entry-delete nil property)
  14851. (message "Property \"%s\" deleted" property)))
  14852. (defun org-delete-property-globally (property)
  14853. "Remove PROPERTY globally, from all entries.
  14854. This function ignores narrowing, if any."
  14855. (interactive
  14856. (let* ((completion-ignore-case t)
  14857. (prop (completing-read
  14858. "Globally remove property: "
  14859. (mapcar #'list (org-buffer-property-keys)))))
  14860. (list prop)))
  14861. (org-with-wide-buffer
  14862. (goto-char (point-min))
  14863. (let ((count 0)
  14864. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  14865. (while (re-search-forward re nil t)
  14866. (when (org-entry-delete (point) property) (cl-incf count)))
  14867. (message "Property \"%s\" removed from %d entries" property count))))
  14868. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  14869. (defun org-compute-property-at-point ()
  14870. "Compute the property at point.
  14871. This looks for an enclosing column format, extracts the operator and
  14872. then applies it to the property in the column format's scope."
  14873. (interactive)
  14874. (unless (org-at-property-p)
  14875. (user-error "Not at a property"))
  14876. (let ((prop (match-string-no-properties 2)))
  14877. (org-columns-get-format-and-top-level)
  14878. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  14879. (user-error "No operator defined for property %s" prop))
  14880. (org-columns-compute prop)))
  14881. (defvar org-property-allowed-value-functions nil
  14882. "Hook for functions supplying allowed values for a specific property.
  14883. The functions must take a single argument, the name of the property, and
  14884. return a flat list of allowed values. If \":ETC\" is one of
  14885. the values, this means that these values are intended as defaults for
  14886. completion, but that other values should be allowed too.
  14887. The functions must return nil if they are not responsible for this
  14888. property.")
  14889. (defun org-property-get-allowed-values (pom property &optional table)
  14890. "Get allowed values for the property PROPERTY.
  14891. When TABLE is non-nil, return an alist that can directly be used for
  14892. completion."
  14893. (let (vals)
  14894. (cond
  14895. ((equal property "TODO")
  14896. (setq vals (org-with-point-at pom
  14897. (append org-todo-keywords-1 '("")))))
  14898. ((equal property "PRIORITY")
  14899. (let ((n org-lowest-priority))
  14900. (while (>= n org-highest-priority)
  14901. (push (char-to-string n) vals)
  14902. (setq n (1- n)))))
  14903. ((equal property "CATEGORY"))
  14904. ((member property org-special-properties))
  14905. ((setq vals (run-hook-with-args-until-success
  14906. 'org-property-allowed-value-functions property)))
  14907. (t
  14908. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  14909. (when (and vals (string-match "\\S-" vals))
  14910. (setq vals (car (read-from-string (concat "(" vals ")"))))
  14911. (setq vals (mapcar (lambda (x)
  14912. (cond ((stringp x) x)
  14913. ((numberp x) (number-to-string x))
  14914. ((symbolp x) (symbol-name x))
  14915. (t "???")))
  14916. vals)))))
  14917. (when (member ":ETC" vals)
  14918. (setq vals (remove ":ETC" vals))
  14919. (org-add-props (car vals) '(org-unrestricted t)))
  14920. (if table (mapcar 'list vals) vals)))
  14921. (defun org-property-previous-allowed-value (&optional _previous)
  14922. "Switch to the next allowed value for this property."
  14923. (interactive)
  14924. (org-property-next-allowed-value t))
  14925. (defun org-property-next-allowed-value (&optional previous)
  14926. "Switch to the next allowed value for this property."
  14927. (interactive)
  14928. (unless (org-at-property-p)
  14929. (user-error "Not at a property"))
  14930. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  14931. (key (match-string 2))
  14932. (value (match-string 3))
  14933. (allowed (or (org-property-get-allowed-values (point) key)
  14934. (and (member value '("[ ]" "[-]" "[X]"))
  14935. '("[ ]" "[X]"))))
  14936. (heading (save-match-data (nth 4 (org-heading-components))))
  14937. nval)
  14938. (unless allowed
  14939. (user-error "Allowed values for this property have not been defined"))
  14940. (when previous (setq allowed (reverse allowed)))
  14941. (when (member value allowed)
  14942. (setq nval (car (cdr (member value allowed)))))
  14943. (setq nval (or nval (car allowed)))
  14944. (when (equal nval value)
  14945. (user-error "Only one allowed value for this property"))
  14946. (org-at-property-p)
  14947. (replace-match (concat " :" key ": " nval) t t)
  14948. (org-indent-line)
  14949. (beginning-of-line 1)
  14950. (skip-chars-forward " \t")
  14951. (when (equal prop org-effort-property)
  14952. (org-refresh-property
  14953. '((effort . identity)
  14954. (effort-minutes . org-duration-to-minutes))
  14955. nval)
  14956. (when (string= org-clock-current-task heading)
  14957. (setq org-clock-effort nval)
  14958. (org-clock-update-mode-line)))
  14959. (run-hook-with-args 'org-property-changed-functions key nval)))
  14960. (defun org-find-olp (path &optional this-buffer)
  14961. "Return a marker pointing to the entry at outline path OLP.
  14962. If anything goes wrong, throw an error.
  14963. You can wrap this call to catch the error like this:
  14964. (condition-case msg
  14965. (org-mobile-locate-entry (match-string 4))
  14966. (error (nth 1 msg)))
  14967. The return value will then be either a string with the error message,
  14968. or a marker if everything is OK.
  14969. If THIS-BUFFER is set, the outline path does not contain a file,
  14970. only headings."
  14971. (let* ((file (if this-buffer buffer-file-name (pop path)))
  14972. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  14973. (level 1)
  14974. (lmin 1)
  14975. (lmax 1)
  14976. end found flevel)
  14977. (unless buffer (error "File not found :%s" file))
  14978. (with-current-buffer buffer
  14979. (unless (derived-mode-p 'org-mode)
  14980. (error "Buffer %s needs to be in Org mode" buffer))
  14981. (org-with-wide-buffer
  14982. (goto-char (point-min))
  14983. (dolist (heading path)
  14984. (let ((re (format org-complex-heading-regexp-format
  14985. (regexp-quote heading)))
  14986. (cnt 0))
  14987. (while (re-search-forward re end t)
  14988. (setq level (- (match-end 1) (match-beginning 1)))
  14989. (when (and (>= level lmin) (<= level lmax))
  14990. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  14991. (when (= cnt 0)
  14992. (error "Heading not found on level %d: %s" lmax heading))
  14993. (when (> cnt 1)
  14994. (error "Heading not unique on level %d: %s" lmax heading))
  14995. (goto-char found)
  14996. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  14997. (setq end (save-excursion (org-end-of-subtree t t)))))
  14998. (when (org-at-heading-p)
  14999. (point-marker))))))
  15000. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15001. "Find node HEADING in BUFFER.
  15002. Return a marker to the heading if it was found, or nil if not.
  15003. If POS-ONLY is set, return just the position instead of a marker.
  15004. The heading text must match exact, but it may have a TODO keyword,
  15005. a priority cookie and tags in the standard locations."
  15006. (with-current-buffer (or buffer (current-buffer))
  15007. (org-with-wide-buffer
  15008. (goto-char (point-min))
  15009. (let (case-fold-search)
  15010. (when (re-search-forward
  15011. (format org-complex-heading-regexp-format
  15012. (regexp-quote heading)) nil t)
  15013. (if pos-only
  15014. (match-beginning 0)
  15015. (move-marker (make-marker) (match-beginning 0))))))))
  15016. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15017. "Find Org node headline HEADING in all .org files in directory DIR.
  15018. When the target headline is found, return a marker to this location."
  15019. (let ((files (directory-files (or dir default-directory)
  15020. t "\\`[^.#].*\\.org\\'"))
  15021. visiting m buffer)
  15022. (catch 'found
  15023. (dolist (file files)
  15024. (message "trying %s" file)
  15025. (setq visiting (org-find-base-buffer-visiting file))
  15026. (setq buffer (or visiting (find-file-noselect file)))
  15027. (setq m (org-find-exact-headline-in-buffer
  15028. heading buffer))
  15029. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15030. (and m (throw 'found m))))))
  15031. (defun org-find-entry-with-id (ident)
  15032. "Locate the entry that contains the ID property with exact value IDENT.
  15033. IDENT can be a string, a symbol or a number, this function will search for
  15034. the string representation of it.
  15035. Return the position where this entry starts, or nil if there is no such entry."
  15036. (interactive "sID: ")
  15037. (let ((id (cond
  15038. ((stringp ident) ident)
  15039. ((symbolp ident) (symbol-name ident))
  15040. ((numberp ident) (number-to-string ident))
  15041. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15042. (org-with-wide-buffer (org-find-property "ID" id))))
  15043. ;;;; Timestamps
  15044. (defvar org-last-changed-timestamp nil)
  15045. (defvar org-last-inserted-timestamp nil
  15046. "The last time stamp inserted with `org-insert-time-stamp'.")
  15047. (defun org-time-stamp (arg &optional inactive)
  15048. "Prompt for a date/time and insert a time stamp.
  15049. If the user specifies a time like HH:MM or if this command is
  15050. called with at least one prefix argument, the time stamp contains
  15051. the date and the time. Otherwise, only the date is included.
  15052. All parts of a date not specified by the user are filled in from
  15053. the timestamp at point, if any, or the current date/time
  15054. otherwise.
  15055. If there is already a timestamp at the cursor, it is replaced.
  15056. With two universal prefix arguments, insert an active timestamp
  15057. with the current time without prompting the user.
  15058. When called from lisp, the timestamp is inactive if INACTIVE is
  15059. non-nil."
  15060. (interactive "P")
  15061. (let* ((ts (cond
  15062. ((org-at-date-range-p t)
  15063. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15064. ((org-at-timestamp-p 'lax) (match-string 0))))
  15065. ;; Default time is either the timestamp at point or today.
  15066. ;; When entering a range, only the range start is considered.
  15067. (default-time (if (not ts) (current-time)
  15068. (apply #'encode-time (org-parse-time-string ts))))
  15069. (default-input (and ts (org-get-compact-tod ts)))
  15070. (repeater (and ts
  15071. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15072. (match-string 0 ts)))
  15073. org-time-was-given
  15074. org-end-time-was-given
  15075. (time
  15076. (and (if (equal arg '(16)) (current-time)
  15077. ;; Preserve `this-command' and `last-command'.
  15078. (let ((this-command this-command)
  15079. (last-command last-command))
  15080. (org-read-date
  15081. arg 'totime nil nil default-time default-input
  15082. inactive))))))
  15083. (cond
  15084. ((and ts
  15085. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15086. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15087. (insert "--")
  15088. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15089. (ts
  15090. ;; Make sure we're on a timestamp. When in the middle of a date
  15091. ;; range, move arbitrarily to range end.
  15092. (unless (org-at-timestamp-p 'lax)
  15093. (skip-chars-forward "-")
  15094. (org-at-timestamp-p 'lax))
  15095. (replace-match "")
  15096. (setq org-last-changed-timestamp
  15097. (org-insert-time-stamp
  15098. time (or org-time-was-given arg)
  15099. inactive nil nil (list org-end-time-was-given)))
  15100. (when repeater
  15101. (backward-char)
  15102. (insert " " repeater)
  15103. (setq org-last-changed-timestamp
  15104. (concat (substring org-last-inserted-timestamp 0 -1)
  15105. " " repeater ">")))
  15106. (message "Timestamp updated"))
  15107. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15108. (t (org-insert-time-stamp
  15109. time (or org-time-was-given arg) inactive nil nil
  15110. (list org-end-time-was-given))))))
  15111. ;; FIXME: can we use this for something else, like computing time differences?
  15112. (defun org-get-compact-tod (s)
  15113. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15114. (let* ((t1 (match-string 1 s))
  15115. (h1 (string-to-number (match-string 2 s)))
  15116. (m1 (string-to-number (match-string 3 s)))
  15117. (t2 (and (match-end 4) (match-string 5 s)))
  15118. (h2 (and t2 (string-to-number (match-string 6 s))))
  15119. (m2 (and t2 (string-to-number (match-string 7 s))))
  15120. dh dm)
  15121. (if (not t2)
  15122. t1
  15123. (setq dh (- h2 h1) dm (- m2 m1))
  15124. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15125. (concat t1 "+" (number-to-string dh)
  15126. (and (/= 0 dm) (format ":%02d" dm)))))))
  15127. (defun org-time-stamp-inactive (&optional arg)
  15128. "Insert an inactive time stamp.
  15129. An inactive time stamp is enclosed in square brackets instead of angle
  15130. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15131. does not link to the calendar and cannot be changed with the S-cursor keys.
  15132. So these are more for recording a certain time/date."
  15133. (interactive "P")
  15134. (org-time-stamp arg 'inactive))
  15135. (defvar org-date-ovl (make-overlay 1 1))
  15136. (overlay-put org-date-ovl 'face 'org-date-selected)
  15137. (delete-overlay org-date-ovl)
  15138. (defvar org-ans1) ; dynamically scoped parameter
  15139. (defvar org-ans2) ; dynamically scoped parameter
  15140. (defvar org-plain-time-of-day-regexp) ; defined below
  15141. (defvar org-overriding-default-time nil) ; dynamically scoped
  15142. (defvar org-read-date-overlay nil)
  15143. (defvar org-dcst nil) ; dynamically scoped
  15144. (defvar org-read-date-history nil)
  15145. (defvar org-read-date-final-answer nil)
  15146. (defvar org-read-date-analyze-futurep nil)
  15147. (defvar org-read-date-analyze-forced-year nil)
  15148. (defvar org-read-date-inactive)
  15149. (defvar org-read-date-minibuffer-local-map
  15150. (let* ((map (make-sparse-keymap)))
  15151. (set-keymap-parent map minibuffer-local-map)
  15152. (org-defkey map (kbd ".")
  15153. (lambda () (interactive)
  15154. ;; Are we at the beginning of the prompt?
  15155. (if (looking-back "^[^:]+: "
  15156. (let ((inhibit-field-text-motion t))
  15157. (line-beginning-position)))
  15158. (org-eval-in-calendar '(calendar-goto-today))
  15159. (insert "."))))
  15160. (org-defkey map (kbd "C-.")
  15161. (lambda () (interactive)
  15162. (org-eval-in-calendar '(calendar-goto-today))))
  15163. (org-defkey map [(meta shift left)]
  15164. (lambda () (interactive)
  15165. (org-eval-in-calendar '(calendar-backward-month 1))))
  15166. (org-defkey map [(meta shift right)]
  15167. (lambda () (interactive)
  15168. (org-eval-in-calendar '(calendar-forward-month 1))))
  15169. (org-defkey map [(meta shift up)]
  15170. (lambda () (interactive)
  15171. (org-eval-in-calendar '(calendar-backward-year 1))))
  15172. (org-defkey map [(meta shift down)]
  15173. (lambda () (interactive)
  15174. (org-eval-in-calendar '(calendar-forward-year 1))))
  15175. (org-defkey map [?\e (shift left)]
  15176. (lambda () (interactive)
  15177. (org-eval-in-calendar '(calendar-backward-month 1))))
  15178. (org-defkey map [?\e (shift right)]
  15179. (lambda () (interactive)
  15180. (org-eval-in-calendar '(calendar-forward-month 1))))
  15181. (org-defkey map [?\e (shift up)]
  15182. (lambda () (interactive)
  15183. (org-eval-in-calendar '(calendar-backward-year 1))))
  15184. (org-defkey map [?\e (shift down)]
  15185. (lambda () (interactive)
  15186. (org-eval-in-calendar '(calendar-forward-year 1))))
  15187. (org-defkey map [(shift up)]
  15188. (lambda () (interactive)
  15189. (org-eval-in-calendar '(calendar-backward-week 1))))
  15190. (org-defkey map [(shift down)]
  15191. (lambda () (interactive)
  15192. (org-eval-in-calendar '(calendar-forward-week 1))))
  15193. (org-defkey map [(shift left)]
  15194. (lambda () (interactive)
  15195. (org-eval-in-calendar '(calendar-backward-day 1))))
  15196. (org-defkey map [(shift right)]
  15197. (lambda () (interactive)
  15198. (org-eval-in-calendar '(calendar-forward-day 1))))
  15199. (org-defkey map "!"
  15200. (lambda () (interactive)
  15201. (org-eval-in-calendar '(diary-view-entries))
  15202. (message "")))
  15203. (org-defkey map ">"
  15204. (lambda () (interactive)
  15205. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15206. (org-defkey map "<"
  15207. (lambda () (interactive)
  15208. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15209. (org-defkey map "\C-v"
  15210. (lambda () (interactive)
  15211. (org-eval-in-calendar
  15212. '(calendar-scroll-left-three-months 1))))
  15213. (org-defkey map "\M-v"
  15214. (lambda () (interactive)
  15215. (org-eval-in-calendar
  15216. '(calendar-scroll-right-three-months 1))))
  15217. map)
  15218. "Keymap for minibuffer commands when using `org-read-date'.")
  15219. (defvar org-def)
  15220. (defvar org-defdecode)
  15221. (defvar org-with-time)
  15222. (defvar calendar-setup) ; Dynamically scoped.
  15223. (defun org-read-date (&optional with-time to-time from-string prompt
  15224. default-time default-input inactive)
  15225. "Read a date, possibly a time, and make things smooth for the user.
  15226. The prompt will suggest to enter an ISO date, but you can also enter anything
  15227. which will at least partially be understood by `parse-time-string'.
  15228. Unrecognized parts of the date will default to the current day, month, year,
  15229. hour and minute. If this command is called to replace a timestamp at point,
  15230. or to enter the second timestamp of a range, the default time is taken
  15231. from the existing stamp. Furthermore, the command prefers the future,
  15232. so if you are giving a date where the year is not given, and the day-month
  15233. combination is already past in the current year, it will assume you
  15234. mean next year. For details, see the manual. A few examples:
  15235. 3-2-5 --> 2003-02-05
  15236. feb 15 --> currentyear-02-15
  15237. 2/15 --> currentyear-02-15
  15238. sep 12 9 --> 2009-09-12
  15239. 12:45 --> today 12:45
  15240. 22 sept 0:34 --> currentyear-09-22 0:34
  15241. 12 --> currentyear-currentmonth-12
  15242. Fri --> nearest Friday after today
  15243. -Tue --> last Tuesday
  15244. etc.
  15245. Furthermore you can specify a relative date by giving, as the *first* thing
  15246. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15247. change in days weeks, months, years.
  15248. With a single plus or minus, the date is relative to today. With a double
  15249. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15250. +4d --> four days from today
  15251. +4 --> same as above
  15252. +2w --> two weeks from today
  15253. ++5 --> five days from default date
  15254. The function understands only English month and weekday abbreviations.
  15255. While prompting, a calendar is popped up - you can also select the
  15256. date with the mouse (button 1). The calendar shows a period of three
  15257. months. To scroll it to other months, use the keys `>' and `<'.
  15258. If you don't like the calendar, turn it off with
  15259. (setq org-read-date-popup-calendar nil)
  15260. With optional argument TO-TIME, the date will immediately be converted
  15261. to an internal time.
  15262. With an optional argument WITH-TIME, the prompt will suggest to
  15263. also insert a time. Note that when WITH-TIME is not set, you can
  15264. still enter a time, and this function will inform the calling routine
  15265. about this change. The calling routine may then choose to change the
  15266. format used to insert the time stamp into the buffer to include the time.
  15267. With optional argument FROM-STRING, read from this string instead from
  15268. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15269. the time/date that is used for everything that is not specified by the
  15270. user."
  15271. (require 'parse-time)
  15272. (let* ((org-with-time with-time)
  15273. (org-time-stamp-rounding-minutes
  15274. (if (equal org-with-time '(16))
  15275. '(0 0)
  15276. org-time-stamp-rounding-minutes))
  15277. (org-dcst org-display-custom-times)
  15278. (ct (org-current-time))
  15279. (org-def (or org-overriding-default-time default-time ct))
  15280. (org-defdecode (decode-time org-def))
  15281. (cur-frame (selected-frame))
  15282. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15283. (calendar-setup
  15284. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15285. (calendar-move-hook nil)
  15286. (calendar-view-diary-initially-flag nil)
  15287. (calendar-view-holidays-initially-flag nil)
  15288. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15289. ;; Rationalize `org-def' and `org-defdecode', if required.
  15290. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15291. (setf (nth 2 org-defdecode) -1)
  15292. (setf (nth 1 org-defdecode) 59)
  15293. (setq org-def (apply #'encode-time org-defdecode))
  15294. (setq org-defdecode (decode-time org-def)))
  15295. (let* ((timestr (format-time-string
  15296. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15297. org-def))
  15298. (prompt (concat (if prompt (concat prompt " ") "")
  15299. (format "Date+time [%s]: " timestr))))
  15300. (cond
  15301. (from-string (setq ans from-string))
  15302. (org-read-date-popup-calendar
  15303. (save-excursion
  15304. (save-window-excursion
  15305. (calendar)
  15306. (when (eq calendar-setup 'calendar-only)
  15307. (setq cal-frame
  15308. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15309. (select-frame cal-frame))
  15310. (org-eval-in-calendar '(setq cursor-type nil) t)
  15311. (unwind-protect
  15312. (progn
  15313. (calendar-forward-day (- (time-to-days org-def)
  15314. (calendar-absolute-from-gregorian
  15315. (calendar-current-date))))
  15316. (org-eval-in-calendar nil t)
  15317. (let* ((old-map (current-local-map))
  15318. (map (copy-keymap calendar-mode-map))
  15319. (minibuffer-local-map
  15320. (copy-keymap org-read-date-minibuffer-local-map)))
  15321. (org-defkey map (kbd "RET") 'org-calendar-select)
  15322. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15323. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15324. (unwind-protect
  15325. (progn
  15326. (use-local-map map)
  15327. (setq org-read-date-inactive inactive)
  15328. (add-hook 'post-command-hook 'org-read-date-display)
  15329. (setq org-ans0
  15330. (read-string prompt
  15331. default-input
  15332. 'org-read-date-history
  15333. nil))
  15334. ;; org-ans0: from prompt
  15335. ;; org-ans1: from mouse click
  15336. ;; org-ans2: from calendar motion
  15337. (setq ans
  15338. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15339. (remove-hook 'post-command-hook 'org-read-date-display)
  15340. (use-local-map old-map)
  15341. (when org-read-date-overlay
  15342. (delete-overlay org-read-date-overlay)
  15343. (setq org-read-date-overlay nil)))))
  15344. (bury-buffer "*Calendar*")
  15345. (when cal-frame
  15346. (delete-frame cal-frame)
  15347. (select-frame-set-input-focus cur-frame))))))
  15348. (t ; Naked prompt only
  15349. (unwind-protect
  15350. (setq ans (read-string prompt default-input
  15351. 'org-read-date-history timestr))
  15352. (when org-read-date-overlay
  15353. (delete-overlay org-read-date-overlay)
  15354. (setq org-read-date-overlay nil))))))
  15355. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15356. (when org-read-date-analyze-forced-year
  15357. (message "Year was forced into %s"
  15358. (if org-read-date-force-compatible-dates
  15359. "compatible range (1970-2037)"
  15360. "range representable on this machine"))
  15361. (ding))
  15362. ;; One round trip to get rid of 34th of August and stuff like that....
  15363. (setq final (decode-time (apply 'encode-time final)))
  15364. (setq org-read-date-final-answer ans)
  15365. (if to-time
  15366. (apply 'encode-time final)
  15367. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15368. (format "%04d-%02d-%02d %02d:%02d"
  15369. (nth 5 final) (nth 4 final) (nth 3 final)
  15370. (nth 2 final) (nth 1 final))
  15371. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15372. (defun org-read-date-display ()
  15373. "Display the current date prompt interpretation in the minibuffer."
  15374. (when org-read-date-display-live
  15375. (when org-read-date-overlay
  15376. (delete-overlay org-read-date-overlay))
  15377. (when (minibufferp (current-buffer))
  15378. (save-excursion
  15379. (end-of-line 1)
  15380. (while (not (equal (buffer-substring
  15381. (max (point-min) (- (point) 4)) (point))
  15382. " "))
  15383. (insert " ")))
  15384. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15385. " " (or org-ans1 org-ans2)))
  15386. (org-end-time-was-given nil)
  15387. (f (org-read-date-analyze ans org-def org-defdecode))
  15388. (fmts (if org-dcst
  15389. org-time-stamp-custom-formats
  15390. org-time-stamp-formats))
  15391. (fmt (if (or org-with-time
  15392. (and (boundp 'org-time-was-given) org-time-was-given))
  15393. (cdr fmts)
  15394. (car fmts)))
  15395. (txt (format-time-string fmt (apply 'encode-time f)))
  15396. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15397. (txt (concat "=> " txt)))
  15398. (when (and org-end-time-was-given
  15399. (string-match org-plain-time-of-day-regexp txt))
  15400. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15401. org-end-time-was-given
  15402. (substring txt (match-end 0)))))
  15403. (when org-read-date-analyze-futurep
  15404. (setq txt (concat txt " (=>F)")))
  15405. (setq org-read-date-overlay
  15406. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15407. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15408. (defun org-read-date-analyze (ans def defdecode)
  15409. "Analyze the combined answer of the date prompt."
  15410. ;; FIXME: cleanup and comment
  15411. ;; Pass `current-time' result to `decode-time' (instead of calling
  15412. ;; without arguments) so that only `current-time' has to be
  15413. ;; overriden in tests.
  15414. (let ((org-def def)
  15415. (org-defdecode defdecode)
  15416. (nowdecode (decode-time (current-time)))
  15417. delta deltan deltaw deltadef year month day
  15418. hour minute second wday pm h2 m2 tl wday1
  15419. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15420. (setq org-read-date-analyze-futurep nil
  15421. org-read-date-analyze-forced-year nil)
  15422. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15423. (setq ans "+0"))
  15424. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15425. (setq ans (replace-match "" t t ans)
  15426. deltan (car delta)
  15427. deltaw (nth 1 delta)
  15428. deltadef (nth 2 delta)))
  15429. ;; Check if there is an iso week date in there. If yes, store the
  15430. ;; info and postpone interpreting it until the rest of the parsing
  15431. ;; is done.
  15432. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15433. (setq iso-year (when (match-end 1)
  15434. (org-small-year-to-year
  15435. (string-to-number (match-string 1 ans))))
  15436. iso-weekday (when (match-end 3)
  15437. (string-to-number (match-string 3 ans)))
  15438. iso-week (string-to-number (match-string 2 ans)))
  15439. (setq ans (replace-match "" t t ans)))
  15440. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15441. (when (string-match
  15442. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15443. (setq year (if (match-end 2)
  15444. (string-to-number (match-string 2 ans))
  15445. (progn (setq kill-year t)
  15446. (string-to-number (format-time-string "%Y"))))
  15447. month (string-to-number (match-string 3 ans))
  15448. day (string-to-number (match-string 4 ans)))
  15449. (setq year (org-small-year-to-year year))
  15450. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15451. t nil ans)))
  15452. ;; Help matching dotted european dates
  15453. (when (string-match
  15454. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15455. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15456. (setq kill-year t)
  15457. (string-to-number (format-time-string "%Y")))
  15458. day (string-to-number (match-string 1 ans))
  15459. month (string-to-number (match-string 2 ans))
  15460. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15461. t nil ans)))
  15462. ;; Help matching american dates, like 5/30 or 5/30/7
  15463. (when (string-match
  15464. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15465. (setq year (if (match-end 4)
  15466. (string-to-number (match-string 4 ans))
  15467. (progn (setq kill-year t)
  15468. (string-to-number (format-time-string "%Y"))))
  15469. month (string-to-number (match-string 1 ans))
  15470. day (string-to-number (match-string 2 ans)))
  15471. (setq year (org-small-year-to-year year))
  15472. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15473. t nil ans)))
  15474. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15475. ;; If there is a time with am/pm, and *no* time without it, we convert
  15476. ;; so that matching will be successful.
  15477. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15478. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15479. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15480. (setq hour (string-to-number (match-string 1 ans))
  15481. minute (if (match-end 3)
  15482. (string-to-number (match-string 3 ans))
  15483. 0)
  15484. pm (equal ?p
  15485. (string-to-char (downcase (match-string 4 ans)))))
  15486. (if (and (= hour 12) (not pm))
  15487. (setq hour 0)
  15488. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15489. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15490. t t ans))))
  15491. ;; Check if a time range is given as a duration
  15492. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15493. (setq hour (string-to-number (match-string 1 ans))
  15494. h2 (+ hour (string-to-number (match-string 3 ans)))
  15495. minute (string-to-number (match-string 2 ans))
  15496. m2 (+ minute (if (match-end 5) (string-to-number
  15497. (match-string 5 ans))0)))
  15498. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15499. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15500. t t ans)))
  15501. ;; Check if there is a time range
  15502. (when (boundp 'org-end-time-was-given)
  15503. (setq org-time-was-given nil)
  15504. (when (and (string-match org-plain-time-of-day-regexp ans)
  15505. (match-end 8))
  15506. (setq org-end-time-was-given (match-string 8 ans))
  15507. (setq ans (concat (substring ans 0 (match-beginning 7))
  15508. (substring ans (match-end 7))))))
  15509. (setq tl (parse-time-string ans)
  15510. day (or (nth 3 tl) (nth 3 org-defdecode))
  15511. month
  15512. (cond ((nth 4 tl))
  15513. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15514. ;; Day was specified. Make sure DAY+MONTH
  15515. ;; combination happens in the future.
  15516. ((nth 3 tl)
  15517. (setq futurep t)
  15518. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15519. (nth 4 nowdecode)))
  15520. (t (nth 4 org-defdecode)))
  15521. year
  15522. (cond ((and (not kill-year) (nth 5 tl)))
  15523. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15524. ;; Month was guessed in the future and is at least
  15525. ;; equal to NOWDECODE's. Fix year accordingly.
  15526. (futurep
  15527. (if (or (> month (nth 4 nowdecode))
  15528. (>= day (nth 3 nowdecode)))
  15529. (nth 5 nowdecode)
  15530. (1+ (nth 5 nowdecode))))
  15531. ;; Month was specified. Make sure MONTH+YEAR
  15532. ;; combination happens in the future.
  15533. ((nth 4 tl)
  15534. (setq futurep t)
  15535. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15536. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15537. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15538. (t (nth 5 nowdecode))))
  15539. (t (nth 5 org-defdecode)))
  15540. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15541. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15542. second (or (nth 0 tl) 0)
  15543. wday (nth 6 tl))
  15544. (when (and (eq org-read-date-prefer-future 'time)
  15545. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15546. (equal day (nth 3 nowdecode))
  15547. (equal month (nth 4 nowdecode))
  15548. (equal year (nth 5 nowdecode))
  15549. (nth 2 tl)
  15550. (or (< (nth 2 tl) (nth 2 nowdecode))
  15551. (and (= (nth 2 tl) (nth 2 nowdecode))
  15552. (nth 1 tl)
  15553. (< (nth 1 tl) (nth 1 nowdecode)))))
  15554. (setq day (1+ day)
  15555. futurep t))
  15556. ;; Special date definitions below
  15557. (cond
  15558. (iso-week
  15559. ;; There was an iso week
  15560. (require 'cal-iso)
  15561. (setq futurep nil)
  15562. (setq year (or iso-year year)
  15563. day (or iso-weekday wday 1)
  15564. wday nil ; to make sure that the trigger below does not match
  15565. iso-date (calendar-gregorian-from-absolute
  15566. (calendar-iso-to-absolute
  15567. (list iso-week day year))))
  15568. ; FIXME: Should we also push ISO weeks into the future?
  15569. ; (when (and org-read-date-prefer-future
  15570. ; (not iso-year)
  15571. ; (< (calendar-absolute-from-gregorian iso-date)
  15572. ; (time-to-days (current-time))))
  15573. ; (setq year (1+ year)
  15574. ; iso-date (calendar-gregorian-from-absolute
  15575. ; (calendar-iso-to-absolute
  15576. ; (list iso-week day year)))))
  15577. (setq month (car iso-date)
  15578. year (nth 2 iso-date)
  15579. day (nth 1 iso-date)))
  15580. (deltan
  15581. (setq futurep nil)
  15582. (unless deltadef
  15583. ;; Pass `current-time' result to `decode-time' (instead of
  15584. ;; calling without arguments) so that only `current-time' has
  15585. ;; to be overriden in tests.
  15586. (let ((now (decode-time (current-time))))
  15587. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15588. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15589. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15590. ((equal deltaw "m") (setq month (+ month deltan)))
  15591. ((equal deltaw "y") (setq year (+ year deltan)))))
  15592. ((and wday (not (nth 3 tl)))
  15593. ;; Weekday was given, but no day, so pick that day in the week
  15594. ;; on or after the derived date.
  15595. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15596. (unless (equal wday wday1)
  15597. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15598. (when (and (boundp 'org-time-was-given)
  15599. (nth 2 tl))
  15600. (setq org-time-was-given t))
  15601. (when (< year 100) (setq year (+ 2000 year)))
  15602. ;; Check of the date is representable
  15603. (if org-read-date-force-compatible-dates
  15604. (progn
  15605. (when (< year 1970)
  15606. (setq year 1970 org-read-date-analyze-forced-year t))
  15607. (when (> year 2037)
  15608. (setq year 2037 org-read-date-analyze-forced-year t)))
  15609. (condition-case nil
  15610. (ignore (encode-time second minute hour day month year))
  15611. (error
  15612. (setq year (nth 5 org-defdecode))
  15613. (setq org-read-date-analyze-forced-year t))))
  15614. (setq org-read-date-analyze-futurep futurep)
  15615. (list second minute hour day month year)))
  15616. (defvar parse-time-weekdays)
  15617. (defun org-read-date-get-relative (s today default)
  15618. "Check string S for special relative date string.
  15619. TODAY and DEFAULT are internal times, for today and for a default.
  15620. Return shift list (N what def-flag)
  15621. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15622. N is the number of WHATs to shift.
  15623. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15624. the DEFAULT date rather than TODAY."
  15625. (require 'parse-time)
  15626. (when (and
  15627. (string-match
  15628. (concat
  15629. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15630. "\\([0-9]+\\)?"
  15631. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15632. "\\([ \t]\\|$\\)") s)
  15633. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15634. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15635. (string-to-char (substring (match-string 1 s) -1))
  15636. ?+))
  15637. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15638. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15639. (what (if (match-end 3) (match-string 3 s) "d"))
  15640. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15641. (date (if rel default today))
  15642. (wday (nth 6 (decode-time date)))
  15643. delta)
  15644. (if wday1
  15645. (progn
  15646. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15647. (when (= delta 0) (setq delta 7))
  15648. (when (= dir ?-)
  15649. (setq delta (- delta 7))
  15650. (when (= delta 0) (setq delta -7)))
  15651. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15652. (list delta "d" rel))
  15653. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15654. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15655. "Turn a user-specified date into the internal representation.
  15656. The internal representation needed by the calendar is (month day year).
  15657. This is a wrapper to handle the brain-dead convention in calendar that
  15658. user function argument order change dependent on argument order."
  15659. (pcase calendar-date-style
  15660. (`american (list arg1 arg2 arg3))
  15661. (`european (list arg2 arg1 arg3))
  15662. (`iso (list arg2 arg3 arg1))))
  15663. (defun org-eval-in-calendar (form &optional keepdate)
  15664. "Eval FORM in the calendar window and return to current window.
  15665. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15666. (let ((sf (selected-frame))
  15667. (sw (selected-window)))
  15668. (select-window (get-buffer-window "*Calendar*" t))
  15669. (eval form)
  15670. (when (and (not keepdate) (calendar-cursor-to-date))
  15671. (let* ((date (calendar-cursor-to-date))
  15672. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15673. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15674. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15675. (select-window sw)
  15676. (select-frame-set-input-focus sf)))
  15677. (defun org-calendar-select ()
  15678. "Return to `org-read-date' with the date currently selected.
  15679. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15680. (interactive)
  15681. (when (calendar-cursor-to-date)
  15682. (let* ((date (calendar-cursor-to-date))
  15683. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15684. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15685. (when (active-minibuffer-window) (exit-minibuffer))))
  15686. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15687. "Insert a date stamp for the date given by the internal TIME.
  15688. See `format-time-string' for the format of TIME.
  15689. WITH-HM means use the stamp format that includes the time of the day.
  15690. INACTIVE means use square brackets instead of angular ones, so that the
  15691. stamp will not contribute to the agenda.
  15692. PRE and POST are optional strings to be inserted before and after the
  15693. stamp.
  15694. The command returns the inserted time stamp."
  15695. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15696. stamp)
  15697. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15698. (insert-before-markers (or pre ""))
  15699. (when (listp extra)
  15700. (setq extra (car extra))
  15701. (if (and (stringp extra)
  15702. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15703. (setq extra (format "-%02d:%02d"
  15704. (string-to-number (match-string 1 extra))
  15705. (string-to-number (match-string 2 extra))))
  15706. (setq extra nil)))
  15707. (when extra
  15708. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15709. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15710. (insert-before-markers (or post ""))
  15711. (setq org-last-inserted-timestamp stamp)))
  15712. (defun org-toggle-time-stamp-overlays ()
  15713. "Toggle the use of custom time stamp formats."
  15714. (interactive)
  15715. (setq org-display-custom-times (not org-display-custom-times))
  15716. (unless org-display-custom-times
  15717. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15718. (while (setq p (next-single-property-change p 'display))
  15719. (when (and (get-text-property p 'display)
  15720. (eq (get-text-property p 'face) 'org-date))
  15721. (remove-text-properties
  15722. p (setq p (next-single-property-change p 'display))
  15723. '(display t))))
  15724. (set-buffer-modified-p bmp)))
  15725. (org-restart-font-lock)
  15726. (setq org-table-may-need-update t)
  15727. (if org-display-custom-times
  15728. (message "Time stamps are overlaid with custom format")
  15729. (message "Time stamp overlays removed")))
  15730. (defun org-display-custom-time (beg end)
  15731. "Overlay modified time stamp format over timestamp between BEG and END."
  15732. (let* ((ts (buffer-substring beg end))
  15733. t1 w1 with-hm tf time str w2 (off 0))
  15734. (save-match-data
  15735. (setq t1 (org-parse-time-string ts t))
  15736. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15737. (setq off (- (match-end 0) (match-beginning 0)))))
  15738. (setq end (- end off))
  15739. (setq w1 (- end beg)
  15740. with-hm (and (nth 1 t1) (nth 2 t1))
  15741. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15742. time (org-fix-decoded-time t1)
  15743. str (org-add-props
  15744. (format-time-string
  15745. (substring tf 1 -1) (apply 'encode-time time))
  15746. nil 'mouse-face 'highlight)
  15747. w2 (length str))
  15748. (unless (= w2 w1)
  15749. (add-text-properties (1+ beg) (+ 2 beg)
  15750. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15751. (put-text-property beg end 'display str)))
  15752. (defun org-fix-decoded-time (time)
  15753. "Set 0 instead of nil for the first 6 elements of time.
  15754. Don't touch the rest."
  15755. (let ((n 0))
  15756. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15757. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15758. "Difference between TIMESTAMP-STRING and now in days.
  15759. If SECONDS is non-nil, return the difference in seconds."
  15760. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15761. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15762. (funcall fdiff (current-time)))))
  15763. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15764. "Is the time in TIMESTAMP-STRING close to the current date?"
  15765. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15766. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15767. (not (org-entry-is-done-p))))
  15768. (defun org-get-wdays (ts &optional delay zero-delay)
  15769. "Get the deadline lead time appropriate for timestring TS.
  15770. When DELAY is non-nil, get the delay time for scheduled items
  15771. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15772. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15773. don't try to find the delay cookie in the scheduled timestamp."
  15774. (let ((tv (if delay org-scheduled-delay-days
  15775. org-deadline-warning-days)))
  15776. (cond
  15777. ((or (and delay (< tv 0))
  15778. (and delay zero-delay (<= tv 0))
  15779. (and (not delay) (<= tv 0)))
  15780. ;; Enforce this value no matter what
  15781. (- tv))
  15782. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15783. ;; lead time is specified.
  15784. (floor (* (string-to-number (match-string 1 ts))
  15785. (cdr (assoc (match-string 2 ts)
  15786. '(("d" . 1) ("w" . 7)
  15787. ("m" . 30.4) ("y" . 365.25)
  15788. ("h" . 0.041667)))))))
  15789. ;; go for the default.
  15790. (t tv))))
  15791. (defun org-calendar-select-mouse (ev)
  15792. "Return to `org-read-date' with the date currently selected.
  15793. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15794. (interactive "e")
  15795. (mouse-set-point ev)
  15796. (when (calendar-cursor-to-date)
  15797. (let* ((date (calendar-cursor-to-date))
  15798. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15799. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15800. (when (active-minibuffer-window) (exit-minibuffer))))
  15801. (defun org-check-deadlines (ndays)
  15802. "Check if there are any deadlines due or past due.
  15803. A deadline is considered due if it happens within `org-deadline-warning-days'
  15804. days from today's date. If the deadline appears in an entry marked DONE,
  15805. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15806. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15807. are shown."
  15808. (interactive "P")
  15809. (let* ((org-warn-days
  15810. (cond
  15811. ((equal ndays '(4)) 100000)
  15812. (ndays (prefix-numeric-value ndays))
  15813. (t (abs org-deadline-warning-days))))
  15814. (case-fold-search nil)
  15815. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15816. (callback
  15817. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15818. (message "%d deadlines past-due or due within %d days"
  15819. (org-occur regexp nil callback)
  15820. org-warn-days)))
  15821. (defsubst org-re-timestamp (type)
  15822. "Return a regexp for timestamp TYPE.
  15823. Allowed values for TYPE are:
  15824. all: all timestamps
  15825. active: only active timestamps (<...>)
  15826. inactive: only inactive timestamps ([...])
  15827. scheduled: only scheduled timestamps
  15828. deadline: only deadline timestamps
  15829. closed: only closed time-stamps
  15830. When TYPE is nil, fall back on returning a regexp that matches
  15831. both scheduled and deadline timestamps."
  15832. (cl-case type
  15833. (all org-ts-regexp-both)
  15834. (active org-ts-regexp)
  15835. (inactive org-ts-regexp-inactive)
  15836. (scheduled org-scheduled-time-regexp)
  15837. (deadline org-deadline-time-regexp)
  15838. (closed org-closed-time-regexp)
  15839. (otherwise
  15840. (concat "\\<"
  15841. (regexp-opt (list org-deadline-string org-scheduled-string))
  15842. " *<\\([^>]+\\)>"))))
  15843. (defun org-check-before-date (d)
  15844. "Check if there are deadlines or scheduled entries before date D."
  15845. (interactive (list (org-read-date)))
  15846. (let* ((case-fold-search nil)
  15847. (regexp (org-re-timestamp org-ts-type))
  15848. (ts-type org-ts-type)
  15849. (callback
  15850. (lambda ()
  15851. (let ((match (match-string 1)))
  15852. (and (if (memq ts-type '(active inactive all))
  15853. (eq (org-element-type (save-excursion
  15854. (backward-char)
  15855. (org-element-context)))
  15856. 'timestamp)
  15857. (org-at-planning-p))
  15858. (time-less-p
  15859. (org-time-string-to-time match)
  15860. (org-time-string-to-time d)))))))
  15861. (message "%d entries before %s"
  15862. (org-occur regexp nil callback)
  15863. d)))
  15864. (defun org-check-after-date (d)
  15865. "Check if there are deadlines or scheduled entries after date D."
  15866. (interactive (list (org-read-date)))
  15867. (let* ((case-fold-search nil)
  15868. (regexp (org-re-timestamp org-ts-type))
  15869. (ts-type org-ts-type)
  15870. (callback
  15871. (lambda ()
  15872. (let ((match (match-string 1)))
  15873. (and (if (memq ts-type '(active inactive all))
  15874. (eq (org-element-type (save-excursion
  15875. (backward-char)
  15876. (org-element-context)))
  15877. 'timestamp)
  15878. (org-at-planning-p))
  15879. (not (time-less-p
  15880. (org-time-string-to-time match)
  15881. (org-time-string-to-time d))))))))
  15882. (message "%d entries after %s"
  15883. (org-occur regexp nil callback)
  15884. d)))
  15885. (defun org-check-dates-range (start-date end-date)
  15886. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  15887. (interactive (list (org-read-date nil nil nil "Range starts")
  15888. (org-read-date nil nil nil "Range end")))
  15889. (let ((case-fold-search nil)
  15890. (regexp (org-re-timestamp org-ts-type))
  15891. (callback
  15892. (let ((type org-ts-type))
  15893. (lambda ()
  15894. (let ((match (match-string 1)))
  15895. (and
  15896. (if (memq type '(active inactive all))
  15897. (eq (org-element-type (save-excursion
  15898. (backward-char)
  15899. (org-element-context)))
  15900. 'timestamp)
  15901. (org-at-planning-p))
  15902. (not (time-less-p
  15903. (org-time-string-to-time match)
  15904. (org-time-string-to-time start-date)))
  15905. (time-less-p
  15906. (org-time-string-to-time match)
  15907. (org-time-string-to-time end-date))))))))
  15908. (message "%d entries between %s and %s"
  15909. (org-occur regexp nil callback) start-date end-date)))
  15910. (defun org-evaluate-time-range (&optional to-buffer)
  15911. "Evaluate a time range by computing the difference between start and end.
  15912. Normally the result is just printed in the echo area, but with prefix arg
  15913. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  15914. If the time range is actually in a table, the result is inserted into the
  15915. next column.
  15916. For time difference computation, a year is assumed to be exactly 365
  15917. days in order to avoid rounding problems."
  15918. (interactive "P")
  15919. (or
  15920. (org-clock-update-time-maybe)
  15921. (save-excursion
  15922. (unless (org-at-date-range-p t)
  15923. (goto-char (point-at-bol))
  15924. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  15925. (unless (org-at-date-range-p t)
  15926. (user-error "Not at a time-stamp range, and none found in current line")))
  15927. (let* ((ts1 (match-string 1))
  15928. (ts2 (match-string 2))
  15929. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  15930. (match-end (match-end 0))
  15931. (time1 (org-time-string-to-time ts1))
  15932. (time2 (org-time-string-to-time ts2))
  15933. (t1 (float-time time1))
  15934. (t2 (float-time time2))
  15935. (diff (abs (- t2 t1)))
  15936. (negative (< (- t2 t1) 0))
  15937. ;; (ys (floor (* 365 24 60 60)))
  15938. (ds (* 24 60 60))
  15939. (hs (* 60 60))
  15940. (fy "%dy %dd %02d:%02d")
  15941. (fy1 "%dy %dd")
  15942. (fd "%dd %02d:%02d")
  15943. (fd1 "%dd")
  15944. (fh "%02d:%02d")
  15945. y d h m align)
  15946. (if havetime
  15947. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15948. y 0
  15949. d (floor (/ diff ds)) diff (mod diff ds)
  15950. h (floor (/ diff hs)) diff (mod diff hs)
  15951. m (floor (/ diff 60)))
  15952. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  15953. y 0
  15954. d (floor (+ (/ diff ds) 0.5))
  15955. h 0 m 0))
  15956. (if (not to-buffer)
  15957. (message "%s" (org-make-tdiff-string y d h m))
  15958. (if (org-at-table-p)
  15959. (progn
  15960. (goto-char match-end)
  15961. (setq align t)
  15962. (and (looking-at " *|") (goto-char (match-end 0))))
  15963. (goto-char match-end))
  15964. (when (looking-at
  15965. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  15966. (replace-match ""))
  15967. (when negative (insert " -"))
  15968. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  15969. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  15970. (insert " " (format fh h m))))
  15971. (when align (org-table-align))
  15972. (message "Time difference inserted")))))
  15973. (defun org-make-tdiff-string (y d h m)
  15974. (let ((fmt "")
  15975. (l nil))
  15976. (when (> y 0)
  15977. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  15978. (push y l))
  15979. (when (> d 0)
  15980. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  15981. (push d l))
  15982. (when (> h 0)
  15983. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  15984. (push h l))
  15985. (when (> m 0)
  15986. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  15987. (push m l))
  15988. (apply 'format fmt (nreverse l))))
  15989. (defun org-time-string-to-time (s &optional buffer pos)
  15990. "Convert a timestamp string into internal time."
  15991. (condition-case errdata
  15992. (apply 'encode-time (org-parse-time-string s))
  15993. (error (error "Bad timestamp `%s'%s\nError was: %s"
  15994. s (if (not (and buffer pos))
  15995. ""
  15996. (format-message " at %d in buffer `%s'" pos buffer))
  15997. (cdr errdata)))))
  15998. (defun org-time-string-to-seconds (s)
  15999. "Convert a timestamp string to a number of seconds."
  16000. (float-time (org-time-string-to-time s)))
  16001. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16002. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16003. "Convert time stamp S to an absolute day number.
  16004. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16005. stamp, get the closest date to DAYNR. If PREFER is
  16006. `past' (respectively `future') return a date past (respectively
  16007. after) or equal to DAYNR.
  16008. POS is the location of time stamp S, as a buffer position in
  16009. BUFFER.
  16010. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16011. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16012. signalled."
  16013. (cond
  16014. ((string-match "\\`%%\\((.*)\\)" s)
  16015. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16016. ;; only able to match individual dates. If it fails, raise an
  16017. ;; error.
  16018. (if (and daynr
  16019. (org-diary-sexp-entry
  16020. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16021. daynr
  16022. (signal 'org-diary-sexp-no-match (list s))))
  16023. (daynr (org-closest-date s daynr prefer))
  16024. (t (time-to-days
  16025. (condition-case errdata
  16026. (apply #'encode-time (org-parse-time-string s))
  16027. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16028. s
  16029. (if (not (and buffer pos)) ""
  16030. (format-message " at %d in buffer `%s'" pos buffer))
  16031. (cdr errdata))))))))
  16032. (defun org-days-to-iso-week (days)
  16033. "Return the iso week number."
  16034. (require 'cal-iso)
  16035. (car (calendar-iso-from-absolute days)))
  16036. (defun org-small-year-to-year (year)
  16037. "Convert 2-digit years into 4-digit years.
  16038. YEAR is expanded into one of the 30 next years, if possible, or
  16039. into a past one. Any year larger than 99 is returned unchanged."
  16040. (if (>= year 100) year
  16041. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16042. (century (/ current 100))
  16043. (offset (- year (% current 100))))
  16044. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16045. ((> offset -70) (+ (* century 100) year))
  16046. (t (+ (* (1+ century) 100) year))))))
  16047. (defun org-time-from-absolute (d)
  16048. "Return the time corresponding to date D.
  16049. D may be an absolute day number, or a calendar-type list (month day year)."
  16050. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16051. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16052. (defvar org-agenda-current-date)
  16053. (defun org-calendar-holiday ()
  16054. "List of holidays, for Diary display in Org mode."
  16055. (require 'holidays)
  16056. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16057. (and hl (mapconcat #'identity hl "; "))))
  16058. (defun org-diary-sexp-entry (sexp entry d)
  16059. "Process a SEXP diary ENTRY for date D."
  16060. (require 'diary-lib)
  16061. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16062. ;; dynamically.
  16063. (let* ((sexp `(let ((entry ,entry)
  16064. (date ',d))
  16065. ,(car (read-from-string sexp))))
  16066. (result (if calendar-debug-sexp (eval sexp)
  16067. (condition-case nil
  16068. (eval sexp)
  16069. (error
  16070. (beep)
  16071. (message "Bad sexp at line %d in %s: %s"
  16072. (org-current-line)
  16073. (buffer-file-name) sexp)
  16074. (sleep-for 2))))))
  16075. (cond ((stringp result) (split-string result "; "))
  16076. ((and (consp result)
  16077. (not (consp (cdr result)))
  16078. (stringp (cdr result))) (cdr result))
  16079. ((and (consp result)
  16080. (stringp (car result))) result)
  16081. (result entry))))
  16082. (defun org-diary-to-ical-string (frombuf)
  16083. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16084. This uses the icalendar.el library."
  16085. (let* ((tmpdir temporary-file-directory)
  16086. (tmpfile (make-temp-name
  16087. (expand-file-name "orgics" tmpdir)))
  16088. buf rtn b e)
  16089. (with-current-buffer frombuf
  16090. (icalendar-export-region (point-min) (point-max) tmpfile)
  16091. (setq buf (find-buffer-visiting tmpfile))
  16092. (set-buffer buf)
  16093. (goto-char (point-min))
  16094. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16095. (setq b (match-beginning 0)))
  16096. (goto-char (point-max))
  16097. (when (re-search-backward "^END:VEVENT" nil t)
  16098. (setq e (match-end 0)))
  16099. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16100. (kill-buffer buf)
  16101. (delete-file tmpfile)
  16102. rtn))
  16103. (defun org-closest-date (start current prefer)
  16104. "Return closest date to CURRENT starting from START.
  16105. CURRENT and START are both time stamps.
  16106. When PREFER is `past', return a date that is either CURRENT or
  16107. past. When PREFER is `future', return a date that is either
  16108. CURRENT or future.
  16109. Only time stamps with a repeater are modified. Any other time
  16110. stamp stay unchanged. In any case, return value is an absolute
  16111. day number."
  16112. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16113. ;; No repeater. Do not shift time stamp.
  16114. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16115. (let ((value (string-to-number (match-string 1 start)))
  16116. (type (match-string 2 start)))
  16117. (if (= 0 value)
  16118. ;; Repeater with a 0-value is considered as void.
  16119. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16120. (let* ((base (org-date-to-gregorian start))
  16121. (target (org-date-to-gregorian current))
  16122. (sday (calendar-absolute-from-gregorian base))
  16123. (cday (calendar-absolute-from-gregorian target))
  16124. n1 n2)
  16125. ;; If START is already past CURRENT, just return START.
  16126. (if (<= cday sday) sday
  16127. ;; Compute closest date before (N1) and closest date past
  16128. ;; (N2) CURRENT.
  16129. (pcase type
  16130. ("h"
  16131. (let ((missing-hours
  16132. (mod (+ (- (* 24 (- cday sday))
  16133. (nth 2 (org-parse-time-string start)))
  16134. org-extend-today-until)
  16135. value)))
  16136. (setf n1 (if (= missing-hours 0) cday
  16137. (- cday (1+ (/ missing-hours 24)))))
  16138. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16139. ((or "d" "w")
  16140. (let ((value (if (equal type "w") (* 7 value) value)))
  16141. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16142. (setf n2 (+ n1 value))))
  16143. ("m"
  16144. (let* ((add-months
  16145. (lambda (d n)
  16146. ;; Add N months to gregorian date D, i.e.,
  16147. ;; a list (MONTH DAY YEAR). Return a valid
  16148. ;; gregorian date.
  16149. (let ((m (+ (nth 0 d) n)))
  16150. (list (mod m 12)
  16151. (nth 1 d)
  16152. (+ (/ m 12) (nth 2 d))))))
  16153. (months ; Complete months to TARGET.
  16154. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16155. (- (nth 0 target) (nth 0 base))
  16156. ;; If START's day is greater than
  16157. ;; TARGET's, remove incomplete month.
  16158. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16159. value)
  16160. value))
  16161. (before (funcall add-months base months)))
  16162. (setf n1 (calendar-absolute-from-gregorian before))
  16163. (setf n2
  16164. (calendar-absolute-from-gregorian
  16165. (funcall add-months before value)))))
  16166. (_
  16167. (let* ((d (nth 1 base))
  16168. (m (nth 0 base))
  16169. (y (nth 2 base))
  16170. (years ; Complete years to TARGET.
  16171. (* (/ (- (nth 2 target)
  16172. y
  16173. ;; If START's month and day are
  16174. ;; greater than TARGET's, remove
  16175. ;; incomplete year.
  16176. (if (or (> (nth 0 target) m)
  16177. (and (= (nth 0 target) m)
  16178. (> (nth 1 target) d)))
  16179. 0
  16180. 1))
  16181. value)
  16182. value))
  16183. (before (list m d (+ y years))))
  16184. (setf n1 (calendar-absolute-from-gregorian before))
  16185. (setf n2 (calendar-absolute-from-gregorian
  16186. (list m d (+ (nth 2 before) value)))))))
  16187. ;; Handle PREFER parameter, if any.
  16188. (cond
  16189. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16190. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16191. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16192. (defun org-date-to-gregorian (d)
  16193. "Turn any specification of date D into a Gregorian date for the calendar."
  16194. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16195. ((and (listp d) (= (length d) 3)) d)
  16196. ((stringp d)
  16197. (let ((d (org-parse-time-string d)))
  16198. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16199. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16200. (defun org-parse-time-string (s &optional nodefault)
  16201. "Parse the standard Org time string.
  16202. This should be a lot faster than the normal `parse-time-string'.
  16203. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16204. hour and minute fields will be nil if not given."
  16205. (cond ((string-match org-ts-regexp0 s)
  16206. (list 0
  16207. (when (or (match-beginning 8) (not nodefault))
  16208. (string-to-number (or (match-string 8 s) "0")))
  16209. (when (or (match-beginning 7) (not nodefault))
  16210. (string-to-number (or (match-string 7 s) "0")))
  16211. (string-to-number (match-string 4 s))
  16212. (string-to-number (match-string 3 s))
  16213. (string-to-number (match-string 2 s))
  16214. nil nil nil))
  16215. ((string-match "^<[^>]+>$" s)
  16216. (decode-time (seconds-to-time (org-matcher-time s))))
  16217. (t (error "Not a standard Org time string: %s" s))))
  16218. (defun org-timestamp-up (&optional arg)
  16219. "Increase the date item at the cursor by one.
  16220. If the cursor is on the year, change the year. If it is on the month,
  16221. the day or the time, change that.
  16222. With prefix ARG, change by that many units."
  16223. (interactive "p")
  16224. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16225. (defun org-timestamp-down (&optional arg)
  16226. "Decrease the date item at the cursor by one.
  16227. If the cursor is on the year, change the year. If it is on the month,
  16228. the day or the time, change that.
  16229. With prefix ARG, change by that many units."
  16230. (interactive "p")
  16231. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16232. (defun org-timestamp-up-day (&optional arg)
  16233. "Increase the date in the time stamp by one day.
  16234. With prefix ARG, change that many days."
  16235. (interactive "p")
  16236. (if (and (not (org-at-timestamp-p 'lax))
  16237. (org-at-heading-p))
  16238. (org-todo 'up)
  16239. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16240. (defun org-timestamp-down-day (&optional arg)
  16241. "Decrease the date in the time stamp by one day.
  16242. With prefix ARG, change that many days."
  16243. (interactive "p")
  16244. (if (and (not (org-at-timestamp-p 'lax))
  16245. (org-at-heading-p))
  16246. (org-todo 'down)
  16247. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16248. (defun org-at-timestamp-p (&optional extended)
  16249. "Non-nil if point is inside a timestamp.
  16250. By default, the function only consider syntactically valid active
  16251. timestamps. However, the caller may have a broader definition
  16252. for timestamps. As a consequence, optional argument EXTENDED can
  16253. be set to the following values
  16254. `inactive'
  16255. Include also syntactically valid inactive timestamps.
  16256. `agenda'
  16257. Include timestamps allowed in Agenda, i.e., those in
  16258. properties drawers, planning lines and clock lines.
  16259. `lax'
  16260. Ignore context. The function matches any part of the
  16261. document looking like a timestamp. This includes comments,
  16262. example blocks...
  16263. For backward-compatibility with Org 9.0, every other non-nil
  16264. value is equivalent to `inactive'.
  16265. When at a timestamp, return the position of the point as a symbol
  16266. among `bracket', `after', `year', `month', `hour', `minute',
  16267. `day' or a number of character from the last know part of the
  16268. time stamp.
  16269. When matching, the match groups are the following:
  16270. group 1: year
  16271. group 2: month
  16272. group 3: day number
  16273. group 4: day name
  16274. group 5: hours, if any
  16275. group 6: minutes, if any"
  16276. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  16277. (pos (point))
  16278. (match?
  16279. (let ((boundaries (org-in-regexp regexp)))
  16280. (save-match-data
  16281. (cond ((null boundaries) nil)
  16282. ((eq extended 'lax) t)
  16283. (t
  16284. (or (and (eq extended 'agenda)
  16285. (or (org-at-planning-p)
  16286. (org-at-property-p)
  16287. (and (bound-and-true-p
  16288. org-agenda-include-inactive-timestamps)
  16289. (org-at-clock-log-p))))
  16290. (eq 'timestamp
  16291. (save-excursion
  16292. (when (= pos (cdr boundaries)) (forward-char -1))
  16293. (org-element-type (org-element-context)))))))))))
  16294. (cond
  16295. ((not match?) nil)
  16296. ((= pos (match-beginning 0)) 'bracket)
  16297. ;; Distinguish location right before the closing bracket from
  16298. ;; right after it.
  16299. ((= pos (1- (match-end 0))) 'bracket)
  16300. ((= pos (match-end 0)) 'after)
  16301. ((org-pos-in-match-range pos 2) 'year)
  16302. ((org-pos-in-match-range pos 3) 'month)
  16303. ((org-pos-in-match-range pos 7) 'hour)
  16304. ((org-pos-in-match-range pos 8) 'minute)
  16305. ((or (org-pos-in-match-range pos 4)
  16306. (org-pos-in-match-range pos 5)) 'day)
  16307. ((and (> pos (or (match-end 8) (match-end 5)))
  16308. (< pos (match-end 0)))
  16309. (- pos (or (match-end 8) (match-end 5))))
  16310. (t 'day))))
  16311. (defun org-toggle-timestamp-type ()
  16312. "Toggle the type (<active> or [inactive]) of a time stamp."
  16313. (interactive)
  16314. (when (org-at-timestamp-p 'lax)
  16315. (let ((beg (match-beginning 0)) (end (match-end 0))
  16316. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16317. (save-excursion
  16318. (goto-char beg)
  16319. (while (re-search-forward "[][<>]" end t)
  16320. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16321. t t)))
  16322. (message "Timestamp is now %sactive"
  16323. (if (equal (char-after beg) ?<) "" "in")))))
  16324. (defun org-at-clock-log-p ()
  16325. "Non-nil if point is on a clock log line."
  16326. (and (org-match-line org-clock-line-re)
  16327. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  16328. (defvar org-clock-history) ; defined in org-clock.el
  16329. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16330. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16331. "Change the date in the time stamp at point.
  16332. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16333. `year', `minute', `second'. If WHAT is not given, the cursor position
  16334. in the timestamp determines what will be changed.
  16335. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16336. (let ((origin (point))
  16337. (timestamp? (org-at-timestamp-p 'lax))
  16338. origin-cat
  16339. with-hm inactive
  16340. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16341. extra rem
  16342. ts time time0 fixnext clrgx)
  16343. (unless timestamp? (user-error "Not at a timestamp"))
  16344. (if (and (not what) (eq timestamp? 'bracket))
  16345. (org-toggle-timestamp-type)
  16346. ;; Point isn't on brackets. Remember the part of the time-stamp
  16347. ;; the point was in. Indeed, size of time-stamps may change,
  16348. ;; but point must be kept in the same category nonetheless.
  16349. (setq origin-cat timestamp?)
  16350. (when (and (not what) (not (eq timestamp? 'day))
  16351. org-display-custom-times
  16352. (get-text-property (point) 'display)
  16353. (not (get-text-property (1- (point)) 'display)))
  16354. (setq timestamp? 'day))
  16355. (setq timestamp? (or what timestamp?)
  16356. inactive (= (char-after (match-beginning 0)) ?\[)
  16357. ts (match-string 0))
  16358. (replace-match "")
  16359. (when (string-match
  16360. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16361. ts)
  16362. (setq extra (match-string 1 ts))
  16363. (when suppress-tmp-delay
  16364. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16365. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16366. (setq with-hm t))
  16367. (setq time0 (org-parse-time-string ts))
  16368. (when (and updown
  16369. (eq timestamp? 'minute)
  16370. (not current-prefix-arg))
  16371. ;; This looks like s-up and s-down. Change by one rounding step.
  16372. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16373. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16374. (setcar (cdr time0) (+ (nth 1 time0)
  16375. (if (> n 0) (- rem) (- dm rem))))))
  16376. (setq time
  16377. (apply #'encode-time
  16378. (or (car time0) 0)
  16379. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  16380. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  16381. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  16382. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  16383. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  16384. (nthcdr 6 time0)))
  16385. (when (and (memq timestamp? '(hour minute))
  16386. extra
  16387. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16388. (setq extra (org-modify-ts-extra
  16389. extra
  16390. (if (eq timestamp? 'hour) 2 5)
  16391. n dm)))
  16392. (when (integerp timestamp?)
  16393. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  16394. (when (eq what 'calendar)
  16395. (let ((cal-date (org-get-date-from-calendar)))
  16396. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16397. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16398. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16399. (setcar time0 (or (car time0) 0))
  16400. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16401. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16402. (setq time (apply 'encode-time time0))))
  16403. ;; Insert the new time-stamp, and ensure point stays in the same
  16404. ;; category as before (i.e. not after the last position in that
  16405. ;; category).
  16406. (let ((pos (point)))
  16407. ;; Stay before inserted string. `save-excursion' is of no use.
  16408. (setq org-last-changed-timestamp
  16409. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16410. (goto-char pos))
  16411. (save-match-data
  16412. (looking-at org-ts-regexp3)
  16413. (goto-char
  16414. (pcase origin-cat
  16415. ;; `day' category ends before `hour' if any, or at the end
  16416. ;; of the day name.
  16417. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16418. (`hour (min (match-end 7) origin))
  16419. (`minute (min (1- (match-end 8)) origin))
  16420. ((pred integerp) (min (1- (match-end 0)) origin))
  16421. ;; Point was right after the time-stamp. However, the
  16422. ;; time-stamp length might have changed, so refer to
  16423. ;; (match-end 0) instead.
  16424. (`after (match-end 0))
  16425. ;; `year' and `month' have both fixed size: point couldn't
  16426. ;; have moved into another part.
  16427. (_ origin))))
  16428. ;; Update clock if on a CLOCK line.
  16429. (org-clock-update-time-maybe)
  16430. ;; Maybe adjust the closest clock in `org-clock-history'
  16431. (when org-clock-adjust-closest
  16432. (if (not (and (org-at-clock-log-p)
  16433. (< 1 (length (delq nil (mapcar 'marker-position
  16434. org-clock-history))))))
  16435. (message "No clock to adjust")
  16436. (cond ((save-excursion ; fix previous clock?
  16437. (re-search-backward org-ts-regexp0 nil t)
  16438. (looking-back (concat org-clock-string " \\[")
  16439. (line-beginning-position)))
  16440. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16441. ((save-excursion ; fix next clock?
  16442. (re-search-backward org-ts-regexp0 nil t)
  16443. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16444. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16445. (save-window-excursion
  16446. ;; Find closest clock to point, adjust the previous/next one in history
  16447. (let* ((p (save-excursion (org-back-to-heading t)))
  16448. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16449. (clfixnth
  16450. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16451. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16452. (if (not clfixpos)
  16453. (message "No clock to adjust")
  16454. (save-excursion
  16455. (org-goto-marker-or-bmk clfixpos)
  16456. (org-show-subtree)
  16457. (when (re-search-forward clrgx nil t)
  16458. (goto-char (match-beginning 1))
  16459. (let (org-clock-adjust-closest)
  16460. (org-timestamp-change n timestamp? updown))
  16461. (message "Clock adjusted in %s for heading: %s"
  16462. (file-name-nondirectory (buffer-file-name))
  16463. (org-get-heading t t)))))))))
  16464. ;; Try to recenter the calendar window, if any.
  16465. (when (and org-calendar-follow-timestamp-change
  16466. (get-buffer-window "*Calendar*" t)
  16467. (memq timestamp? '(day month year)))
  16468. (org-recenter-calendar (time-to-days time))))))
  16469. (defun org-modify-ts-extra (s pos n dm)
  16470. "Change the different parts of the lead-time and repeat fields in timestamp."
  16471. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16472. ng h m new rem)
  16473. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16474. (cond
  16475. ((or (org-pos-in-match-range pos 2)
  16476. (org-pos-in-match-range pos 3))
  16477. (setq m (string-to-number (match-string 3 s))
  16478. h (string-to-number (match-string 2 s)))
  16479. (if (org-pos-in-match-range pos 2)
  16480. (setq h (+ h n))
  16481. (setq n (* dm (with-no-warnings (signum n))))
  16482. (unless (= 0 (setq rem (% m dm)))
  16483. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16484. (setq m (+ m n)))
  16485. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16486. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16487. (setq h (mod h 24))
  16488. (setq ng 1 new (format "-%02d:%02d" h m)))
  16489. ((org-pos-in-match-range pos 6)
  16490. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16491. ((org-pos-in-match-range pos 5)
  16492. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16493. ((org-pos-in-match-range pos 9)
  16494. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16495. ((org-pos-in-match-range pos 8)
  16496. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16497. (when ng
  16498. (setq s (concat
  16499. (substring s 0 (match-beginning ng))
  16500. new
  16501. (substring s (match-end ng))))))
  16502. s))
  16503. (defun org-recenter-calendar (d)
  16504. "If the calendar is visible, recenter it to date D."
  16505. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16506. (when cwin
  16507. (let ((calendar-move-hook nil))
  16508. (with-selected-window cwin
  16509. (calendar-goto-date
  16510. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16511. (defun org-goto-calendar (&optional arg)
  16512. "Go to the Emacs calendar at the current date.
  16513. If there is a time stamp in the current line, go to that date.
  16514. A prefix ARG can be used to force the current date."
  16515. (interactive "P")
  16516. (let ((calendar-move-hook nil)
  16517. (calendar-view-holidays-initially-flag nil)
  16518. (calendar-view-diary-initially-flag nil)
  16519. diff)
  16520. (when (or (org-at-timestamp-p 'lax)
  16521. (org-match-line (concat ".*" org-ts-regexp)))
  16522. (let ((d1 (time-to-days (current-time)))
  16523. (d2 (time-to-days
  16524. (org-time-string-to-time (match-string 1)))))
  16525. (setq diff (- d2 d1))))
  16526. (calendar)
  16527. (calendar-goto-today)
  16528. (when (and diff (not arg)) (calendar-forward-day diff))))
  16529. (defun org-get-date-from-calendar ()
  16530. "Return a list (month day year) of date at point in calendar."
  16531. (with-current-buffer "*Calendar*"
  16532. (save-match-data
  16533. (calendar-cursor-to-date))))
  16534. (defun org-date-from-calendar ()
  16535. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16536. If there is already a time stamp at the cursor position, update it."
  16537. (interactive)
  16538. (if (org-at-timestamp-p 'lax)
  16539. (org-timestamp-change 0 'calendar)
  16540. (let ((cal-date (org-get-date-from-calendar)))
  16541. (org-insert-time-stamp
  16542. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16543. (defcustom org-effort-durations
  16544. `(("min" . 1)
  16545. ("h" . 60)
  16546. ("d" . ,(* 60 8))
  16547. ("w" . ,(* 60 8 5))
  16548. ("m" . ,(* 60 8 5 4))
  16549. ("y" . ,(* 60 8 5 40)))
  16550. "Conversion factor to minutes for an effort modifier.
  16551. Each entry has the form (MODIFIER . MINUTES).
  16552. In an effort string, a number followed by MODIFIER is multiplied
  16553. by the specified number of MINUTES to obtain an effort in
  16554. minutes.
  16555. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16556. effort string \"2hours\" is equivalent to 120 minutes."
  16557. :group 'org-agenda
  16558. :version "26.1"
  16559. :package-version '(Org . "8.3")
  16560. :type '(alist :key-type (string :tag "Modifier")
  16561. :value-type (number :tag "Minutes")))
  16562. (defcustom org-image-actual-width t
  16563. "Should we use the actual width of images when inlining them?
  16564. When set to t, always use the image width.
  16565. When set to a number, use imagemagick (when available) to set
  16566. the image's width to this value.
  16567. When set to a number in a list, try to get the width from any
  16568. #+ATTR.* keyword if it matches a width specification like
  16569. #+ATTR_HTML: :width 300px
  16570. and fall back on that number if none is found.
  16571. When set to nil, try to get the width from an #+ATTR.* keyword
  16572. and fall back on the original width if none is found.
  16573. This requires Emacs >= 24.1, build with imagemagick support."
  16574. :group 'org-appearance
  16575. :version "24.4"
  16576. :package-version '(Org . "8.0")
  16577. :type '(choice
  16578. (const :tag "Use the image width" t)
  16579. (integer :tag "Use a number of pixels")
  16580. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16581. (const :tag "Use #+ATTR* or don't resize" nil)))
  16582. (defcustom org-agenda-inhibit-startup nil
  16583. "Inhibit startup when preparing agenda buffers.
  16584. When this variable is t, the initialization of the Org agenda
  16585. buffers is inhibited: e.g. the visibility state is not set, the
  16586. tables are not re-aligned, etc."
  16587. :type 'boolean
  16588. :version "24.3"
  16589. :group 'org-agenda)
  16590. (defcustom org-agenda-ignore-properties nil
  16591. "Avoid updating text properties when building the agenda.
  16592. Properties are used to prepare buffers for effort estimates,
  16593. appointments, statistics and subtree-local categories.
  16594. If you don't use these in the agenda, you can add them to this
  16595. list and agenda building will be a bit faster.
  16596. The value is a list, with zero or more of the symbols `effort', `appt',
  16597. `stats' or `category'."
  16598. :type '(set :greedy t
  16599. (const effort)
  16600. (const appt)
  16601. (const stats)
  16602. (const category))
  16603. :version "26.1"
  16604. :package-version '(Org . "8.3")
  16605. :group 'org-agenda)
  16606. ;;;; Files
  16607. (defun org-save-all-org-buffers ()
  16608. "Save all Org buffers without user confirmation."
  16609. (interactive)
  16610. (message "Saving all Org buffers...")
  16611. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16612. (when (featurep 'org-id) (org-id-locations-save))
  16613. (message "Saving all Org buffers... done"))
  16614. (defun org-revert-all-org-buffers ()
  16615. "Revert all Org buffers.
  16616. Prompt for confirmation when there are unsaved changes.
  16617. Be sure you know what you are doing before letting this function
  16618. overwrite your changes.
  16619. This function is useful in a setup where one tracks org files
  16620. with a version control system, to revert on one machine after pulling
  16621. changes from another. I believe the procedure must be like this:
  16622. 1. M-x org-save-all-org-buffers
  16623. 2. Pull changes from the other machine, resolve conflicts
  16624. 3. M-x org-revert-all-org-buffers"
  16625. (interactive)
  16626. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16627. (user-error "Abort"))
  16628. (save-excursion
  16629. (save-window-excursion
  16630. (dolist (b (buffer-list))
  16631. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16632. (with-current-buffer b buffer-file-name))
  16633. (pop-to-buffer-same-window b)
  16634. (revert-buffer t 'no-confirm)))
  16635. (when (and (featurep 'org-id) org-id-track-globally)
  16636. (org-id-locations-load)))))
  16637. ;;;; Agenda files
  16638. ;;;###autoload
  16639. (defun org-switchb (&optional arg)
  16640. "Switch between Org buffers.
  16641. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16642. With `\\[universal-argument] \\[universal-argument]' \
  16643. prefix, restrict available buffers to agenda files."
  16644. (interactive "P")
  16645. (let ((blist (org-buffer-list
  16646. (cond ((equal arg '(4)) 'files)
  16647. ((equal arg '(16)) 'agenda)))))
  16648. (pop-to-buffer-same-window
  16649. (completing-read "Org buffer: "
  16650. (mapcar #'list (mapcar #'buffer-name blist))
  16651. nil t))))
  16652. (defun org-buffer-list (&optional predicate exclude-tmp)
  16653. "Return a list of Org buffers.
  16654. PREDICATE can be `export', `files' or `agenda'.
  16655. export restrict the list to Export buffers.
  16656. files restrict the list to buffers visiting Org files.
  16657. agenda restrict the list to buffers visiting agenda files.
  16658. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16659. (let* ((bfn nil)
  16660. (agenda-files (and (eq predicate 'agenda)
  16661. (mapcar 'file-truename (org-agenda-files t))))
  16662. (filter
  16663. (cond
  16664. ((eq predicate 'files)
  16665. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16666. ((eq predicate 'export)
  16667. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16668. ((eq predicate 'agenda)
  16669. (lambda (b)
  16670. (with-current-buffer b
  16671. (and (derived-mode-p 'org-mode)
  16672. (setq bfn (buffer-file-name b))
  16673. (member (file-truename bfn) agenda-files)))))
  16674. (t (lambda (b) (with-current-buffer b
  16675. (or (derived-mode-p 'org-mode)
  16676. (string-match "\\*Org .*Export"
  16677. (buffer-name b)))))))))
  16678. (delq nil
  16679. (mapcar
  16680. (lambda(b)
  16681. (if (and (funcall filter b)
  16682. (or (not exclude-tmp)
  16683. (not (string-match "tmp" (buffer-name b)))))
  16684. b
  16685. nil))
  16686. (buffer-list)))))
  16687. (defun org-agenda-files (&optional unrestricted archives)
  16688. "Get the list of agenda files.
  16689. Optional UNRESTRICTED means return the full list even if a restriction
  16690. is currently in place.
  16691. When ARCHIVES is t, include all archive files that are really being
  16692. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16693. `org-agenda-archives-mode' is t."
  16694. (let ((files
  16695. (cond
  16696. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16697. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16698. ((listp org-agenda-files) org-agenda-files)
  16699. (t (error "Invalid value of `org-agenda-files'")))))
  16700. (setq files (apply 'append
  16701. (mapcar (lambda (f)
  16702. (if (file-directory-p f)
  16703. (directory-files
  16704. f t org-agenda-file-regexp)
  16705. (list f)))
  16706. files)))
  16707. (when org-agenda-skip-unavailable-files
  16708. (setq files (delq nil
  16709. (mapcar (function
  16710. (lambda (file)
  16711. (and (file-readable-p file) file)))
  16712. files))))
  16713. (when (or (eq archives t)
  16714. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16715. (setq files (org-add-archive-files files)))
  16716. files))
  16717. (defun org-agenda-file-p (&optional file)
  16718. "Return non-nil, if FILE is an agenda file.
  16719. If FILE is omitted, use the file associated with the current
  16720. buffer."
  16721. (let ((fname (or file (buffer-file-name))))
  16722. (and fname
  16723. (member (file-truename fname)
  16724. (mapcar #'file-truename (org-agenda-files t))))))
  16725. (defun org-edit-agenda-file-list ()
  16726. "Edit the list of agenda files.
  16727. Depending on setup, this either uses customize to edit the variable
  16728. `org-agenda-files', or it visits the file that is holding the list. In the
  16729. latter case, the buffer is set up in a way that saving it automatically kills
  16730. the buffer and restores the previous window configuration."
  16731. (interactive)
  16732. (if (stringp org-agenda-files)
  16733. (let ((cw (current-window-configuration)))
  16734. (find-file org-agenda-files)
  16735. (setq-local org-window-configuration cw)
  16736. (add-hook 'after-save-hook
  16737. (lambda ()
  16738. (set-window-configuration
  16739. (prog1 org-window-configuration
  16740. (kill-buffer (current-buffer))))
  16741. (org-install-agenda-files-menu)
  16742. (message "New agenda file list installed"))
  16743. nil 'local)
  16744. (message "%s" (substitute-command-keys
  16745. "Edit list and finish with \\[save-buffer]")))
  16746. (customize-variable 'org-agenda-files)))
  16747. (defun org-store-new-agenda-file-list (list)
  16748. "Set new value for the agenda file list and save it correctly."
  16749. (if (stringp org-agenda-files)
  16750. (let ((fe (org-read-agenda-file-list t)) b u)
  16751. (while (setq b (find-buffer-visiting org-agenda-files))
  16752. (kill-buffer b))
  16753. (with-temp-file org-agenda-files
  16754. (insert
  16755. (mapconcat
  16756. (lambda (f) ;; Keep un-expanded entries.
  16757. (if (setq u (assoc f fe))
  16758. (cdr u)
  16759. f))
  16760. list "\n")
  16761. "\n")))
  16762. (let ((org-mode-hook nil) (org-inhibit-startup t)
  16763. (org-insert-mode-line-in-empty-file nil))
  16764. (setq org-agenda-files list)
  16765. (customize-save-variable 'org-agenda-files org-agenda-files))))
  16766. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  16767. "Read the list of agenda files from a file.
  16768. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  16769. filenames, used by `org-store-new-agenda-file-list' to write back
  16770. un-expanded file names."
  16771. (when (file-directory-p org-agenda-files)
  16772. (error "`org-agenda-files' cannot be a single directory"))
  16773. (when (stringp org-agenda-files)
  16774. (with-temp-buffer
  16775. (insert-file-contents org-agenda-files)
  16776. (mapcar
  16777. (lambda (f)
  16778. (let ((e (expand-file-name (substitute-in-file-name f)
  16779. org-directory)))
  16780. (if pair-with-expansion
  16781. (cons e f)
  16782. e)))
  16783. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  16784. ;;;###autoload
  16785. (defun org-cycle-agenda-files ()
  16786. "Cycle through the files in `org-agenda-files'.
  16787. If the current buffer visits an agenda file, find the next one in the list.
  16788. If the current buffer does not, find the first agenda file."
  16789. (interactive)
  16790. (let* ((fs (or (org-agenda-files t)
  16791. (user-error "No agenda files")))
  16792. (files (copy-sequence fs))
  16793. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  16794. file)
  16795. (when tcf
  16796. (while (and (setq file (pop files))
  16797. (not (equal (file-truename file) tcf)))))
  16798. (find-file (car (or files fs)))
  16799. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  16800. (defun org-agenda-file-to-front (&optional to-end)
  16801. "Move/add the current file to the top of the agenda file list.
  16802. If the file is not present in the list, it is added to the front. If it is
  16803. present, it is moved there. With optional argument TO-END, add/move to the
  16804. end of the list."
  16805. (interactive "P")
  16806. (let ((org-agenda-skip-unavailable-files nil)
  16807. (file-alist (mapcar (lambda (x)
  16808. (cons (file-truename x) x))
  16809. (org-agenda-files t)))
  16810. (ctf (file-truename
  16811. (or buffer-file-name
  16812. (user-error "Please save the current buffer to a file"))))
  16813. x had)
  16814. (setq x (assoc ctf file-alist) had x)
  16815. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  16816. (if to-end
  16817. (setq file-alist (append (delq x file-alist) (list x)))
  16818. (setq file-alist (cons x (delq x file-alist))))
  16819. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  16820. (org-install-agenda-files-menu)
  16821. (message "File %s to %s of agenda file list"
  16822. (if had "moved" "added") (if to-end "end" "front"))))
  16823. (defun org-remove-file (&optional file)
  16824. "Remove current file from the list of files in variable `org-agenda-files'.
  16825. These are the files which are being checked for agenda entries.
  16826. Optional argument FILE means use this file instead of the current."
  16827. (interactive)
  16828. (let* ((org-agenda-skip-unavailable-files nil)
  16829. (file (or file buffer-file-name
  16830. (user-error "Current buffer does not visit a file")))
  16831. (true-file (file-truename file))
  16832. (afile (abbreviate-file-name file))
  16833. (files (delq nil (mapcar
  16834. (lambda (x)
  16835. (unless (equal true-file
  16836. (file-truename x))
  16837. x))
  16838. (org-agenda-files t)))))
  16839. (if (not (= (length files) (length (org-agenda-files t))))
  16840. (progn
  16841. (org-store-new-agenda-file-list files)
  16842. (org-install-agenda-files-menu)
  16843. (message "Removed from Org Agenda list: %s" afile))
  16844. (message "File was not in list: %s (not removed)" afile))))
  16845. (defun org-file-menu-entry (file)
  16846. (vector file (list 'find-file file) t))
  16847. (defun org-check-agenda-file (file)
  16848. "Make sure FILE exists. If not, ask user what to do."
  16849. (unless (file-exists-p file)
  16850. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  16851. (abbreviate-file-name file))
  16852. (let ((r (downcase (read-char-exclusive))))
  16853. (cond
  16854. ((equal r ?r)
  16855. (org-remove-file file)
  16856. (throw 'nextfile t))
  16857. (t (user-error "Abort"))))))
  16858. (defun org-get-agenda-file-buffer (file)
  16859. "Get an agenda buffer visiting FILE.
  16860. If the buffer needs to be created, add it to the list of buffers
  16861. which might be released later."
  16862. (let ((buf (org-find-base-buffer-visiting file)))
  16863. (if buf
  16864. buf ; just return it
  16865. ;; Make a new buffer and remember it
  16866. (setq buf (find-file-noselect file))
  16867. (when buf (push buf org-agenda-new-buffers))
  16868. buf)))
  16869. (defun org-release-buffers (blist)
  16870. "Release all buffers in list, asking the user for confirmation when needed.
  16871. When a buffer is unmodified, it is just killed. When modified, it is saved
  16872. \(if the user agrees) and then killed."
  16873. (let (file)
  16874. (dolist (buf blist)
  16875. (setq file (buffer-file-name buf))
  16876. (when (and (buffer-modified-p buf)
  16877. file
  16878. (y-or-n-p (format "Save file %s? " file)))
  16879. (with-current-buffer buf (save-buffer)))
  16880. (kill-buffer buf))))
  16881. (defun org-agenda-prepare-buffers (files)
  16882. "Create buffers for all agenda files, protect archived trees and comments."
  16883. (interactive)
  16884. (let ((pa '(:org-archived t))
  16885. (pc '(:org-comment t))
  16886. (pall '(:org-archived t :org-comment t))
  16887. (inhibit-read-only t)
  16888. (org-inhibit-startup org-agenda-inhibit-startup)
  16889. (rea (concat ":" org-archive-tag ":"))
  16890. re pos)
  16891. (setq org-tag-alist-for-agenda nil
  16892. org-tag-groups-alist-for-agenda nil)
  16893. (save-excursion
  16894. (save-restriction
  16895. (dolist (file files)
  16896. (catch 'nextfile
  16897. (if (bufferp file)
  16898. (set-buffer file)
  16899. (org-check-agenda-file file)
  16900. (set-buffer (org-get-agenda-file-buffer file)))
  16901. (widen)
  16902. (org-set-regexps-and-options 'tags-only)
  16903. (setq pos (point))
  16904. (or (memq 'category org-agenda-ignore-properties)
  16905. (org-refresh-category-properties))
  16906. (or (memq 'stats org-agenda-ignore-properties)
  16907. (org-refresh-stats-properties))
  16908. (or (memq 'effort org-agenda-ignore-properties)
  16909. (org-refresh-effort-properties))
  16910. (or (memq 'appt org-agenda-ignore-properties)
  16911. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  16912. (setq org-todo-keywords-for-agenda
  16913. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  16914. (setq org-done-keywords-for-agenda
  16915. (append org-done-keywords-for-agenda org-done-keywords))
  16916. (setq org-todo-keyword-alist-for-agenda
  16917. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  16918. (setq org-tag-alist-for-agenda
  16919. (org-uniquify
  16920. (append org-tag-alist-for-agenda
  16921. org-current-tag-alist)))
  16922. ;; Merge current file's tag groups into global
  16923. ;; `org-tag-groups-alist-for-agenda'.
  16924. (when org-group-tags
  16925. (dolist (alist org-tag-groups-alist)
  16926. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  16927. (if old
  16928. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  16929. (push alist org-tag-groups-alist-for-agenda)))))
  16930. (org-with-silent-modifications
  16931. (save-excursion
  16932. (remove-text-properties (point-min) (point-max) pall)
  16933. (when org-agenda-skip-archived-trees
  16934. (goto-char (point-min))
  16935. (while (re-search-forward rea nil t)
  16936. (when (org-at-heading-p t)
  16937. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  16938. (goto-char (point-min))
  16939. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  16940. (while (re-search-forward re nil t)
  16941. (when (save-match-data (org-in-commented-heading-p t))
  16942. (add-text-properties
  16943. (match-beginning 0) (org-end-of-subtree t) pc)))))
  16944. (goto-char pos)))))
  16945. (setq org-todo-keywords-for-agenda
  16946. (org-uniquify org-todo-keywords-for-agenda))
  16947. (setq org-todo-keyword-alist-for-agenda
  16948. (org-uniquify org-todo-keyword-alist-for-agenda))))
  16949. ;;;; CDLaTeX minor mode
  16950. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  16951. "Keymap for the minor `org-cdlatex-mode'.")
  16952. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  16953. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  16954. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  16955. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  16956. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  16957. (defvar org-cdlatex-texmathp-advice-is-done nil
  16958. "Flag remembering if we have applied the advice to texmathp already.")
  16959. (define-minor-mode org-cdlatex-mode
  16960. "Toggle the minor `org-cdlatex-mode'.
  16961. This mode supports entering LaTeX environment and math in LaTeX fragments
  16962. in Org mode.
  16963. \\{org-cdlatex-mode-map}"
  16964. nil " OCDL" nil
  16965. (when org-cdlatex-mode
  16966. (require 'cdlatex)
  16967. (run-hooks 'cdlatex-mode-hook)
  16968. (cdlatex-compute-tables))
  16969. (unless org-cdlatex-texmathp-advice-is-done
  16970. (setq org-cdlatex-texmathp-advice-is-done t)
  16971. (defadvice texmathp (around org-math-always-on activate)
  16972. "Always return t in Org buffers.
  16973. This is because we want to insert math symbols without dollars even outside
  16974. the LaTeX math segments. If Org mode thinks that point is actually inside
  16975. an embedded LaTeX fragment, let `texmathp' do its job.
  16976. `\\[org-cdlatex-mode-map]'"
  16977. (interactive)
  16978. (let (p)
  16979. (cond
  16980. ((not (derived-mode-p 'org-mode)) ad-do-it)
  16981. ((eq this-command 'cdlatex-math-symbol)
  16982. (setq ad-return-value t
  16983. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  16984. (t
  16985. (let ((p (org-inside-LaTeX-fragment-p)))
  16986. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  16987. (setq ad-return-value t
  16988. texmathp-why '("Org mode embedded math" . 0))
  16989. (when p ad-do-it)))))))))
  16990. (defun turn-on-org-cdlatex ()
  16991. "Unconditionally turn on `org-cdlatex-mode'."
  16992. (org-cdlatex-mode 1))
  16993. (defun org-try-cdlatex-tab ()
  16994. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  16995. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  16996. - inside a LaTeX fragment, or
  16997. - after the first word in a line, where an abbreviation expansion could
  16998. insert a LaTeX environment."
  16999. (when org-cdlatex-mode
  17000. (cond
  17001. ;; Before any word on the line: No expansion possible.
  17002. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17003. ;; Just after first word on the line: Expand it. Make sure it
  17004. ;; cannot happen on headlines, though.
  17005. ((save-excursion
  17006. (skip-chars-backward "a-zA-Z0-9*")
  17007. (skip-chars-backward " \t")
  17008. (and (bolp) (not (org-at-heading-p))))
  17009. (cdlatex-tab) t)
  17010. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17011. (defun org-cdlatex-underscore-caret (&optional _arg)
  17012. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17013. Revert to the normal definition outside of these fragments."
  17014. (interactive "P")
  17015. (if (org-inside-LaTeX-fragment-p)
  17016. (call-interactively 'cdlatex-sub-superscript)
  17017. (let (org-cdlatex-mode)
  17018. (call-interactively (key-binding (vector last-input-event))))))
  17019. (defun org-cdlatex-math-modify (&optional _arg)
  17020. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17021. Revert to the normal definition outside of these fragments."
  17022. (interactive "P")
  17023. (if (org-inside-LaTeX-fragment-p)
  17024. (call-interactively 'cdlatex-math-modify)
  17025. (let (org-cdlatex-mode)
  17026. (call-interactively (key-binding (vector last-input-event))))))
  17027. (defun org-cdlatex-environment-indent (&optional environment item)
  17028. "Execute `cdlatex-environment' and indent the inserted environment.
  17029. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17030. The inserted environment is indented to current indentation
  17031. unless point is at the beginning of the line, in which the
  17032. environment remains unintended."
  17033. (interactive)
  17034. ;; cdlatex-environment always return nil. Therefore, capture output
  17035. ;; first and determine if an environment was selected.
  17036. (let* ((beg (point-marker))
  17037. (end (copy-marker (point) t))
  17038. (inserted (progn
  17039. (ignore-errors (cdlatex-environment environment item))
  17040. (< beg end)))
  17041. ;; Figure out how many lines to move forward after the
  17042. ;; environment has been inserted.
  17043. (lines (when inserted
  17044. (save-excursion
  17045. (- (cl-loop while (< beg (point))
  17046. with x = 0
  17047. do (forward-line -1)
  17048. (cl-incf x)
  17049. finally return x)
  17050. (if (progn (goto-char beg)
  17051. (and (progn (skip-chars-forward " \t") (eolp))
  17052. (progn (skip-chars-backward " \t") (bolp))))
  17053. 1 0)))))
  17054. (env (org-trim (delete-and-extract-region beg end))))
  17055. (when inserted
  17056. ;; Get indentation of next line unless at column 0.
  17057. (let ((ind (if (bolp) 0
  17058. (save-excursion
  17059. (org-return-indent)
  17060. (prog1 (org-get-indentation)
  17061. (when (progn (skip-chars-forward " \t") (eolp))
  17062. (delete-region beg (point)))))))
  17063. (bol (progn (skip-chars-backward " \t") (bolp))))
  17064. ;; Insert a newline before environment unless at column zero
  17065. ;; to "escape" the current line. Insert a newline if
  17066. ;; something is one the same line as \end{ENVIRONMENT}.
  17067. (insert
  17068. (concat (unless bol "\n") env
  17069. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17070. (unless (zerop ind)
  17071. (save-excursion
  17072. (goto-char beg)
  17073. (while (< (point) end)
  17074. (unless (eolp) (indent-line-to ind))
  17075. (forward-line))))
  17076. (goto-char beg)
  17077. (forward-line lines)
  17078. (indent-line-to ind)))
  17079. (set-marker beg nil)
  17080. (set-marker end nil)))
  17081. ;;;; LaTeX fragments
  17082. (defun org-inside-LaTeX-fragment-p ()
  17083. "Test if point is inside a LaTeX fragment.
  17084. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17085. sequence appearing also before point.
  17086. Even though the matchers for math are configurable, this function assumes
  17087. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17088. delimiters are skipped when they have been removed by customization.
  17089. The return value is nil, or a cons cell with the delimiter and the
  17090. position of this delimiter.
  17091. This function does a reasonably good job, but can locally be fooled by
  17092. for example currency specifications. For example it will assume being in
  17093. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17094. fragments that are properly closed, but during editing, we have to live
  17095. with the uncertainty caused by missing closing delimiters. This function
  17096. looks only before point, not after."
  17097. (catch 'exit
  17098. (let ((pos (point))
  17099. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17100. (lim (progn
  17101. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17102. (point)))
  17103. dd-on str (start 0) m re)
  17104. (goto-char pos)
  17105. (when dodollar
  17106. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17107. re (nth 1 (assoc "$" org-latex-regexps)))
  17108. (while (string-match re str start)
  17109. (cond
  17110. ((= (match-end 0) (length str))
  17111. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17112. ((= (match-end 0) (- (length str) 5))
  17113. (throw 'exit nil))
  17114. (t (setq start (match-end 0))))))
  17115. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17116. (goto-char pos)
  17117. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17118. (and (match-beginning 2) (throw 'exit nil))
  17119. ;; count $$
  17120. (while (re-search-backward "\\$\\$" lim t)
  17121. (setq dd-on (not dd-on)))
  17122. (goto-char pos)
  17123. (when dd-on (cons "$$" m))))))
  17124. (defun org-inside-latex-macro-p ()
  17125. "Is point inside a LaTeX macro or its arguments?"
  17126. (save-match-data
  17127. (org-in-regexp
  17128. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17129. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17130. "Build an overlay between BEG and END using IMAGE file.
  17131. Argument IMAGETYPE is the extension of the displayed image,
  17132. as a string. It defaults to \"png\"."
  17133. (let ((ov (make-overlay beg end))
  17134. (imagetype (or (intern imagetype) 'png)))
  17135. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17136. (overlay-put ov 'evaporate t)
  17137. (overlay-put ov
  17138. 'modification-hooks
  17139. (list (lambda (o _flag _beg _end &optional _l)
  17140. (delete-overlay o))))
  17141. (overlay-put ov
  17142. 'display
  17143. (list 'image :type imagetype :file image :ascent 'center))))
  17144. (defun org--list-latex-overlays (&optional beg end)
  17145. "List all Org LaTeX overlays in current buffer.
  17146. Limit to overlays between BEG and END when those are provided."
  17147. (cl-remove-if-not
  17148. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17149. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17150. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17151. "Remove all overlays with LaTeX fragment images in current buffer.
  17152. When optional arguments BEG and END are non-nil, remove all
  17153. overlays between them instead. Return a non-nil value when some
  17154. overlays were removed, nil otherwise."
  17155. (let ((overlays (org--list-latex-overlays beg end)))
  17156. (mapc #'delete-overlay overlays)
  17157. overlays))
  17158. (defun org-toggle-latex-fragment (&optional arg)
  17159. "Preview the LaTeX fragment at point, or all locally or globally.
  17160. If the cursor is on a LaTeX fragment, create the image and overlay
  17161. it over the source code, if there is none. Remove it otherwise.
  17162. If there is no fragment at point, display all fragments in the
  17163. current section.
  17164. With prefix ARG, preview or clear image for all fragments in the
  17165. current subtree or in the whole buffer when used before the first
  17166. headline. With a prefix ARG `\\[universal-argument] \
  17167. \\[universal-argument]' preview or clear images
  17168. for all fragments in the buffer."
  17169. (interactive "P")
  17170. (when (display-graphic-p)
  17171. (catch 'exit
  17172. (save-excursion
  17173. (let (beg end msg)
  17174. (cond
  17175. ((or (equal arg '(16))
  17176. (and (equal arg '(4))
  17177. (org-with-limited-levels (org-before-first-heading-p))))
  17178. (if (org-remove-latex-fragment-image-overlays)
  17179. (progn (message "LaTeX fragments images removed from buffer")
  17180. (throw 'exit nil))
  17181. (setq msg "Creating images for buffer...")))
  17182. ((equal arg '(4))
  17183. (org-with-limited-levels (org-back-to-heading t))
  17184. (setq beg (point))
  17185. (setq end (progn (org-end-of-subtree t) (point)))
  17186. (if (org-remove-latex-fragment-image-overlays beg end)
  17187. (progn
  17188. (message "LaTeX fragment images removed from subtree")
  17189. (throw 'exit nil))
  17190. (setq msg "Creating images for subtree...")))
  17191. ((let ((datum (org-element-context)))
  17192. (when (memq (org-element-type datum)
  17193. '(latex-environment latex-fragment))
  17194. (setq beg (org-element-property :begin datum))
  17195. (setq end (org-element-property :end datum))
  17196. (if (org-remove-latex-fragment-image-overlays beg end)
  17197. (progn (message "LaTeX fragment image removed")
  17198. (throw 'exit nil))
  17199. (setq msg "Creating image...")))))
  17200. (t
  17201. (org-with-limited-levels
  17202. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17203. (outline-previous-heading)
  17204. (point)))
  17205. (setq end (progn (outline-next-heading) (point)))
  17206. (if (org-remove-latex-fragment-image-overlays beg end)
  17207. (progn
  17208. (message "LaTeX fragment images removed from section")
  17209. (throw 'exit nil))
  17210. (setq msg "Creating images for section...")))))
  17211. (let ((file (buffer-file-name (buffer-base-buffer))))
  17212. (org-format-latex
  17213. (concat org-preview-latex-image-directory "org-ltximg")
  17214. beg end
  17215. ;; Emacs cannot overlay images from remote hosts. Create
  17216. ;; it in `temporary-file-directory' instead.
  17217. (if (or (not file) (file-remote-p file))
  17218. temporary-file-directory
  17219. default-directory)
  17220. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17221. (message (concat msg "done")))))))
  17222. (defun org-format-latex
  17223. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17224. "Replace LaTeX fragments with links to an image.
  17225. The function takes care of creating the replacement image.
  17226. Only consider fragments between BEG and END when those are
  17227. provided.
  17228. When optional argument OVERLAYS is non-nil, display the image on
  17229. top of the fragment instead of replacing it.
  17230. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17231. Some of the options can be changed using the variable
  17232. `org-format-latex-options', which see."
  17233. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17234. (unless (eq processing-type 'verbatim)
  17235. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17236. (cnt 0)
  17237. checkdir-flag)
  17238. (goto-char (or beg (point-min)))
  17239. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17240. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17241. (overlay-recenter (or end (point-max))))
  17242. (while (re-search-forward math-regexp end t)
  17243. (unless (and overlays
  17244. (eq (get-char-property (point) 'org-overlay-type)
  17245. 'org-latex-overlay))
  17246. (let* ((context (org-element-context))
  17247. (type (org-element-type context)))
  17248. (when (memq type '(latex-environment latex-fragment))
  17249. (let ((block-type (eq type 'latex-environment))
  17250. (value (org-element-property :value context))
  17251. (beg (org-element-property :begin context))
  17252. (end (save-excursion
  17253. (goto-char (org-element-property :end context))
  17254. (skip-chars-backward " \r\t\n")
  17255. (point))))
  17256. (cond
  17257. ((eq processing-type 'mathjax)
  17258. ;; Prepare for MathJax processing.
  17259. (if (not (string-match "\\`\\$\\$?" value))
  17260. (goto-char end)
  17261. (delete-region beg end)
  17262. (if (string= (match-string 0 value) "$$")
  17263. (insert "\\[" (substring value 2 -2) "\\]")
  17264. (insert "\\(" (substring value 1 -1) "\\)"))))
  17265. ((assq processing-type org-preview-latex-process-alist)
  17266. ;; Process to an image.
  17267. (cl-incf cnt)
  17268. (goto-char beg)
  17269. (let* ((processing-info
  17270. (cdr (assq processing-type org-preview-latex-process-alist)))
  17271. (face (face-at-point))
  17272. ;; Get the colors from the face at point.
  17273. (fg
  17274. (let ((color (plist-get org-format-latex-options
  17275. :foreground)))
  17276. (if (and forbuffer (eq color 'auto))
  17277. (face-attribute face :foreground nil 'default)
  17278. color)))
  17279. (bg
  17280. (let ((color (plist-get org-format-latex-options
  17281. :background)))
  17282. (if (and forbuffer (eq color 'auto))
  17283. (face-attribute face :background nil 'default)
  17284. color)))
  17285. (hash (sha1 (prin1-to-string
  17286. (list org-format-latex-header
  17287. org-latex-default-packages-alist
  17288. org-latex-packages-alist
  17289. org-format-latex-options
  17290. forbuffer value fg bg))))
  17291. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17292. (absprefix (expand-file-name prefix dir))
  17293. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17294. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17295. (sep (and block-type "\n\n"))
  17296. (link (concat sep "[[file:" linkfile "]]" sep))
  17297. (options
  17298. (org-combine-plists
  17299. org-format-latex-options
  17300. `(:foreground ,fg :background ,bg))))
  17301. (when msg (message msg cnt))
  17302. (unless checkdir-flag ; Ensure the directory exists.
  17303. (setq checkdir-flag t)
  17304. (let ((todir (file-name-directory absprefix)))
  17305. (unless (file-directory-p todir)
  17306. (make-directory todir t))))
  17307. (unless (file-exists-p movefile)
  17308. (org-create-formula-image
  17309. value movefile options forbuffer processing-type))
  17310. (if overlays
  17311. (progn
  17312. (dolist (o (overlays-in beg end))
  17313. (when (eq (overlay-get o 'org-overlay-type)
  17314. 'org-latex-overlay)
  17315. (delete-overlay o)))
  17316. (org--format-latex-make-overlay beg end movefile imagetype)
  17317. (goto-char end))
  17318. (delete-region beg end)
  17319. (insert
  17320. (org-add-props link
  17321. (list 'org-latex-src
  17322. (replace-regexp-in-string "\"" "" value)
  17323. 'org-latex-src-embed-type
  17324. (if block-type 'paragraph 'character)))))))
  17325. ((eq processing-type 'mathml)
  17326. ;; Process to MathML.
  17327. (unless (org-format-latex-mathml-available-p)
  17328. (user-error "LaTeX to MathML converter not configured"))
  17329. (cl-incf cnt)
  17330. (when msg (message msg cnt))
  17331. (goto-char beg)
  17332. (delete-region beg end)
  17333. (insert (org-format-latex-as-mathml
  17334. value block-type prefix dir)))
  17335. (t
  17336. (error "Unknown conversion process %s for LaTeX fragments"
  17337. processing-type)))))))))))
  17338. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17339. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17340. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17341. sucessful, return the portion between \"<math...> </math>\"
  17342. elements otherwise return nil. When MATHML-FILE is specified,
  17343. write the results in to that file. When invoked as an
  17344. interactive command, prompt for LATEX-FRAG, with initial value
  17345. set to the current active region and echo the results for user
  17346. inspection."
  17347. (interactive (list (let ((frag (when (org-region-active-p)
  17348. (buffer-substring-no-properties
  17349. (region-beginning) (region-end)))))
  17350. (read-string "LaTeX Fragment: " frag nil frag))))
  17351. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17352. (let* ((tmp-in-file
  17353. (let ((file (file-relative-name
  17354. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17355. (write-region latex-frag nil file)
  17356. file))
  17357. (tmp-out-file (file-relative-name
  17358. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17359. (cmd (format-spec
  17360. org-latex-to-mathml-convert-command
  17361. `((?j . ,(and org-latex-to-mathml-jar-file
  17362. (shell-quote-argument
  17363. (expand-file-name
  17364. org-latex-to-mathml-jar-file))))
  17365. (?I . ,(shell-quote-argument tmp-in-file))
  17366. (?i . ,latex-frag)
  17367. (?o . ,(shell-quote-argument tmp-out-file)))))
  17368. mathml shell-command-output)
  17369. (when (called-interactively-p 'any)
  17370. (unless (org-format-latex-mathml-available-p)
  17371. (user-error "LaTeX to MathML converter not configured")))
  17372. (message "Running %s" cmd)
  17373. (setq shell-command-output (shell-command-to-string cmd))
  17374. (setq mathml
  17375. (when (file-readable-p tmp-out-file)
  17376. (with-current-buffer (find-file-noselect tmp-out-file t)
  17377. (goto-char (point-min))
  17378. (when (re-search-forward
  17379. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17380. (regexp-quote
  17381. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17382. nil t)
  17383. (prog1 (match-string 0) (kill-buffer))))))
  17384. (cond
  17385. (mathml
  17386. (setq mathml
  17387. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17388. (when mathml-file
  17389. (write-region mathml nil mathml-file))
  17390. (when (called-interactively-p 'any)
  17391. (message mathml)))
  17392. ((message "LaTeX to MathML conversion failed")
  17393. (message shell-command-output)))
  17394. (delete-file tmp-in-file)
  17395. (when (file-exists-p tmp-out-file)
  17396. (delete-file tmp-out-file))
  17397. mathml))
  17398. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17399. prefix &optional dir)
  17400. "Use `org-create-math-formula' but check local cache first."
  17401. (let* ((absprefix (expand-file-name prefix dir))
  17402. (print-length nil) (print-level nil)
  17403. (formula-id (concat
  17404. "formula-"
  17405. (sha1
  17406. (prin1-to-string
  17407. (list latex-frag
  17408. org-latex-to-mathml-convert-command)))))
  17409. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17410. (formula-cache-dir (file-name-directory formula-cache)))
  17411. (unless (file-directory-p formula-cache-dir)
  17412. (make-directory formula-cache-dir t))
  17413. (unless (file-exists-p formula-cache)
  17414. (org-create-math-formula latex-frag formula-cache))
  17415. (if (file-exists-p formula-cache)
  17416. ;; Successful conversion. Return the link to MathML file.
  17417. (org-add-props
  17418. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17419. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17420. 'org-latex-src-embed-type (if latex-frag-type
  17421. 'paragraph 'character)))
  17422. ;; Failed conversion. Return the LaTeX fragment verbatim
  17423. latex-frag)))
  17424. (defun org--get-display-dpi ()
  17425. "Get the DPI of the display.
  17426. The function assumes that the display has the same pixel width in
  17427. the horizontal and vertical directions."
  17428. (if (display-graphic-p)
  17429. (round (/ (display-pixel-height)
  17430. (/ (display-mm-height) 25.4)))
  17431. (error "Attempt to calculate the dpi of a non-graphic display")))
  17432. (defun org-create-formula-image
  17433. (string tofile options buffer &optional processing-type)
  17434. "Create an image from LaTeX source using external processes.
  17435. The LaTeX STRING is saved to a temporary LaTeX file, then
  17436. converted to an image file by process PROCESSING-TYPE defined in
  17437. `org-preview-latex-process-alist'. A nil value defaults to
  17438. `org-preview-latex-default-process'.
  17439. The generated image file is eventually moved to TOFILE.
  17440. The OPTIONS argument controls the size, foreground color and
  17441. background color of the generated image.
  17442. When BUFFER non-nil, this function is used for LaTeX previewing.
  17443. Otherwise, it is used to deal with LaTeX snippets showed in
  17444. a HTML file."
  17445. (let* ((processing-type (or processing-type
  17446. org-preview-latex-default-process))
  17447. (processing-info
  17448. (cdr (assq processing-type org-preview-latex-process-alist)))
  17449. (programs (plist-get processing-info :programs))
  17450. (error-message (or (plist-get processing-info :message) ""))
  17451. (use-xcolor (plist-get processing-info :use-xcolor))
  17452. (image-input-type (plist-get processing-info :image-input-type))
  17453. (image-output-type (plist-get processing-info :image-output-type))
  17454. (post-clean (or (plist-get processing-info :post-clean)
  17455. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17456. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17457. (latex-header
  17458. (or (plist-get processing-info :latex-header)
  17459. (org-latex-make-preamble
  17460. (org-export-get-environment (org-export-get-backend 'latex))
  17461. org-format-latex-header
  17462. 'snippet)))
  17463. (latex-compiler (plist-get processing-info :latex-compiler))
  17464. (image-converter (plist-get processing-info :image-converter))
  17465. (tmpdir temporary-file-directory)
  17466. (texfilebase (make-temp-name
  17467. (expand-file-name "orgtex" tmpdir)))
  17468. (texfile (concat texfilebase ".tex"))
  17469. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17470. '(1.0 . 1.0)))
  17471. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17472. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17473. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17474. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17475. "Black"))
  17476. (bg (or (plist-get options (if buffer :background :html-background))
  17477. "Transparent"))
  17478. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17479. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17480. (dolist (program programs)
  17481. (org-check-external-command program error-message))
  17482. (if use-xcolor
  17483. (progn (if (eq fg 'default)
  17484. (setq fg (org-latex-color :foreground))
  17485. (setq fg (org-latex-color-format fg)))
  17486. (if (eq bg 'default)
  17487. (setq bg (org-latex-color :background))
  17488. (setq bg (org-latex-color-format
  17489. (if (string= bg "Transparent") "white" bg))))
  17490. (with-temp-file texfile
  17491. (insert latex-header)
  17492. (insert "\n\\begin{document}\n"
  17493. "\\definecolor{fg}{rgb}{" fg "}\n"
  17494. "\\definecolor{bg}{rgb}{" bg "}\n"
  17495. "\n\\pagecolor{bg}\n"
  17496. "\n{\\color{fg}\n"
  17497. string
  17498. "\n}\n"
  17499. "\n\\end{document}\n")))
  17500. (if (eq fg 'default)
  17501. (setq fg (org-dvipng-color :foreground))
  17502. (unless (string= fg "Transparent")
  17503. (setq fg (org-dvipng-color-format fg))))
  17504. (if (eq bg 'default)
  17505. (setq bg (org-dvipng-color :background))
  17506. (unless (string= bg "Transparent")
  17507. (setq bg (org-dvipng-color-format bg))))
  17508. (with-temp-file texfile
  17509. (insert latex-header)
  17510. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17511. (let* ((err-msg (format "Please adjust '%s' part of \
  17512. `org-preview-latex-process-alist'."
  17513. processing-type))
  17514. (image-input-file
  17515. (org-compile-file
  17516. texfile latex-compiler image-input-type err-msg log-buf))
  17517. (image-output-file
  17518. (org-compile-file
  17519. image-input-file image-converter image-output-type err-msg log-buf
  17520. `((?F . ,(shell-quote-argument fg))
  17521. (?B . ,(shell-quote-argument bg))
  17522. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17523. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17524. (copy-file image-output-file tofile 'replace)
  17525. (dolist (e post-clean)
  17526. (when (file-exists-p (concat texfilebase e))
  17527. (delete-file (concat texfilebase e))))
  17528. image-output-file)))
  17529. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17530. "Fill a LaTeX header template TPL.
  17531. In the template, the following place holders will be recognized:
  17532. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17533. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17534. [PACKAGES] \\usepackage statements for PKG
  17535. [NO-PACKAGES] do not include PKG
  17536. [EXTRA] the string EXTRA
  17537. [NO-EXTRA] do not include EXTRA
  17538. For backward compatibility, if both the positive and the negative place
  17539. holder is missing, the positive one (without the \"NO-\") will be
  17540. assumed to be present at the end of the template.
  17541. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17542. EXTRA is a string.
  17543. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17544. (let (rpl (end ""))
  17545. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17546. (setq rpl (if (or (match-end 1) (not def-pkg))
  17547. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17548. tpl (replace-match rpl t t tpl))
  17549. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17550. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17551. (setq rpl (if (or (match-end 1) (not pkg))
  17552. "" (org-latex-packages-to-string pkg snippets-p t))
  17553. tpl (replace-match rpl t t tpl))
  17554. (when pkg (setq end
  17555. (concat end "\n"
  17556. (org-latex-packages-to-string pkg snippets-p)))))
  17557. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17558. (setq rpl (if (or (match-end 1) (not extra))
  17559. "" (concat extra "\n"))
  17560. tpl (replace-match rpl t t tpl))
  17561. (when (and extra (string-match "\\S-" extra))
  17562. (setq end (concat end "\n" extra))))
  17563. (if (string-match "\\S-" end)
  17564. (concat tpl "\n" end)
  17565. tpl)))
  17566. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17567. "Turn an alist of packages into a string with the \\usepackage macros."
  17568. (setq pkg (mapconcat (lambda(p)
  17569. (cond
  17570. ((stringp p) p)
  17571. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17572. (format "%% Package %s omitted" (cadr p)))
  17573. ((equal "" (car p))
  17574. (format "\\usepackage{%s}" (cadr p)))
  17575. (t
  17576. (format "\\usepackage[%s]{%s}"
  17577. (car p) (cadr p)))))
  17578. pkg
  17579. "\n"))
  17580. (if newline (concat pkg "\n") pkg))
  17581. (defun org-dvipng-color (attr)
  17582. "Return a RGB color specification for dvipng."
  17583. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17584. (defun org-dvipng-color-format (color-name)
  17585. "Convert COLOR-NAME to a RGB color value for dvipng."
  17586. (apply #'format "rgb %s %s %s"
  17587. (mapcar 'org-normalize-color
  17588. (color-values color-name))))
  17589. (defun org-latex-color (attr)
  17590. "Return a RGB color for the LaTeX color package."
  17591. (org-latex-color-format (face-attribute 'default attr nil)))
  17592. (defun org-latex-color-format (color-name)
  17593. "Convert COLOR-NAME to a RGB color value."
  17594. (apply #'format "%s,%s,%s"
  17595. (mapcar 'org-normalize-color
  17596. (color-values color-name))))
  17597. (defun org-normalize-color (value)
  17598. "Return string to be used as color value for an RGB component."
  17599. (format "%g" (/ value 65535.0)))
  17600. ;; Image display
  17601. (defvar-local org-inline-image-overlays nil)
  17602. (defun org-toggle-inline-images (&optional include-linked)
  17603. "Toggle the display of inline images.
  17604. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17605. (interactive "P")
  17606. (if org-inline-image-overlays
  17607. (progn
  17608. (org-remove-inline-images)
  17609. (when (called-interactively-p 'interactive)
  17610. (message "Inline image display turned off")))
  17611. (org-display-inline-images include-linked)
  17612. (when (called-interactively-p 'interactive)
  17613. (message (if org-inline-image-overlays
  17614. (format "%d images displayed inline"
  17615. (length org-inline-image-overlays))
  17616. "No images to display inline")))))
  17617. (defun org-redisplay-inline-images ()
  17618. "Refresh the display of inline images."
  17619. (interactive)
  17620. (if (not org-inline-image-overlays)
  17621. (org-toggle-inline-images)
  17622. (org-toggle-inline-images)
  17623. (org-toggle-inline-images)))
  17624. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17625. "Display inline images.
  17626. An inline image is a link which follows either of these
  17627. conventions:
  17628. 1. Its path is a file with an extension matching return value
  17629. from `image-file-name-regexp' and it has no contents.
  17630. 2. Its description consists in a single link of the previous
  17631. type.
  17632. When optional argument INCLUDE-LINKED is non-nil, also links with
  17633. a text description part will be inlined. This can be nice for
  17634. a quick look at those images, but it does not reflect what
  17635. exported files will look like.
  17636. When optional argument REFRESH is non-nil, refresh existing
  17637. images between BEG and END. This will create new image displays
  17638. only if necessary. BEG and END default to the buffer
  17639. boundaries."
  17640. (interactive "P")
  17641. (when (display-graphic-p)
  17642. (unless refresh
  17643. (org-remove-inline-images)
  17644. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17645. (org-with-wide-buffer
  17646. (goto-char (or beg (point-min)))
  17647. (let ((case-fold-search t)
  17648. (file-extension-re (image-file-name-regexp)))
  17649. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17650. (let ((link (save-match-data (org-element-context))))
  17651. ;; Check if we're at an inline image.
  17652. (when (and (equal (org-element-property :type link) "file")
  17653. (or include-linked
  17654. (not (org-element-property :contents-begin link)))
  17655. (let ((parent (org-element-property :parent link)))
  17656. (or (not (eq (org-element-type parent) 'link))
  17657. (not (cdr (org-element-contents parent)))))
  17658. (string-match-p file-extension-re
  17659. (org-element-property :path link)))
  17660. (let ((file (expand-file-name
  17661. (org-link-unescape
  17662. (org-element-property :path link)))))
  17663. (when (file-exists-p file)
  17664. (let ((width
  17665. ;; Apply `org-image-actual-width' specifications.
  17666. (cond
  17667. ((not (image-type-available-p 'imagemagick)) nil)
  17668. ((eq org-image-actual-width t) nil)
  17669. ((listp org-image-actual-width)
  17670. (or
  17671. ;; First try to find a width among
  17672. ;; attributes associated to the paragraph
  17673. ;; containing link.
  17674. (let ((paragraph
  17675. (let ((e link))
  17676. (while (and (setq e (org-element-property
  17677. :parent e))
  17678. (not (eq (org-element-type e)
  17679. 'paragraph))))
  17680. e)))
  17681. (when paragraph
  17682. (save-excursion
  17683. (goto-char (org-element-property :begin paragraph))
  17684. (when
  17685. (re-search-forward
  17686. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17687. (org-element-property
  17688. :post-affiliated paragraph)
  17689. t)
  17690. (string-to-number (match-string 1))))))
  17691. ;; Otherwise, fall-back to provided number.
  17692. (car org-image-actual-width)))
  17693. ((numberp org-image-actual-width)
  17694. org-image-actual-width)))
  17695. (old (get-char-property-and-overlay
  17696. (org-element-property :begin link)
  17697. 'org-image-overlay)))
  17698. (if (and (car-safe old) refresh)
  17699. (image-refresh (overlay-get (cdr old) 'display))
  17700. (let ((image (create-image file
  17701. (and width 'imagemagick)
  17702. nil
  17703. :width width)))
  17704. (when image
  17705. (let* ((link
  17706. ;; If inline image is the description
  17707. ;; of another link, be sure to
  17708. ;; consider the latter as the one to
  17709. ;; apply the overlay on.
  17710. (let ((parent
  17711. (org-element-property :parent link)))
  17712. (if (eq (org-element-type parent) 'link)
  17713. parent
  17714. link)))
  17715. (ov (make-overlay
  17716. (org-element-property :begin link)
  17717. (progn
  17718. (goto-char
  17719. (org-element-property :end link))
  17720. (skip-chars-backward " \t")
  17721. (point)))))
  17722. (overlay-put ov 'display image)
  17723. (overlay-put ov 'face 'default)
  17724. (overlay-put ov 'org-image-overlay t)
  17725. (overlay-put
  17726. ov 'modification-hooks
  17727. (list 'org-display-inline-remove-overlay))
  17728. (push ov org-inline-image-overlays)))))))))))))))
  17729. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17730. "Remove inline-display overlay if a corresponding region is modified."
  17731. (let ((inhibit-modification-hooks t))
  17732. (when (and ov after)
  17733. (delete ov org-inline-image-overlays)
  17734. (delete-overlay ov))))
  17735. (defun org-remove-inline-images ()
  17736. "Remove inline display of images."
  17737. (interactive)
  17738. (mapc #'delete-overlay org-inline-image-overlays)
  17739. (setq org-inline-image-overlays nil))
  17740. ;;;; Key bindings
  17741. ;; Outline functions from `outline-mode-prefix-map'
  17742. ;; that can be remapped in Org:
  17743. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17744. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17745. (define-key org-mode-map [remap outline-forward-same-level]
  17746. 'org-forward-heading-same-level)
  17747. (define-key org-mode-map [remap outline-backward-same-level]
  17748. 'org-backward-heading-same-level)
  17749. (define-key org-mode-map [remap outline-show-branches]
  17750. 'org-kill-note-or-show-branches)
  17751. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17752. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17753. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17754. (define-key org-mode-map [remap outline-next-visible-heading]
  17755. 'org-next-visible-heading)
  17756. (define-key org-mode-map [remap outline-previous-visible-heading]
  17757. 'org-previous-visible-heading)
  17758. (define-key org-mode-map [remap show-children] 'org-show-children)
  17759. ;; Outline functions from `outline-mode-prefix-map' that can not
  17760. ;; be remapped in Org:
  17761. ;; - the column "key binding" shows whether the Outline function is still
  17762. ;; available in Org mode on the same key that it has been bound to in
  17763. ;; Outline mode:
  17764. ;; - "overridden": key used for a different functionality in Org mode
  17765. ;; - else: key still bound to the same Outline function in Org mode
  17766. ;; | Outline function | key binding | Org replacement |
  17767. ;; |------------------------------------+-------------+--------------------------|
  17768. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  17769. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  17770. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  17771. ;; | `show-entry' | overridden | no replacement |
  17772. ;; | `show-branches' | `C-c C-k' | still same function |
  17773. ;; | `show-subtree' | overridden | visibility cycling |
  17774. ;; | `show-all' | overridden | no replacement |
  17775. ;; | `hide-subtree' | overridden | visibility cycling |
  17776. ;; | `hide-body' | overridden | no replacement |
  17777. ;; | `hide-entry' | overridden | visibility cycling |
  17778. ;; | `hide-leaves' | overridden | no replacement |
  17779. ;; | `hide-sublevels' | overridden | no replacement |
  17780. ;; | `hide-other' | overridden | no replacement |
  17781. ;; Make `C-c C-x' a prefix key
  17782. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  17783. ;; TAB key with modifiers
  17784. (org-defkey org-mode-map "\C-i" 'org-cycle)
  17785. (org-defkey org-mode-map [(tab)] 'org-cycle)
  17786. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  17787. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  17788. ;; The following line is necessary under Suse GNU/Linux
  17789. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  17790. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  17791. (define-key org-mode-map [backtab] 'org-shifttab)
  17792. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  17793. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  17794. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  17795. ;; Cursor keys with modifiers
  17796. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  17797. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  17798. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  17799. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  17800. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  17801. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  17802. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  17803. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  17804. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  17805. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  17806. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  17807. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  17808. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  17809. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  17810. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  17811. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  17812. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  17813. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  17814. ;; Babel keys
  17815. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  17816. (dolist (pair org-babel-key-bindings)
  17817. (define-key org-babel-map (car pair) (cdr pair)))
  17818. ;;; Extra keys for tty access.
  17819. ;; We only set them when really needed because otherwise the
  17820. ;; menus don't show the simple keys
  17821. (when (or org-use-extra-keys (not window-system))
  17822. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  17823. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  17824. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  17825. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  17826. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  17827. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  17828. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  17829. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  17830. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  17831. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  17832. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  17833. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  17834. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  17835. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  17836. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  17837. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  17838. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  17839. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  17840. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  17841. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  17842. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  17843. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  17844. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  17845. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  17846. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  17847. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  17848. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  17849. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  17850. ;; All the other keys
  17851. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  17852. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  17853. (if (boundp 'narrow-map)
  17854. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  17855. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  17856. (if (boundp 'narrow-map)
  17857. (org-defkey narrow-map "b" 'org-narrow-to-block)
  17858. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  17859. (if (boundp 'narrow-map)
  17860. (org-defkey narrow-map "e" 'org-narrow-to-element)
  17861. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  17862. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  17863. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  17864. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  17865. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  17866. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  17867. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  17868. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  17869. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  17870. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  17871. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  17872. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  17873. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  17874. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  17875. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  17876. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  17877. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  17878. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  17879. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  17880. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  17881. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  17882. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  17883. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  17884. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  17885. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  17886. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  17887. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  17888. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  17889. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  17890. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  17891. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  17892. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  17893. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  17894. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  17895. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  17896. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  17897. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  17898. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  17899. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  17900. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  17901. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  17902. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  17903. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  17904. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  17905. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  17906. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  17907. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  17908. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  17909. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  17910. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  17911. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  17912. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  17913. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  17914. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  17915. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  17916. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  17917. (org-defkey org-mode-map "\C-c^" 'org-sort)
  17918. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  17919. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  17920. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  17921. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  17922. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  17923. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  17924. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  17925. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  17926. (org-defkey org-mode-map "\C-m" 'org-return)
  17927. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  17928. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  17929. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  17930. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  17931. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  17932. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  17933. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  17934. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  17935. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  17936. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  17937. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  17938. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  17939. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  17940. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  17941. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  17942. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  17943. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  17944. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  17945. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  17946. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  17947. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  17948. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  17949. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  17950. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  17951. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  17952. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  17953. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  17954. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  17955. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  17956. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  17957. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  17958. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  17959. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  17960. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  17961. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  17962. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  17963. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  17964. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  17965. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  17966. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  17967. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  17968. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  17969. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  17970. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  17971. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  17972. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  17973. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  17974. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  17975. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  17976. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  17977. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  17978. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  17979. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  17980. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  17981. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  17982. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  17983. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  17984. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  17985. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  17986. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  17987. (defconst org-speed-commands-default
  17988. '(
  17989. ("Outline Navigation")
  17990. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  17991. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  17992. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  17993. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  17994. ("F" . org-next-block)
  17995. ("B" . org-previous-block)
  17996. ("u" . (org-speed-move-safe 'outline-up-heading))
  17997. ("j" . org-goto)
  17998. ("g" . (org-refile t))
  17999. ("Outline Visibility")
  18000. ("c" . org-cycle)
  18001. ("C" . org-shifttab)
  18002. (" " . org-display-outline-path)
  18003. ("s" . org-narrow-to-subtree)
  18004. ("=" . org-columns)
  18005. ("Outline Structure Editing")
  18006. ("U" . org-metaup)
  18007. ("D" . org-metadown)
  18008. ("r" . org-metaright)
  18009. ("l" . org-metaleft)
  18010. ("R" . org-shiftmetaright)
  18011. ("L" . org-shiftmetaleft)
  18012. ("i" . (progn (forward-char 1) (call-interactively
  18013. 'org-insert-heading-respect-content)))
  18014. ("^" . org-sort)
  18015. ("w" . org-refile)
  18016. ("a" . org-archive-subtree-default-with-confirmation)
  18017. ("@" . org-mark-subtree)
  18018. ("#" . org-toggle-comment)
  18019. ("Clock Commands")
  18020. ("I" . org-clock-in)
  18021. ("O" . org-clock-out)
  18022. ("Meta Data Editing")
  18023. ("t" . org-todo)
  18024. ("," . (org-priority))
  18025. ("0" . (org-priority ?\ ))
  18026. ("1" . (org-priority ?A))
  18027. ("2" . (org-priority ?B))
  18028. ("3" . (org-priority ?C))
  18029. (":" . org-set-tags-command)
  18030. ("e" . org-set-effort)
  18031. ("E" . org-inc-effort)
  18032. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18033. (org-entry-put (point) "APPT_WARNTIME" m)))
  18034. ("Agenda Views etc")
  18035. ("v" . org-agenda)
  18036. ("/" . org-sparse-tree)
  18037. ("Misc")
  18038. ("o" . org-open-at-point)
  18039. ("?" . org-speed-command-help)
  18040. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18041. (">" . (org-agenda-remove-restriction-lock))
  18042. )
  18043. "The default speed commands.")
  18044. (defun org-print-speed-command (e)
  18045. (if (> (length (car e)) 1)
  18046. (progn
  18047. (princ "\n")
  18048. (princ (car e))
  18049. (princ "\n")
  18050. (princ (make-string (length (car e)) ?-))
  18051. (princ "\n"))
  18052. (princ (car e))
  18053. (princ " ")
  18054. (if (symbolp (cdr e))
  18055. (princ (symbol-name (cdr e)))
  18056. (prin1 (cdr e)))
  18057. (princ "\n")))
  18058. (defun org-speed-command-help ()
  18059. "Show the available speed commands."
  18060. (interactive)
  18061. (if (not org-use-speed-commands)
  18062. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18063. (with-output-to-temp-buffer "*Help*"
  18064. (princ "User-defined Speed commands\n===========================\n")
  18065. (mapc #'org-print-speed-command org-speed-commands-user)
  18066. (princ "\n")
  18067. (princ "Built-in Speed commands\n=======================\n")
  18068. (mapc #'org-print-speed-command org-speed-commands-default))
  18069. (with-current-buffer "*Help*"
  18070. (setq truncate-lines t))))
  18071. (defun org-speed-move-safe (cmd)
  18072. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18073. If not, return to the original position and throw an error."
  18074. (interactive)
  18075. (let ((pos (point)))
  18076. (call-interactively cmd)
  18077. (unless (and (bolp) (org-at-heading-p))
  18078. (goto-char pos)
  18079. (error "Boundary reached while executing %s" cmd))))
  18080. (defvar org-self-insert-command-undo-counter 0)
  18081. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18082. (defvar org-speed-command nil)
  18083. (defun org-speed-command-activate (keys)
  18084. "Hook for activating single-letter speed commands.
  18085. `org-speed-commands-default' specifies a minimal command set.
  18086. Use `org-speed-commands-user' for further customization."
  18087. (when (or (and (bolp) (looking-at org-outline-regexp))
  18088. (and (functionp org-use-speed-commands)
  18089. (funcall org-use-speed-commands)))
  18090. (cdr (assoc keys (append org-speed-commands-user
  18091. org-speed-commands-default)))))
  18092. (defun org-babel-speed-command-activate (keys)
  18093. "Hook for activating single-letter code block commands."
  18094. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18095. (cdr (assoc keys org-babel-key-bindings))))
  18096. (defcustom org-speed-command-hook
  18097. '(org-speed-command-activate org-babel-speed-command-activate)
  18098. "Hook for activating speed commands at strategic locations.
  18099. Hook functions are called in sequence until a valid handler is
  18100. found.
  18101. Each hook takes a single argument, a user-pressed command key
  18102. which is also a `self-insert-command' from the global map.
  18103. Within the hook, examine the cursor position and the command key
  18104. and return nil or a valid handler as appropriate. Handler could
  18105. be one of an interactive command, a function, or a form.
  18106. Set `org-use-speed-commands' to non-nil value to enable this
  18107. hook. The default setting is `org-speed-command-activate'."
  18108. :group 'org-structure
  18109. :version "24.1"
  18110. :type 'hook)
  18111. (defun org-self-insert-command (N)
  18112. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18113. If the cursor is in a table looking at whitespace, the whitespace is
  18114. overwritten, and the table is not marked as requiring realignment."
  18115. (interactive "p")
  18116. (org-check-before-invisible-edit 'insert)
  18117. (cond
  18118. ((and org-use-speed-commands
  18119. (let ((kv (this-command-keys-vector)))
  18120. (setq org-speed-command
  18121. (run-hook-with-args-until-success
  18122. 'org-speed-command-hook
  18123. (make-string 1 (aref kv (1- (length kv))))))))
  18124. (cond
  18125. ((commandp org-speed-command)
  18126. (setq this-command org-speed-command)
  18127. (call-interactively org-speed-command))
  18128. ((functionp org-speed-command)
  18129. (funcall org-speed-command))
  18130. ((and org-speed-command (listp org-speed-command))
  18131. (eval org-speed-command))
  18132. (t (let (org-use-speed-commands)
  18133. (call-interactively 'org-self-insert-command)))))
  18134. ((and
  18135. (org-at-table-p)
  18136. (progn
  18137. ;; Check if we blank the field, and if that triggers align.
  18138. (and (featurep 'org-table) org-table-auto-blank-field
  18139. (memq last-command
  18140. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18141. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18142. ;; Got extra space, this field does not determine
  18143. ;; column width.
  18144. (let (org-table-may-need-update) (org-table-blank-field))
  18145. ;; No extra space, this field may determine column
  18146. ;; width.
  18147. (org-table-blank-field)))
  18148. t)
  18149. (eq N 1)
  18150. (looking-at "[^|\n]* \\( \\)|"))
  18151. ;; There is room for insertion without re-aligning the table.
  18152. (delete-region (match-beginning 1) (match-end 1))
  18153. (self-insert-command N))
  18154. (t
  18155. (setq org-table-may-need-update t)
  18156. (self-insert-command N)
  18157. (org-fix-tags-on-the-fly)
  18158. (when org-self-insert-cluster-for-undo
  18159. (if (not (eq last-command 'org-self-insert-command))
  18160. (setq org-self-insert-command-undo-counter 1)
  18161. (if (>= org-self-insert-command-undo-counter 20)
  18162. (setq org-self-insert-command-undo-counter 1)
  18163. (and (> org-self-insert-command-undo-counter 0)
  18164. buffer-undo-list (listp buffer-undo-list)
  18165. (not (cadr buffer-undo-list)) ; remove nil entry
  18166. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18167. (setq org-self-insert-command-undo-counter
  18168. (1+ org-self-insert-command-undo-counter))))))))
  18169. (defun org-check-before-invisible-edit (kind)
  18170. "Check is editing if kind KIND would be dangerous with invisible text around.
  18171. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18172. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18173. (when (and org-catch-invisible-edits
  18174. (or (not (boundp 'visible-mode)) (not visible-mode))
  18175. (or (get-char-property (point) 'invisible)
  18176. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18177. ;; OK, we need to take a closer look
  18178. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18179. (invisible-before-point (unless (bobp) (get-char-property
  18180. (1- (point)) 'invisible)))
  18181. (border-and-ok-direction
  18182. (or
  18183. ;; Check if we are acting predictably before invisible text
  18184. (and invisible-at-point (not invisible-before-point)
  18185. (memq kind '(insert delete-backward)))
  18186. ;; Check if we are acting predictably after invisible text
  18187. ;; This works not well, and I have turned it off. It seems
  18188. ;; better to always show and stop after invisible text.
  18189. ;; (and (not invisible-at-point) invisible-before-point
  18190. ;; (memq kind '(insert delete)))
  18191. )))
  18192. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18193. (memq invisible-before-point '(outline org-hide-block t)))
  18194. (when (eq org-catch-invisible-edits 'error)
  18195. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18196. (if (and org-custom-properties-overlays
  18197. (y-or-n-p "Display invisible properties in this buffer? "))
  18198. (org-toggle-custom-properties-visibility)
  18199. ;; Make the area visible
  18200. (save-excursion
  18201. (when invisible-before-point
  18202. (goto-char (previous-single-char-property-change
  18203. (point) 'invisible)))
  18204. (outline-show-subtree))
  18205. (cond
  18206. ((eq org-catch-invisible-edits 'show)
  18207. ;; That's it, we do the edit after showing
  18208. (message
  18209. "Unfolding invisible region around point before editing")
  18210. (sit-for 1))
  18211. ((and (eq org-catch-invisible-edits 'smart)
  18212. border-and-ok-direction)
  18213. (message "Unfolding invisible region around point before editing"))
  18214. (t
  18215. ;; Don't do the edit, make the user repeat it in full visibility
  18216. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18217. (defun org-fix-tags-on-the-fly ()
  18218. "Align tags in headline at point.
  18219. Unlike to `org-set-tags', it ignores region and sorting."
  18220. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18221. (org-at-heading-p))
  18222. (let ((org-ignore-region t)
  18223. (org-tags-sort-function nil))
  18224. (org-set-tags nil t))))
  18225. (defun org-delete-backward-char (N)
  18226. "Like `delete-backward-char', insert whitespace at field end in tables.
  18227. When deleting backwards, in tables this function will insert whitespace in
  18228. front of the next \"|\" separator, to keep the table aligned. The table will
  18229. still be marked for re-alignment if the field did fill the entire column,
  18230. because, in this case the deletion might narrow the column."
  18231. (interactive "p")
  18232. (save-match-data
  18233. (org-check-before-invisible-edit 'delete-backward)
  18234. (if (and (org-at-table-p)
  18235. (eq N 1)
  18236. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18237. (looking-at ".*?|"))
  18238. (let ((pos (point))
  18239. (noalign (looking-at "[^|\n\r]* |"))
  18240. (c org-table-may-need-update))
  18241. (backward-delete-char N)
  18242. (unless overwrite-mode
  18243. (skip-chars-forward "^|")
  18244. (insert " ")
  18245. (goto-char (1- pos)))
  18246. ;; noalign: if there were two spaces at the end, this field
  18247. ;; does not determine the width of the column.
  18248. (when noalign (setq org-table-may-need-update c)))
  18249. (backward-delete-char N)
  18250. (org-fix-tags-on-the-fly))))
  18251. (defun org-delete-char (N)
  18252. "Like `delete-char', but insert whitespace at field end in tables.
  18253. When deleting characters, in tables this function will insert whitespace in
  18254. front of the next \"|\" separator, to keep the table aligned. The table will
  18255. still be marked for re-alignment if the field did fill the entire column,
  18256. because, in this case the deletion might narrow the column."
  18257. (interactive "p")
  18258. (save-match-data
  18259. (org-check-before-invisible-edit 'delete)
  18260. (if (and (org-at-table-p)
  18261. (not (bolp))
  18262. (not (= (char-after) ?|))
  18263. (eq N 1))
  18264. (if (looking-at ".*?|")
  18265. (let ((pos (point))
  18266. (noalign (looking-at "[^|\n\r]* |"))
  18267. (c org-table-may-need-update))
  18268. (replace-match
  18269. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18270. (goto-char pos)
  18271. ;; noalign: if there were two spaces at the end, this field
  18272. ;; does not determine the width of the column.
  18273. (when noalign (setq org-table-may-need-update c)))
  18274. (delete-char N))
  18275. (delete-char N)
  18276. (org-fix-tags-on-the-fly))))
  18277. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18278. (put 'org-self-insert-command 'delete-selection
  18279. (lambda ()
  18280. (not (run-hook-with-args-until-success
  18281. 'self-insert-uses-region-functions))))
  18282. (put 'orgtbl-self-insert-command 'delete-selection
  18283. (lambda ()
  18284. (not (run-hook-with-args-until-success
  18285. 'self-insert-uses-region-functions))))
  18286. (put 'org-delete-char 'delete-selection 'supersede)
  18287. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18288. (put 'org-yank 'delete-selection 'yank)
  18289. ;; Make `flyspell-mode' delay after some commands
  18290. (put 'org-self-insert-command 'flyspell-delayed t)
  18291. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18292. (put 'org-delete-char 'flyspell-delayed t)
  18293. (put 'org-delete-backward-char 'flyspell-delayed t)
  18294. ;; Make pabbrev-mode expand after Org mode commands
  18295. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18296. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18297. (defun org-remap (map &rest commands)
  18298. "In MAP, remap the functions given in COMMANDS.
  18299. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18300. (let (new old)
  18301. (while commands
  18302. (setq old (pop commands) new (pop commands))
  18303. (org-defkey map (vector 'remap old) new))))
  18304. (defun org-transpose-words ()
  18305. "Transpose words for Org.
  18306. This uses the `org-mode-transpose-word-syntax-table' syntax
  18307. table, which interprets characters in `org-emphasis-alist' as
  18308. word constituents."
  18309. (interactive)
  18310. (with-syntax-table org-mode-transpose-word-syntax-table
  18311. (call-interactively 'transpose-words)))
  18312. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18313. (when (eq org-enable-table-editor 'optimized)
  18314. ;; If the user wants maximum table support, we need to hijack
  18315. ;; some standard editing functions
  18316. (org-remap org-mode-map
  18317. 'self-insert-command 'org-self-insert-command
  18318. 'delete-char 'org-delete-char
  18319. 'delete-backward-char 'org-delete-backward-char)
  18320. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18321. (defvar org-ctrl-c-ctrl-c-hook nil
  18322. "Hook for functions attaching themselves to `C-c C-c'.
  18323. This can be used to add additional functionality to the C-c C-c
  18324. key which executes context-dependent commands. This hook is run
  18325. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18326. run after the last test.
  18327. Each function will be called with no arguments. The function
  18328. must check if the context is appropriate for it to act. If yes,
  18329. it should do its thing and then return a non-nil value. If the
  18330. context is wrong, just do nothing and return nil.")
  18331. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18332. "Hook for functions attaching themselves to `C-c C-c'.
  18333. This can be used to add additional functionality to the C-c C-c
  18334. key which executes context-dependent commands. This hook is run
  18335. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18336. before the first test.
  18337. Each function will be called with no arguments. The function
  18338. must check if the context is appropriate for it to act. If yes,
  18339. it should do its thing and then return a non-nil value. If the
  18340. context is wrong, just do nothing and return nil.")
  18341. (defvar org-tab-first-hook nil
  18342. "Hook for functions to attach themselves to TAB.
  18343. See `org-ctrl-c-ctrl-c-hook' for more information.
  18344. This hook runs as the first action when TAB is pressed, even before
  18345. `org-cycle' messes around with the `outline-regexp' to cater for
  18346. inline tasks and plain list item folding.
  18347. If any function in this hook returns t, any other actions that
  18348. would have been caused by TAB (such as table field motion or visibility
  18349. cycling) will not occur.")
  18350. (defvar org-tab-after-check-for-table-hook nil
  18351. "Hook for functions to attach themselves to TAB.
  18352. See `org-ctrl-c-ctrl-c-hook' for more information.
  18353. This hook runs after it has been established that the cursor is not in a
  18354. table, but before checking if the cursor is in a headline or if global cycling
  18355. should be done.
  18356. If any function in this hook returns t, not other actions like visibility
  18357. cycling will be done.")
  18358. (defvar org-tab-after-check-for-cycling-hook nil
  18359. "Hook for functions to attach themselves to TAB.
  18360. See `org-ctrl-c-ctrl-c-hook' for more information.
  18361. This hook runs after it has been established that not table field motion and
  18362. not visibility should be done because of current context. This is probably
  18363. the place where a package like yasnippets can hook in.")
  18364. (defvar org-tab-before-tab-emulation-hook nil
  18365. "Hook for functions to attach themselves to TAB.
  18366. See `org-ctrl-c-ctrl-c-hook' for more information.
  18367. This hook runs after every other options for TAB have been exhausted, but
  18368. before indentation and \t insertion takes place.")
  18369. (defvar org-metaleft-hook nil
  18370. "Hook for functions attaching themselves to `M-left'.
  18371. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18372. (defvar org-metaright-hook nil
  18373. "Hook for functions attaching themselves to `M-right'.
  18374. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18375. (defvar org-metaup-hook nil
  18376. "Hook for functions attaching themselves to `M-up'.
  18377. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18378. (defvar org-metadown-hook nil
  18379. "Hook for functions attaching themselves to `M-down'.
  18380. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18381. (defvar org-shiftmetaleft-hook nil
  18382. "Hook for functions attaching themselves to `M-S-left'.
  18383. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18384. (defvar org-shiftmetaright-hook nil
  18385. "Hook for functions attaching themselves to `M-S-right'.
  18386. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18387. (defvar org-shiftmetaup-hook nil
  18388. "Hook for functions attaching themselves to `M-S-up'.
  18389. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18390. (defvar org-shiftmetadown-hook nil
  18391. "Hook for functions attaching themselves to `M-S-down'.
  18392. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18393. (defvar org-metareturn-hook nil
  18394. "Hook for functions attaching themselves to `M-RET'.
  18395. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18396. (defvar org-shiftup-hook nil
  18397. "Hook for functions attaching themselves to `S-up'.
  18398. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18399. (defvar org-shiftup-final-hook nil
  18400. "Hook for functions attaching themselves to `S-up'.
  18401. This one runs after all other options except shift-select have been excluded.
  18402. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18403. (defvar org-shiftdown-hook nil
  18404. "Hook for functions attaching themselves to `S-down'.
  18405. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18406. (defvar org-shiftdown-final-hook nil
  18407. "Hook for functions attaching themselves to `S-down'.
  18408. This one runs after all other options except shift-select have been excluded.
  18409. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18410. (defvar org-shiftleft-hook nil
  18411. "Hook for functions attaching themselves to `S-left'.
  18412. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18413. (defvar org-shiftleft-final-hook nil
  18414. "Hook for functions attaching themselves to `S-left'.
  18415. This one runs after all other options except shift-select have been excluded.
  18416. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18417. (defvar org-shiftright-hook nil
  18418. "Hook for functions attaching themselves to `S-right'.
  18419. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18420. (defvar org-shiftright-final-hook nil
  18421. "Hook for functions attaching themselves to `S-right'.
  18422. This one runs after all other options except shift-select have been excluded.
  18423. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18424. (defun org-modifier-cursor-error ()
  18425. "Throw an error, a modified cursor command was applied in wrong context."
  18426. (user-error "This command is active in special context like tables, headlines or items"))
  18427. (defun org-shiftselect-error ()
  18428. "Throw an error because Shift-Cursor command was applied in wrong context."
  18429. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18430. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18431. (user-error "This command works only in special context like headlines or timestamps")))
  18432. (defun org-call-for-shift-select (cmd)
  18433. (let ((this-command-keys-shift-translated t))
  18434. (call-interactively cmd)))
  18435. (defun org-shifttab (&optional arg)
  18436. "Global visibility cycling or move to previous table field.
  18437. Call `org-table-previous-field' within a table.
  18438. When ARG is nil, cycle globally through visibility states.
  18439. When ARG is a numeric prefix, show contents of this level."
  18440. (interactive "P")
  18441. (cond
  18442. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18443. ((integerp arg)
  18444. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18445. (message "Content view to level: %d" arg)
  18446. (org-content (prefix-numeric-value arg2))
  18447. (org-cycle-show-empty-lines t)
  18448. (setq org-cycle-global-status 'overview)))
  18449. (t (call-interactively 'org-global-cycle))))
  18450. (defun org-shiftmetaleft ()
  18451. "Promote subtree or delete table column.
  18452. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18453. `org-table-delete-column', depending on context. See the
  18454. individual commands for more information."
  18455. (interactive)
  18456. (cond
  18457. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18458. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18459. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18460. ((if (not (org-region-active-p)) (org-at-item-p)
  18461. (save-excursion (goto-char (region-beginning))
  18462. (org-at-item-p)))
  18463. (call-interactively 'org-outdent-item-tree))
  18464. (t (org-modifier-cursor-error))))
  18465. (defun org-shiftmetaright ()
  18466. "Demote subtree or insert table column.
  18467. Calls `org-demote-subtree', `org-indent-item-tree', or
  18468. `org-table-insert-column', depending on context. See the
  18469. individual commands for more information."
  18470. (interactive)
  18471. (cond
  18472. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18473. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18474. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18475. ((if (not (org-region-active-p)) (org-at-item-p)
  18476. (save-excursion (goto-char (region-beginning))
  18477. (org-at-item-p)))
  18478. (call-interactively 'org-indent-item-tree))
  18479. (t (org-modifier-cursor-error))))
  18480. (defun org-shiftmetaup (&optional _arg)
  18481. "Drag the line at point up.
  18482. In a table, kill the current row.
  18483. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18484. but also adjust the previous clocked item in the clock history.
  18485. Everywhere else, drag the line at point up."
  18486. (interactive "P")
  18487. (cond
  18488. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18489. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18490. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18491. (call-interactively 'org-timestamp-up)))
  18492. (t (call-interactively 'org-drag-line-backward))))
  18493. (defun org-shiftmetadown (&optional _arg)
  18494. "Drag the line at point down.
  18495. In a table, insert an empty row at the current line.
  18496. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18497. but also adjust the previous clocked item in the clock history.
  18498. Everywhere else, drag the line at point down."
  18499. (interactive "P")
  18500. (cond
  18501. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18502. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18503. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18504. (call-interactively 'org-timestamp-down)))
  18505. (t (call-interactively 'org-drag-line-forward))))
  18506. (defsubst org-hidden-tree-error ()
  18507. (user-error
  18508. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18509. (defun org-metaleft (&optional _arg)
  18510. "Promote heading, list item at point or move table column left.
  18511. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18512. depending on context. With no specific context, calls the Emacs
  18513. default `backward-word'. See the individual commands for more
  18514. information.
  18515. This function runs the hook `org-metaleft-hook' as a first step,
  18516. and returns at first non-nil value."
  18517. (interactive "P")
  18518. (cond
  18519. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18520. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18521. ((org-with-limited-levels
  18522. (or (org-at-heading-p)
  18523. (and (org-region-active-p)
  18524. (save-excursion
  18525. (goto-char (region-beginning))
  18526. (org-at-heading-p)))))
  18527. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18528. (call-interactively 'org-do-promote))
  18529. ;; At an inline task.
  18530. ((org-at-heading-p)
  18531. (call-interactively 'org-inlinetask-promote))
  18532. ((or (org-at-item-p)
  18533. (and (org-region-active-p)
  18534. (save-excursion
  18535. (goto-char (region-beginning))
  18536. (org-at-item-p))))
  18537. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18538. (call-interactively 'org-outdent-item))
  18539. (t (call-interactively 'backward-word))))
  18540. (defun org-metaright (&optional _arg)
  18541. "Demote heading, list item at point or move table column right.
  18542. In front of a drawer or a block keyword, indent it correctly.
  18543. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18544. `org-indent-drawer' or `org-indent-block' depending on context.
  18545. With no specific context, calls the Emacs default `forward-word'.
  18546. See the individual commands for more information.
  18547. This function runs the hook `org-metaright-hook' as a first step,
  18548. and returns at first non-nil value."
  18549. (interactive "P")
  18550. (cond
  18551. ((run-hook-with-args-until-success 'org-metaright-hook))
  18552. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18553. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18554. ((org-at-block-p) (call-interactively 'org-indent-block))
  18555. ((org-with-limited-levels
  18556. (or (org-at-heading-p)
  18557. (and (org-region-active-p)
  18558. (save-excursion
  18559. (goto-char (region-beginning))
  18560. (org-at-heading-p)))))
  18561. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18562. (call-interactively 'org-do-demote))
  18563. ;; At an inline task.
  18564. ((org-at-heading-p)
  18565. (call-interactively 'org-inlinetask-demote))
  18566. ((or (org-at-item-p)
  18567. (and (org-region-active-p)
  18568. (save-excursion
  18569. (goto-char (region-beginning))
  18570. (org-at-item-p))))
  18571. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18572. (call-interactively 'org-indent-item))
  18573. (t (call-interactively 'forward-word))))
  18574. (defun org-check-for-hidden (what)
  18575. "Check if there are hidden headlines/items in the current visual line.
  18576. WHAT can be either `headlines' or `items'. If the current line is
  18577. an outline or item heading and it has a folded subtree below it,
  18578. this function returns t, nil otherwise."
  18579. (let ((re (cond
  18580. ((eq what 'headlines) org-outline-regexp-bol)
  18581. ((eq what 'items) (org-item-beginning-re))
  18582. (t (error "This should not happen"))))
  18583. beg end)
  18584. (save-excursion
  18585. (catch 'exit
  18586. (unless (org-region-active-p)
  18587. (setq beg (point-at-bol))
  18588. (beginning-of-line 2)
  18589. (while (and (not (eobp)) ;; this is like `next-line'
  18590. (get-char-property (1- (point)) 'invisible))
  18591. (beginning-of-line 2))
  18592. (setq end (point))
  18593. (goto-char beg)
  18594. (goto-char (point-at-eol))
  18595. (setq end (max end (point)))
  18596. (while (re-search-forward re end t)
  18597. (when (get-char-property (match-beginning 0) 'invisible)
  18598. (throw 'exit t))))
  18599. nil))))
  18600. (defun org-metaup (&optional _arg)
  18601. "Move subtree up or move table row up.
  18602. Calls `org-move-subtree-up' or `org-table-move-row' or
  18603. `org-move-item-up', depending on context. See the individual commands
  18604. for more information."
  18605. (interactive "P")
  18606. (cond
  18607. ((run-hook-with-args-until-success 'org-metaup-hook))
  18608. ((org-region-active-p)
  18609. (let* ((a (min (region-beginning) (region-end)))
  18610. (b (1- (max (region-beginning) (region-end))))
  18611. (c (save-excursion (goto-char a)
  18612. (move-beginning-of-line 0)))
  18613. (d (save-excursion (goto-char a)
  18614. (move-end-of-line 0) (point))))
  18615. (transpose-regions a b c d)
  18616. (goto-char c)))
  18617. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18618. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18619. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18620. (t (org-drag-element-backward))))
  18621. (defun org-metadown (&optional _arg)
  18622. "Move subtree down or move table row down.
  18623. Calls `org-move-subtree-down' or `org-table-move-row' or
  18624. `org-move-item-down', depending on context. See the individual
  18625. commands for more information."
  18626. (interactive "P")
  18627. (cond
  18628. ((run-hook-with-args-until-success 'org-metadown-hook))
  18629. ((org-region-active-p)
  18630. (let* ((a (min (region-beginning) (region-end)))
  18631. (b (max (region-beginning) (region-end)))
  18632. (c (save-excursion (goto-char b)
  18633. (move-beginning-of-line 1)))
  18634. (d (save-excursion (goto-char b)
  18635. (move-end-of-line 1) (1+ (point)))))
  18636. (transpose-regions a b c d)
  18637. (goto-char d)))
  18638. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18639. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18640. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18641. (t (org-drag-element-forward))))
  18642. (defun org-shiftup (&optional arg)
  18643. "Increase item in timestamp or increase priority of current headline.
  18644. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18645. depending on context. See the individual commands for more information."
  18646. (interactive "P")
  18647. (cond
  18648. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18649. ((and org-support-shift-select (org-region-active-p))
  18650. (org-call-for-shift-select 'previous-line))
  18651. ((org-at-timestamp-p 'lax)
  18652. (call-interactively (if org-edit-timestamp-down-means-later
  18653. 'org-timestamp-down 'org-timestamp-up)))
  18654. ((and (not (eq org-support-shift-select 'always))
  18655. org-enable-priority-commands
  18656. (org-at-heading-p))
  18657. (call-interactively 'org-priority-up))
  18658. ((and (not org-support-shift-select) (org-at-item-p))
  18659. (call-interactively 'org-previous-item))
  18660. ((org-clocktable-try-shift 'up arg))
  18661. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18662. (org-support-shift-select
  18663. (org-call-for-shift-select 'previous-line))
  18664. (t (org-shiftselect-error))))
  18665. (defun org-shiftdown (&optional arg)
  18666. "Decrease item in timestamp or decrease priority of current headline.
  18667. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18668. depending on context. See the individual commands for more information."
  18669. (interactive "P")
  18670. (cond
  18671. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18672. ((and org-support-shift-select (org-region-active-p))
  18673. (org-call-for-shift-select 'next-line))
  18674. ((org-at-timestamp-p 'lax)
  18675. (call-interactively (if org-edit-timestamp-down-means-later
  18676. 'org-timestamp-up 'org-timestamp-down)))
  18677. ((and (not (eq org-support-shift-select 'always))
  18678. org-enable-priority-commands
  18679. (org-at-heading-p))
  18680. (call-interactively 'org-priority-down))
  18681. ((and (not org-support-shift-select) (org-at-item-p))
  18682. (call-interactively 'org-next-item))
  18683. ((org-clocktable-try-shift 'down arg))
  18684. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18685. (org-support-shift-select
  18686. (org-call-for-shift-select 'next-line))
  18687. (t (org-shiftselect-error))))
  18688. (defun org-shiftright (&optional arg)
  18689. "Cycle the thing at point or in the current line, depending on context.
  18690. Depending on context, this does one of the following:
  18691. - switch a timestamp at point one day into the future
  18692. - on a headline, switch to the next TODO keyword.
  18693. - on an item, switch entire list to the next bullet type
  18694. - on a property line, switch to the next allowed value
  18695. - on a clocktable definition line, move time block into the future"
  18696. (interactive "P")
  18697. (cond
  18698. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18699. ((and org-support-shift-select (org-region-active-p))
  18700. (org-call-for-shift-select 'forward-char))
  18701. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  18702. ((and (not (eq org-support-shift-select 'always))
  18703. (org-at-heading-p))
  18704. (let ((org-inhibit-logging
  18705. (not org-treat-S-cursor-todo-selection-as-state-change))
  18706. (org-inhibit-blocking
  18707. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18708. (org-call-with-arg 'org-todo 'right)))
  18709. ((or (and org-support-shift-select
  18710. (not (eq org-support-shift-select 'always))
  18711. (org-at-item-bullet-p))
  18712. (and (not org-support-shift-select) (org-at-item-p)))
  18713. (org-call-with-arg 'org-cycle-list-bullet nil))
  18714. ((and (not (eq org-support-shift-select 'always))
  18715. (org-at-property-p))
  18716. (call-interactively 'org-property-next-allowed-value))
  18717. ((org-clocktable-try-shift 'right arg))
  18718. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18719. (org-support-shift-select
  18720. (org-call-for-shift-select 'forward-char))
  18721. (t (org-shiftselect-error))))
  18722. (defun org-shiftleft (&optional arg)
  18723. "Cycle the thing at point or in the current line, depending on context.
  18724. Depending on context, this does one of the following:
  18725. - switch a timestamp at point one day into the past
  18726. - on a headline, switch to the previous TODO keyword.
  18727. - on an item, switch entire list to the previous bullet type
  18728. - on a property line, switch to the previous allowed value
  18729. - on a clocktable definition line, move time block into the past"
  18730. (interactive "P")
  18731. (cond
  18732. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18733. ((and org-support-shift-select (org-region-active-p))
  18734. (org-call-for-shift-select 'backward-char))
  18735. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  18736. ((and (not (eq org-support-shift-select 'always))
  18737. (org-at-heading-p))
  18738. (let ((org-inhibit-logging
  18739. (not org-treat-S-cursor-todo-selection-as-state-change))
  18740. (org-inhibit-blocking
  18741. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18742. (org-call-with-arg 'org-todo 'left)))
  18743. ((or (and org-support-shift-select
  18744. (not (eq org-support-shift-select 'always))
  18745. (org-at-item-bullet-p))
  18746. (and (not org-support-shift-select) (org-at-item-p)))
  18747. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  18748. ((and (not (eq org-support-shift-select 'always))
  18749. (org-at-property-p))
  18750. (call-interactively 'org-property-previous-allowed-value))
  18751. ((org-clocktable-try-shift 'left arg))
  18752. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  18753. (org-support-shift-select
  18754. (org-call-for-shift-select 'backward-char))
  18755. (t (org-shiftselect-error))))
  18756. (defun org-shiftcontrolright ()
  18757. "Switch to next TODO set."
  18758. (interactive)
  18759. (cond
  18760. ((and org-support-shift-select (org-region-active-p))
  18761. (org-call-for-shift-select 'forward-word))
  18762. ((and (not (eq org-support-shift-select 'always))
  18763. (org-at-heading-p))
  18764. (org-call-with-arg 'org-todo 'nextset))
  18765. (org-support-shift-select
  18766. (org-call-for-shift-select 'forward-word))
  18767. (t (org-shiftselect-error))))
  18768. (defun org-shiftcontrolleft ()
  18769. "Switch to previous TODO set."
  18770. (interactive)
  18771. (cond
  18772. ((and org-support-shift-select (org-region-active-p))
  18773. (org-call-for-shift-select 'backward-word))
  18774. ((and (not (eq org-support-shift-select 'always))
  18775. (org-at-heading-p))
  18776. (org-call-with-arg 'org-todo 'previousset))
  18777. (org-support-shift-select
  18778. (org-call-for-shift-select 'backward-word))
  18779. (t (org-shiftselect-error))))
  18780. (defun org-shiftcontrolup (&optional n)
  18781. "Change timestamps synchronously up in CLOCK log lines.
  18782. Optional argument N tells to change by that many units."
  18783. (interactive "P")
  18784. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18785. (let (org-support-shift-select)
  18786. (org-clock-timestamps-up n))
  18787. (user-error "Not at a clock log")))
  18788. (defun org-shiftcontroldown (&optional n)
  18789. "Change timestamps synchronously down in CLOCK log lines.
  18790. Optional argument N tells to change by that many units."
  18791. (interactive "P")
  18792. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  18793. (let (org-support-shift-select)
  18794. (org-clock-timestamps-down n))
  18795. (user-error "Not at a clock log")))
  18796. (defun org-increase-number-at-point (&optional inc)
  18797. "Increment the number at point.
  18798. With an optional prefix numeric argument INC, increment using
  18799. this numeric value."
  18800. (interactive "p")
  18801. (if (not (number-at-point))
  18802. (user-error "Not on a number")
  18803. (unless inc (setq inc 1))
  18804. (let ((pos (point))
  18805. (beg (skip-chars-backward "-+^/*0-9eE."))
  18806. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  18807. (setq nap (buffer-substring-no-properties
  18808. (+ pos beg) (+ pos beg end)))
  18809. (delete-region (+ pos beg) (+ pos beg end))
  18810. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  18811. (when (org-at-table-p)
  18812. (org-table-align)
  18813. (org-table-end-of-field 1))))
  18814. (defun org-decrease-number-at-point (&optional inc)
  18815. "Decrement the number at point.
  18816. With an optional prefix numeric argument INC, decrement using
  18817. this numeric value."
  18818. (interactive "p")
  18819. (org-increase-number-at-point (- (or inc 1))))
  18820. (defun org-ctrl-c-ret ()
  18821. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  18822. (interactive)
  18823. (cond
  18824. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  18825. (t (call-interactively 'org-insert-heading))))
  18826. (defun org-find-visible ()
  18827. (let ((s (point)))
  18828. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18829. (get-char-property s 'invisible)))
  18830. s))
  18831. (defun org-find-invisible ()
  18832. (let ((s (point)))
  18833. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  18834. (not (get-char-property s 'invisible))))
  18835. s))
  18836. (defun org-copy-visible (beg end)
  18837. "Copy the visible parts of the region."
  18838. (interactive "r")
  18839. (let (snippets s)
  18840. (save-excursion
  18841. (save-restriction
  18842. (narrow-to-region beg end)
  18843. (setq s (goto-char (point-min)))
  18844. (while (not (= (point) (point-max)))
  18845. (goto-char (org-find-invisible))
  18846. (push (buffer-substring s (point)) snippets)
  18847. (setq s (goto-char (org-find-visible))))))
  18848. (kill-new (apply 'concat (nreverse snippets)))))
  18849. (defun org-copy-special ()
  18850. "Copy region in table or copy current subtree.
  18851. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  18852. context. See the individual commands for more information."
  18853. (interactive)
  18854. (call-interactively
  18855. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  18856. (defun org-cut-special ()
  18857. "Cut region in table or cut current subtree.
  18858. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  18859. context. See the individual commands for more information."
  18860. (interactive)
  18861. (call-interactively
  18862. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  18863. (defun org-paste-special (arg)
  18864. "Paste rectangular region into table, or past subtree relative to level.
  18865. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  18866. See the individual commands for more information."
  18867. (interactive "P")
  18868. (if (org-at-table-p)
  18869. (org-table-paste-rectangle)
  18870. (org-paste-subtree arg)))
  18871. (defun org-edit-special (&optional arg)
  18872. "Call a special editor for the element at point.
  18873. When at a table, call the formula editor with `org-table-edit-formulas'.
  18874. When in a source code block, call `org-edit-src-code'.
  18875. When in a fixed-width region, call `org-edit-fixed-width-region'.
  18876. When in an export block, call `org-edit-export-block'.
  18877. When in a LaTeX environment, call `org-edit-latex-environment'.
  18878. When at an #+INCLUDE keyword, visit the included file.
  18879. When at a footnote reference, call `org-edit-footnote-reference'
  18880. On a link, call `ffap' to visit the link at point.
  18881. Otherwise, return a user error."
  18882. (interactive "P")
  18883. (let ((element (org-element-at-point)))
  18884. (barf-if-buffer-read-only)
  18885. (pcase (org-element-type element)
  18886. (`src-block
  18887. (if (not arg) (org-edit-src-code)
  18888. (let* ((info (org-babel-get-src-block-info))
  18889. (lang (nth 0 info))
  18890. (params (nth 2 info))
  18891. (session (cdr (assq :session params))))
  18892. (if (not session) (org-edit-src-code)
  18893. ;; At a src-block with a session and function called with
  18894. ;; an ARG: switch to the buffer related to the inferior
  18895. ;; process.
  18896. (switch-to-buffer
  18897. (funcall (intern (concat "org-babel-prep-session:" lang))
  18898. session params))))))
  18899. (`keyword
  18900. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  18901. (org-open-link-from-string
  18902. (format "[[%s]]"
  18903. (expand-file-name
  18904. (let ((value (org-element-property :value element)))
  18905. (cond ((not (org-string-nw-p value))
  18906. (user-error "No file to edit"))
  18907. ((string-match "\\`\"\\(.*?\\)\"" value)
  18908. (match-string 1 value))
  18909. ((string-match "\\`[^ \t\"]\\S-*" value)
  18910. (match-string 0 value))
  18911. (t (user-error "No valid file specified")))))))
  18912. (user-error "No special environment to edit here")))
  18913. (`table
  18914. (if (eq (org-element-property :type element) 'table.el)
  18915. (org-edit-table.el)
  18916. (call-interactively 'org-table-edit-formulas)))
  18917. ;; Only Org tables contain `table-row' type elements.
  18918. (`table-row (call-interactively 'org-table-edit-formulas))
  18919. (`example-block (org-edit-src-code))
  18920. (`export-block (org-edit-export-block))
  18921. (`fixed-width (org-edit-fixed-width-region))
  18922. (`latex-environment (org-edit-latex-environment))
  18923. (_
  18924. ;; No notable element at point. Though, we may be at a link or
  18925. ;; a footnote reference, which are objects. Thus, scan deeper.
  18926. (let ((context (org-element-context element)))
  18927. (pcase (org-element-type context)
  18928. (`footnote-reference (org-edit-footnote-reference))
  18929. (`inline-src-block (org-edit-inline-src-code))
  18930. (`link (call-interactively #'ffap))
  18931. (_ (user-error "No special environment to edit here"))))))))
  18932. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  18933. (defun org-ctrl-c-ctrl-c (&optional arg)
  18934. "Set tags in headline, or update according to changed information at point.
  18935. This command does many different things, depending on context:
  18936. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  18937. this is what we do.
  18938. - If the cursor is on a statistics cookie, update it.
  18939. - If the cursor is in a headline, prompt for tags and insert them
  18940. into the current line, aligned to `org-tags-column'. When called
  18941. with prefix arg, realign all tags in the current buffer.
  18942. - If the cursor is in one of the special #+KEYWORD lines, this
  18943. triggers scanning the buffer for these lines and updating the
  18944. information.
  18945. - If the cursor is inside a table, realign the table. This command
  18946. works even if the automatic table editor has been turned off.
  18947. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  18948. the entire table.
  18949. - If the cursor is at a footnote reference or definition, jump to
  18950. the corresponding definition or references, respectively.
  18951. - If the cursor is a the beginning of a dynamic block, update it.
  18952. - If the current buffer is a capture buffer, close note and file it.
  18953. - If the cursor is on a <<<target>>>, update radio targets and
  18954. corresponding links in this buffer.
  18955. - If the cursor is on a numbered item in a plain list, renumber the
  18956. ordered list.
  18957. - If the cursor is on a checkbox, toggle it.
  18958. - If the cursor is on a code block, evaluate it. The variable
  18959. `org-confirm-babel-evaluate' can be used to control prompting
  18960. before code block evaluation, by default every code block
  18961. evaluation requires confirmation. Code block evaluation can be
  18962. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  18963. (interactive "P")
  18964. (cond
  18965. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  18966. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  18967. (org-remove-occur-highlights)
  18968. (message "Temporary highlights/overlays removed from current buffer"))
  18969. ((and (local-variable-p 'org-finish-function)
  18970. (fboundp org-finish-function))
  18971. (funcall org-finish-function))
  18972. ((org-babel-hash-at-point))
  18973. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  18974. (t
  18975. (let* ((context
  18976. (org-element-lineage
  18977. (org-element-context)
  18978. ;; Limit to supported contexts.
  18979. '(babel-call clock dynamic-block footnote-definition
  18980. footnote-reference inline-babel-call inline-src-block
  18981. inlinetask item keyword node-property paragraph
  18982. plain-list property-drawer radio-target src-block
  18983. statistics-cookie table table-cell table-row
  18984. timestamp)
  18985. t))
  18986. (type (org-element-type context)))
  18987. ;; For convenience: at the first line of a paragraph on the same
  18988. ;; line as an item, apply function on that item instead.
  18989. (when (eq type 'paragraph)
  18990. (let ((parent (org-element-property :parent context)))
  18991. (when (and (eq (org-element-type parent) 'item)
  18992. (= (line-beginning-position)
  18993. (org-element-property :begin parent)))
  18994. (setq context parent)
  18995. (setq type 'item))))
  18996. ;; Act according to type of element or object at point.
  18997. ;;
  18998. ;; Do nothing on a blank line, except if it is contained in
  18999. ;; a src block. Hence, we first check if point is in such
  19000. ;; a block and then if it is at a blank line.
  19001. (pcase type
  19002. ((or `inline-src-block `src-block)
  19003. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19004. (org-babel-eval-wipe-error-buffer)
  19005. (org-babel-execute-src-block
  19006. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19007. ((guard (org-match-line "[ \t]*$"))
  19008. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19009. (user-error
  19010. (substitute-command-keys
  19011. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19012. ((or `babel-call `inline-babel-call)
  19013. (let ((info (org-babel-lob-get-info context)))
  19014. (when info (org-babel-execute-src-block nil info))))
  19015. (`clock (org-clock-update-time-maybe))
  19016. (`dynamic-block
  19017. (save-excursion
  19018. (goto-char (org-element-property :post-affiliated context))
  19019. (org-update-dblock)))
  19020. (`footnote-definition
  19021. (goto-char (org-element-property :post-affiliated context))
  19022. (call-interactively 'org-footnote-action))
  19023. (`footnote-reference (call-interactively #'org-footnote-action))
  19024. ((or `headline `inlinetask)
  19025. (save-excursion (goto-char (org-element-property :begin context))
  19026. (call-interactively #'org-set-tags)))
  19027. (`item
  19028. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19029. ;; unconditionally, whereas `C-u' will toggle its presence.
  19030. ;; Without a universal argument, if the item has a checkbox,
  19031. ;; toggle it. Otherwise repair the list.
  19032. (let* ((box (org-element-property :checkbox context))
  19033. (struct (org-element-property :structure context))
  19034. (old-struct (copy-tree struct))
  19035. (parents (org-list-parents-alist struct))
  19036. (prevs (org-list-prevs-alist struct))
  19037. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19038. (org-list-set-checkbox
  19039. (org-element-property :begin context) struct
  19040. (cond ((equal arg '(16)) "[-]")
  19041. ((and (not box) (equal arg '(4))) "[ ]")
  19042. ((or (not box) (equal arg '(4))) nil)
  19043. ((eq box 'on) "[ ]")
  19044. (t "[X]")))
  19045. ;; Mimic `org-list-write-struct' but with grabbing a return
  19046. ;; value from `org-list-struct-fix-box'.
  19047. (org-list-struct-fix-ind struct parents 2)
  19048. (org-list-struct-fix-item-end struct)
  19049. (org-list-struct-fix-bul struct prevs)
  19050. (org-list-struct-fix-ind struct parents)
  19051. (let ((block-item
  19052. (org-list-struct-fix-box struct parents prevs orderedp)))
  19053. (if (and box (equal struct old-struct))
  19054. (if (equal arg '(16))
  19055. (message "Checkboxes already reset")
  19056. (user-error "Cannot toggle this checkbox: %s"
  19057. (if (eq box 'on)
  19058. "all subitems checked"
  19059. "unchecked subitems")))
  19060. (org-list-struct-apply-struct struct old-struct)
  19061. (org-update-checkbox-count-maybe))
  19062. (when block-item
  19063. (message "Checkboxes were removed due to empty box at line %d"
  19064. (org-current-line block-item))))))
  19065. (`keyword
  19066. (let ((org-inhibit-startup-visibility-stuff t)
  19067. (org-startup-align-all-tables nil))
  19068. (when (boundp 'org-table-coordinate-overlays)
  19069. (mapc #'delete-overlay org-table-coordinate-overlays)
  19070. (setq org-table-coordinate-overlays nil))
  19071. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19072. (message "Local setup has been refreshed"))
  19073. (`plain-list
  19074. ;; At a plain list, with a double C-u argument, set
  19075. ;; checkboxes of each item to "[-]", whereas a single one
  19076. ;; will toggle their presence according to the state of the
  19077. ;; first item in the list. Without an argument, repair the
  19078. ;; list.
  19079. (let* ((begin (org-element-property :contents-begin context))
  19080. (beginm (move-marker (make-marker) begin))
  19081. (struct (org-element-property :structure context))
  19082. (old-struct (copy-tree struct))
  19083. (first-box (save-excursion
  19084. (goto-char begin)
  19085. (looking-at org-list-full-item-re)
  19086. (match-string-no-properties 3)))
  19087. (new-box (cond ((equal arg '(16)) "[-]")
  19088. ((equal arg '(4)) (unless first-box "[ ]"))
  19089. ((equal first-box "[X]") "[ ]")
  19090. (t "[X]"))))
  19091. (cond
  19092. (arg
  19093. (dolist (pos
  19094. (org-list-get-all-items
  19095. begin struct (org-list-prevs-alist struct)))
  19096. (org-list-set-checkbox pos struct new-box)))
  19097. ((and first-box (eq (point) begin))
  19098. ;; For convenience, when point is at bol on the first
  19099. ;; item of the list and no argument is provided, simply
  19100. ;; toggle checkbox of that item, if any.
  19101. (org-list-set-checkbox begin struct new-box)))
  19102. (org-list-write-struct
  19103. struct (org-list-parents-alist struct) old-struct)
  19104. (org-update-checkbox-count-maybe)
  19105. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19106. ((or `property-drawer `node-property)
  19107. (call-interactively #'org-property-action))
  19108. (`radio-target
  19109. (call-interactively #'org-update-radio-target-regexp))
  19110. (`statistics-cookie
  19111. (call-interactively #'org-update-statistics-cookies))
  19112. ((or `table `table-cell `table-row)
  19113. ;; At a table, recalculate every field and align it. Also
  19114. ;; send the table if necessary. If the table has
  19115. ;; a `table.el' type, just give up. At a table row or cell,
  19116. ;; maybe recalculate line but always align table.
  19117. (if (eq (org-element-property :type context) 'table.el)
  19118. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19119. Use `\\[org-edit-special]' to edit table.el tables"))
  19120. (let ((org-enable-table-editor t))
  19121. (if (or (eq type 'table)
  19122. ;; Check if point is at a TBLFM line.
  19123. (and (eq type 'table-row)
  19124. (= (point) (org-element-property :end context))))
  19125. (save-excursion
  19126. (if (org-at-TBLFM-p)
  19127. (progn (require 'org-table)
  19128. (org-table-calc-current-TBLFM))
  19129. (goto-char (org-element-property :contents-begin context))
  19130. (org-call-with-arg 'org-table-recalculate (or arg t))
  19131. (orgtbl-send-table 'maybe)))
  19132. (org-table-maybe-eval-formula)
  19133. (cond (arg (call-interactively #'org-table-recalculate))
  19134. ((org-table-maybe-recalculate-line))
  19135. (t (org-table-align)))))))
  19136. (`timestamp (org-timestamp-change 0 'day))
  19137. ((and `nil (guard (org-at-heading-p)))
  19138. ;; When point is on an unsupported object type, we can miss
  19139. ;; the fact that it also is at a heading. Handle it here.
  19140. (call-interactively #'org-set-tags))
  19141. ((guard
  19142. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19143. (_
  19144. (user-error
  19145. (substitute-command-keys
  19146. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19147. (defun org-mode-restart ()
  19148. (interactive)
  19149. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19150. (funcall major-mode)
  19151. (hack-local-variables)
  19152. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19153. (org-indent-mode -1)))
  19154. (message "%s restarted" major-mode))
  19155. (defun org-kill-note-or-show-branches ()
  19156. "Abort storing current note, or call `outline-show-branches'."
  19157. (interactive)
  19158. (if (not org-finish-function)
  19159. (progn
  19160. (outline-hide-subtree)
  19161. (call-interactively 'outline-show-branches))
  19162. (let ((org-note-abort t))
  19163. (funcall org-finish-function))))
  19164. (defun org-delete-indentation (&optional arg)
  19165. "Join current line to previous and fix whitespace at join.
  19166. If previous line is a headline add to headline title. Otherwise
  19167. the function calls `delete-indentation'.
  19168. With a non-nil optional argument, join it to the following one."
  19169. (interactive "*P")
  19170. (if (save-excursion
  19171. (beginning-of-line (if arg 1 0))
  19172. (let ((case-fold-search nil))
  19173. (looking-at org-complex-heading-regexp)))
  19174. ;; At headline.
  19175. (let ((tags-column (when (match-beginning 5)
  19176. (save-excursion (goto-char (match-beginning 5))
  19177. (current-column))))
  19178. (string (concat " " (progn (when arg (forward-line 1))
  19179. (org-trim (delete-and-extract-region
  19180. (line-beginning-position)
  19181. (line-end-position)))))))
  19182. (unless (bobp) (delete-region (point) (1- (point))))
  19183. (goto-char (or (match-end 4)
  19184. (match-beginning 5)
  19185. (match-end 0)))
  19186. (skip-chars-backward " \t")
  19187. (save-excursion (insert string))
  19188. ;; Adjust alignment of tags.
  19189. (cond
  19190. ((not tags-column)) ;no tags
  19191. (org-auto-align-tags (org-set-tags nil t))
  19192. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19193. (delete-indentation arg)))
  19194. (defun org-open-line (n)
  19195. "Insert a new row in tables, call `open-line' elsewhere.
  19196. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19197. As a special case, when a document starts with a table, allow to
  19198. call `open-line' on the very first character."
  19199. (interactive "*p")
  19200. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19201. (org-table-insert-row)
  19202. (open-line n)))
  19203. (defun org-return (&optional indent)
  19204. "Goto next table row or insert a newline.
  19205. Calls `org-table-next-row' or `newline', depending on context.
  19206. When optional INDENT argument is non-nil, call
  19207. `newline-and-indent' instead of `newline'.
  19208. When `org-return-follows-link' is non-nil and point is on
  19209. a timestamp or a link, call `org-open-at-point'. However, it
  19210. will not happen if point is in a table or on a \"dead\"
  19211. object (e.g., within a comment). In these case, you need to use
  19212. `org-open-at-point' directly."
  19213. (interactive)
  19214. (let ((context (if org-return-follows-link (org-element-context)
  19215. (org-element-at-point))))
  19216. (cond
  19217. ;; In a table, call `org-table-next-row'.
  19218. ((or (and (eq (org-element-type context) 'table)
  19219. (>= (point) (org-element-property :contents-begin context))
  19220. (< (point) (org-element-property :contents-end context)))
  19221. (org-element-lineage context '(table-row table-cell) t))
  19222. (org-table-justify-field-maybe)
  19223. (call-interactively #'org-table-next-row))
  19224. ;; On a link or a timestamp, call `org-open-at-point' if
  19225. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19226. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19227. ((and org-return-follows-link
  19228. (or (org-in-regexp org-ts-regexp-both nil t)
  19229. (org-in-regexp org-tsr-regexp-both nil t)
  19230. (org-in-regexp org-any-link-re nil t)))
  19231. (call-interactively #'org-open-at-point))
  19232. ;; Insert newline in heading, but preserve tags.
  19233. ((and (not (bolp))
  19234. (save-excursion (beginning-of-line)
  19235. (let ((case-fold-search nil))
  19236. (looking-at org-complex-heading-regexp))))
  19237. ;; At headline. Split line. However, if point is on keyword,
  19238. ;; priority cookie or tags, do not break any of them: add
  19239. ;; a newline after the headline instead.
  19240. (let ((tags-column (and (match-beginning 5)
  19241. (save-excursion (goto-char (match-beginning 5))
  19242. (current-column))))
  19243. (string
  19244. (when (and (match-end 4) (org-point-in-group (point) 4))
  19245. (delete-and-extract-region (point) (match-end 4)))))
  19246. ;; Adjust tag alignment.
  19247. (cond
  19248. ((not (and tags-column string)))
  19249. (org-auto-align-tags (org-set-tags nil t))
  19250. (t (org--align-tags-here tags-column))) ;preserve tags column
  19251. (end-of-line)
  19252. (org-show-entry)
  19253. (if indent (newline-and-indent) (newline))
  19254. (when string (save-excursion (insert (org-trim string))))))
  19255. ;; In a list, make sure indenting keeps trailing text within.
  19256. ((and indent
  19257. (not (eolp))
  19258. (org-element-lineage context '(item)))
  19259. (let ((trailing-data
  19260. (delete-and-extract-region (point) (line-end-position))))
  19261. (newline-and-indent)
  19262. (save-excursion (insert trailing-data))))
  19263. (t (if indent (newline-and-indent) (newline))))))
  19264. (defun org-return-indent ()
  19265. "Goto next table row or insert a newline and indent.
  19266. Calls `org-table-next-row' or `newline-and-indent', depending on
  19267. context. See the individual commands for more information."
  19268. (interactive)
  19269. (org-return t))
  19270. (defun org-ctrl-c-star ()
  19271. "Compute table, or change heading status of lines.
  19272. Calls `org-table-recalculate' or `org-toggle-heading',
  19273. depending on context."
  19274. (interactive)
  19275. (cond
  19276. ((org-at-table-p)
  19277. (call-interactively 'org-table-recalculate))
  19278. (t
  19279. ;; Convert all lines in region to list items
  19280. (call-interactively 'org-toggle-heading))))
  19281. (defun org-ctrl-c-minus ()
  19282. "Insert separator line in table or modify bullet status of line.
  19283. Also turns a plain line or a region of lines into list items.
  19284. Calls `org-table-insert-hline', `org-toggle-item', or
  19285. `org-cycle-list-bullet', depending on context."
  19286. (interactive)
  19287. (cond
  19288. ((org-at-table-p)
  19289. (call-interactively 'org-table-insert-hline))
  19290. ((org-region-active-p)
  19291. (call-interactively 'org-toggle-item))
  19292. ((org-in-item-p)
  19293. (call-interactively 'org-cycle-list-bullet))
  19294. (t
  19295. (call-interactively 'org-toggle-item))))
  19296. (defun org-toggle-heading (&optional nstars)
  19297. "Convert headings to normal text, or items or text to headings.
  19298. If there is no active region, only convert the current line.
  19299. With a `\\[universal-argument]' prefix, convert the whole list at
  19300. point into heading.
  19301. In a region:
  19302. - If the first non blank line is a headline, remove the stars
  19303. from all headlines in the region.
  19304. - If it is a normal line, turn each and every normal line (i.e.,
  19305. not an heading or an item) in the region into headings. If you
  19306. want to convert only the first line of this region, use one
  19307. universal prefix argument.
  19308. - If it is a plain list item, turn all plain list items into headings.
  19309. When converting a line into a heading, the number of stars is chosen
  19310. such that the lines become children of the current entry. However,
  19311. when a numeric prefix argument is given, its value determines the
  19312. number of stars to add."
  19313. (interactive "P")
  19314. (let ((skip-blanks
  19315. (function
  19316. ;; Return beginning of first non-blank line, starting from
  19317. ;; line at POS.
  19318. (lambda (pos)
  19319. (save-excursion
  19320. (goto-char pos)
  19321. (while (org-at-comment-p) (forward-line))
  19322. (skip-chars-forward " \r\t\n")
  19323. (point-at-bol)))))
  19324. beg end toggled)
  19325. ;; Determine boundaries of changes. If a universal prefix has
  19326. ;; been given, put the list in a region. If region ends at a bol,
  19327. ;; do not consider the last line to be in the region.
  19328. (when (and current-prefix-arg (org-at-item-p))
  19329. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19330. (org-mark-element))
  19331. (if (org-region-active-p)
  19332. (setq beg (funcall skip-blanks (region-beginning))
  19333. end (copy-marker (save-excursion
  19334. (goto-char (region-end))
  19335. (if (bolp) (point) (point-at-eol)))))
  19336. (setq beg (funcall skip-blanks (point-at-bol))
  19337. end (copy-marker (point-at-eol))))
  19338. ;; Ensure inline tasks don't count as headings.
  19339. (org-with-limited-levels
  19340. (save-excursion
  19341. (goto-char beg)
  19342. (cond
  19343. ;; Case 1. Started at an heading: de-star headings.
  19344. ((org-at-heading-p)
  19345. (while (< (point) end)
  19346. (when (org-at-heading-p t)
  19347. (looking-at org-outline-regexp) (replace-match "")
  19348. (setq toggled t))
  19349. (forward-line)))
  19350. ;; Case 2. Started at an item: change items into headlines.
  19351. ;; One star will be added by `org-list-to-subtree'.
  19352. ((org-at-item-p)
  19353. (while (< (point) end)
  19354. (when (org-at-item-p)
  19355. ;; Pay attention to cases when region ends before list.
  19356. (let* ((struct (org-list-struct))
  19357. (list-end
  19358. (min (org-list-get-bottom-point struct) (1+ end))))
  19359. (save-restriction
  19360. (narrow-to-region (point) list-end)
  19361. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19362. (setq toggled t))
  19363. (forward-line)))
  19364. ;; Case 3. Started at normal text: make every line an heading,
  19365. ;; skipping headlines and items.
  19366. (t (let* ((stars
  19367. (make-string
  19368. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19369. (add-stars
  19370. (cond (nstars "") ; stars from prefix only
  19371. ((equal stars "") "*") ; before first heading
  19372. (org-odd-levels-only "**") ; inside heading, odd
  19373. (t "*"))) ; inside heading, oddeven
  19374. (rpl (concat stars add-stars " "))
  19375. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19376. (while (< (point) (if (equal nstars '(4)) lend end))
  19377. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19378. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19379. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19380. (forward-line)))))))
  19381. (unless toggled (message "Cannot toggle heading from here"))))
  19382. (defun org-meta-return (&optional arg)
  19383. "Insert a new heading or wrap a region in a table.
  19384. Calls `org-insert-heading', `org-insert-item' or
  19385. `org-table-wrap-region', depending on context. When called with
  19386. an argument, unconditionally call `org-insert-heading'."
  19387. (interactive "P")
  19388. (org-check-before-invisible-edit 'insert)
  19389. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19390. (call-interactively (cond (arg #'org-insert-heading)
  19391. ((org-at-table-p) #'org-table-wrap-region)
  19392. ((org-in-item-p) #'org-insert-item)
  19393. (t #'org-insert-heading)))))
  19394. ;;; Menu entries
  19395. (defsubst org-in-subtree-not-table-p ()
  19396. "Are we in a subtree and not in a table?"
  19397. (and (not (org-before-first-heading-p))
  19398. (not (org-at-table-p))))
  19399. ;; Define the Org mode menus
  19400. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19401. '("Tbl"
  19402. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19403. ["Next Field" org-cycle (org-at-table-p)]
  19404. ["Previous Field" org-shifttab (org-at-table-p)]
  19405. ["Next Row" org-return (org-at-table-p)]
  19406. "--"
  19407. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19408. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19409. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19410. "--"
  19411. ("Column"
  19412. ["Move Column Left" org-metaleft (org-at-table-p)]
  19413. ["Move Column Right" org-metaright (org-at-table-p)]
  19414. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19415. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19416. ("Row"
  19417. ["Move Row Up" org-metaup (org-at-table-p)]
  19418. ["Move Row Down" org-metadown (org-at-table-p)]
  19419. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19420. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19421. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19422. "--"
  19423. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19424. ("Rectangle"
  19425. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19426. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19427. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19428. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19429. "--"
  19430. ("Calculate"
  19431. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19432. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19433. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19434. "--"
  19435. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19436. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19437. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19438. "--"
  19439. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19440. "--"
  19441. ["Sum Column/Rectangle" org-table-sum
  19442. (or (org-at-table-p) (org-region-active-p))]
  19443. ["Which Column?" org-table-current-column (org-at-table-p)])
  19444. ["Debug Formulas"
  19445. org-table-toggle-formula-debugger
  19446. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19447. ["Show Col/Row Numbers"
  19448. org-table-toggle-coordinate-overlays
  19449. :style toggle
  19450. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19451. "--"
  19452. ["Create" org-table-create (and (not (org-at-table-p))
  19453. org-enable-table-editor)]
  19454. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19455. ["Import from File" org-table-import (not (org-at-table-p))]
  19456. ["Export to File" org-table-export (org-at-table-p)]
  19457. "--"
  19458. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19459. "--"
  19460. ("Plot"
  19461. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19462. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19463. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19464. '("Org"
  19465. ("Show/Hide"
  19466. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19467. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19468. ["Sparse Tree..." org-sparse-tree t]
  19469. ["Reveal Context" org-reveal t]
  19470. ["Show All" outline-show-all t]
  19471. "--"
  19472. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19473. "--"
  19474. ["New Heading" org-insert-heading t]
  19475. ("Navigate Headings"
  19476. ["Up" outline-up-heading t]
  19477. ["Next" outline-next-visible-heading t]
  19478. ["Previous" outline-previous-visible-heading t]
  19479. ["Next Same Level" outline-forward-same-level t]
  19480. ["Previous Same Level" outline-backward-same-level t]
  19481. "--"
  19482. ["Jump" org-goto t])
  19483. ("Edit Structure"
  19484. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19485. "--"
  19486. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19487. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19488. "--"
  19489. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19490. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19491. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19492. "--"
  19493. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19494. "--"
  19495. ["Copy visible text" org-copy-visible t]
  19496. "--"
  19497. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19498. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19499. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19500. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19501. "--"
  19502. ["Sort Region/Children" org-sort t]
  19503. "--"
  19504. ["Convert to odd levels" org-convert-to-odd-levels t]
  19505. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19506. ("Editing"
  19507. ["Emphasis..." org-emphasize t]
  19508. ["Edit Source Example" org-edit-special t]
  19509. "--"
  19510. ["Footnote new/jump" org-footnote-action t]
  19511. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19512. ("Archive"
  19513. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19514. "--"
  19515. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19516. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19517. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19518. )
  19519. "--"
  19520. ("Hyperlinks"
  19521. ["Store Link (Global)" org-store-link t]
  19522. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19523. ["Insert Link" org-insert-link t]
  19524. ["Follow Link" org-open-at-point t]
  19525. "--"
  19526. ["Next link" org-next-link t]
  19527. ["Previous link" org-previous-link t]
  19528. "--"
  19529. ["Descriptive Links"
  19530. org-toggle-link-display
  19531. :style radio
  19532. :selected org-descriptive-links
  19533. ]
  19534. ["Literal Links"
  19535. org-toggle-link-display
  19536. :style radio
  19537. :selected (not org-descriptive-links)])
  19538. "--"
  19539. ("TODO Lists"
  19540. ["TODO/DONE/-" org-todo t]
  19541. ("Select keyword"
  19542. ["Next keyword" org-shiftright (org-at-heading-p)]
  19543. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19544. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19545. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19546. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19547. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19548. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19549. "--"
  19550. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19551. :selected org-enforce-todo-dependencies :style toggle :active t]
  19552. "Settings for tree at point"
  19553. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19554. :selected (org-entry-get nil "ORDERED")
  19555. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19556. ["Do Children parallel" org-toggle-ordered-property :style radio
  19557. :selected (not (org-entry-get nil "ORDERED"))
  19558. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19559. "--"
  19560. ["Set Priority" org-priority t]
  19561. ["Priority Up" org-shiftup t]
  19562. ["Priority Down" org-shiftdown t]
  19563. "--"
  19564. ["Get news from all feeds" org-feed-update-all t]
  19565. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19566. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19567. ("TAGS and Properties"
  19568. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19569. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19570. "--"
  19571. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19572. ["Column view of properties" org-columns t]
  19573. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19574. ("Dates and Scheduling"
  19575. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19576. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19577. ("Change Date"
  19578. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  19579. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  19580. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  19581. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  19582. ["Compute Time Range" org-evaluate-time-range t]
  19583. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19584. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19585. "--"
  19586. ["Custom time format" org-toggle-time-stamp-overlays
  19587. :style radio :selected org-display-custom-times]
  19588. "--"
  19589. ["Goto Calendar" org-goto-calendar t]
  19590. ["Date from Calendar" org-date-from-calendar t]
  19591. "--"
  19592. ["Start/Restart Timer" org-timer-start t]
  19593. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19594. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19595. ["Insert Timer String" org-timer t]
  19596. ["Insert Timer Item" org-timer-item t])
  19597. ("Logging work"
  19598. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19599. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19600. ["Clock out" org-clock-out t]
  19601. ["Clock cancel" org-clock-cancel t]
  19602. "--"
  19603. ["Mark as default task" org-clock-mark-default-task t]
  19604. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19605. ["Goto running clock" org-clock-goto t]
  19606. "--"
  19607. ["Display times" org-clock-display t]
  19608. ["Create clock table" org-clock-report t]
  19609. "--"
  19610. ["Record DONE time"
  19611. (progn (setq org-log-done (not org-log-done))
  19612. (message "Switching to %s will %s record a timestamp"
  19613. (car org-done-keywords)
  19614. (if org-log-done "automatically" "not")))
  19615. :style toggle :selected org-log-done])
  19616. "--"
  19617. ["Agenda Command..." org-agenda t]
  19618. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19619. ("File List for Agenda")
  19620. ("Special views current file"
  19621. ["TODO Tree" org-show-todo-tree t]
  19622. ["Check Deadlines" org-check-deadlines t]
  19623. ["Tags/Property tree" org-match-sparse-tree t])
  19624. "--"
  19625. ["Export/Publish..." org-export-dispatch t]
  19626. ("LaTeX"
  19627. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19628. :selected org-cdlatex-mode]
  19629. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19630. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19631. ["Modify math symbol" org-cdlatex-math-modify
  19632. (org-inside-LaTeX-fragment-p)]
  19633. ["Insert citation" org-reftex-citation t])
  19634. "--"
  19635. ("MobileOrg"
  19636. ["Push Files and Views" org-mobile-push t]
  19637. ["Get Captured and Flagged" org-mobile-pull t]
  19638. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19639. "--"
  19640. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19641. "--"
  19642. ("Documentation"
  19643. ["Show Version" org-version t]
  19644. ["Info Documentation" org-info t])
  19645. ("Customize"
  19646. ["Browse Org Group" org-customize t]
  19647. "--"
  19648. ["Expand This Menu" org-create-customize-menu
  19649. (fboundp 'customize-menu-create)])
  19650. ["Send bug report" org-submit-bug-report t]
  19651. "--"
  19652. ("Refresh/Reload"
  19653. ["Refresh setup current buffer" org-mode-restart t]
  19654. ["Reload Org (after update)" org-reload t]
  19655. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19656. ))
  19657. (defun org-info (&optional node)
  19658. "Read documentation for Org in the info system.
  19659. With optional NODE, go directly to that node."
  19660. (interactive)
  19661. (info (format "(org)%s" (or node ""))))
  19662. ;;;###autoload
  19663. (defun org-submit-bug-report ()
  19664. "Submit a bug report on Org via mail.
  19665. Don't hesitate to report any problems or inaccurate documentation.
  19666. If you don't have setup sending mail from (X)Emacs, please copy the
  19667. output buffer into your mail program, as it gives us important
  19668. information about your Org version and configuration."
  19669. (interactive)
  19670. (require 'reporter)
  19671. (defvar reporter-prompt-for-summary-p)
  19672. (org-load-modules-maybe)
  19673. (org-require-autoloaded-modules)
  19674. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19675. (reporter-submit-bug-report
  19676. "emacs-orgmode@gnu.org"
  19677. (org-version nil 'full)
  19678. (let (list)
  19679. (save-window-excursion
  19680. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19681. (delete-other-windows)
  19682. (erase-buffer)
  19683. (insert "You are about to submit a bug report to the Org mailing list.
  19684. We would like to add your full Org and Outline configuration to the
  19685. bug report. This greatly simplifies the work of the maintainer and
  19686. other experts on the mailing list.
  19687. HOWEVER, some variables you have customized may contain private
  19688. information. The names of customers, colleagues, or friends, might
  19689. appear in the form of file names, tags, todo states, or search strings.
  19690. If you answer yes to the prompt, you might want to check and remove
  19691. such private information before sending the email.")
  19692. (add-text-properties (point-min) (point-max) '(face org-warning))
  19693. (when (yes-or-no-p "Include your Org configuration ")
  19694. (mapatoms
  19695. (lambda (v)
  19696. (and (boundp v)
  19697. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19698. (or (and (symbol-value v)
  19699. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19700. (and
  19701. (get v 'custom-type) (get v 'standard-value)
  19702. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19703. (push v list)))))
  19704. (kill-buffer (get-buffer "*Warn about privacy*"))
  19705. list))
  19706. nil nil
  19707. "Remember to cover the basics, that is, what you expected to happen and
  19708. what in fact did happen. You don't know how to make a good report? See
  19709. http://orgmode.org/manual/Feedback.html#Feedback
  19710. Your bug report will be posted to the Org mailing list.
  19711. ------------------------------------------------------------------------")
  19712. (save-excursion
  19713. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19714. (replace-match "\\1Bug: \\3 [\\2]")))))
  19715. (defun org-install-agenda-files-menu ()
  19716. (let ((bl (buffer-list)))
  19717. (save-excursion
  19718. (while bl
  19719. (set-buffer (pop bl))
  19720. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19721. (when (derived-mode-p 'org-mode)
  19722. (easy-menu-change
  19723. '("Org") "File List for Agenda"
  19724. (append
  19725. (list
  19726. ["Edit File List" (org-edit-agenda-file-list) t]
  19727. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19728. ["Remove Current File from List" org-remove-file t]
  19729. ["Cycle through agenda files" org-cycle-agenda-files t]
  19730. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19731. "--")
  19732. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19733. ;;;; Documentation
  19734. (defun org-require-autoloaded-modules ()
  19735. (interactive)
  19736. (mapc #'require
  19737. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19738. org-table org-timer)))
  19739. ;;;###autoload
  19740. (defun org-reload (&optional uncompiled)
  19741. "Reload all org lisp files.
  19742. With prefix arg UNCOMPILED, load the uncompiled versions."
  19743. (interactive "P")
  19744. (require 'loadhist)
  19745. (let* ((org-dir (org-find-library-dir "org"))
  19746. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  19747. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  19748. (remove-re (format "\\`%s\\'"
  19749. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  19750. (feats (delete-dups
  19751. (mapcar 'file-name-sans-extension
  19752. (mapcar 'file-name-nondirectory
  19753. (delq nil
  19754. (mapcar 'feature-file
  19755. features))))))
  19756. (lfeat (append
  19757. (sort
  19758. (setq feats
  19759. (delq nil (mapcar
  19760. (lambda (f)
  19761. (if (and (string-match feature-re f)
  19762. (not (string-match remove-re f)))
  19763. f nil))
  19764. feats)))
  19765. 'string-lessp)
  19766. (list "org-version" "org")))
  19767. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  19768. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  19769. load-uncore load-misses)
  19770. (setq load-misses
  19771. (delq 't
  19772. (mapcar (lambda (f)
  19773. (or (org-load-noerror-mustsuffix (concat org-dir f))
  19774. (and (string= org-dir contrib-dir)
  19775. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  19776. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  19777. (add-to-list 'load-uncore f 'append)
  19778. 't)
  19779. f))
  19780. lfeat)))
  19781. (when load-uncore
  19782. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  19783. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  19784. (if load-misses
  19785. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  19786. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  19787. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  19788. ;;;###autoload
  19789. (defun org-customize ()
  19790. "Call the customize function with org as argument."
  19791. (interactive)
  19792. (org-load-modules-maybe)
  19793. (org-require-autoloaded-modules)
  19794. (customize-browse 'org))
  19795. (defun org-create-customize-menu ()
  19796. "Create a full customization menu for Org mode, insert it into the menu."
  19797. (interactive)
  19798. (org-load-modules-maybe)
  19799. (org-require-autoloaded-modules)
  19800. (if (fboundp 'customize-menu-create)
  19801. (progn
  19802. (easy-menu-change
  19803. '("Org") "Customize"
  19804. `(["Browse Org group" org-customize t]
  19805. "--"
  19806. ,(customize-menu-create 'org)
  19807. ["Set" Custom-set t]
  19808. ["Save" Custom-save t]
  19809. ["Reset to Current" Custom-reset-current t]
  19810. ["Reset to Saved" Custom-reset-saved t]
  19811. ["Reset to Standard Settings" Custom-reset-standard t]))
  19812. (message "\"Org\"-menu now contains full customization menu"))
  19813. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  19814. ;;;; Miscellaneous stuff
  19815. ;;; Generally useful functions
  19816. (defun org-get-at-eol (property n)
  19817. "Get text property PROPERTY at the end of line less N characters."
  19818. (get-text-property (- (point-at-eol) n) property))
  19819. (defun org-find-text-property-in-string (prop s)
  19820. "Return the first non-nil value of property PROP in string S."
  19821. (or (get-text-property 0 prop s)
  19822. (get-text-property (or (next-single-property-change 0 prop s) 0)
  19823. prop s)))
  19824. (defun org-display-warning (message)
  19825. "Display the given MESSAGE as a warning."
  19826. (display-warning 'org message :warning))
  19827. (defun org-eval (form)
  19828. "Eval FORM and return result."
  19829. (condition-case error
  19830. (eval form)
  19831. (error (format "%%![Error: %s]" error))))
  19832. (defun org-in-clocktable-p ()
  19833. "Check if the cursor is in a clocktable."
  19834. (let ((pos (point)) start)
  19835. (save-excursion
  19836. (end-of-line 1)
  19837. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  19838. (setq start (match-beginning 0))
  19839. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  19840. (>= (match-end 0) pos)
  19841. start))))
  19842. (defun org-in-verbatim-emphasis ()
  19843. (save-match-data
  19844. (and (org-in-regexp org-verbatim-re 2)
  19845. (>= (point) (match-beginning 3))
  19846. (<= (point) (match-end 4)))))
  19847. (defun org-overlay-display (ovl text &optional face evap)
  19848. "Make overlay OVL display TEXT with face FACE."
  19849. (overlay-put ovl 'display text)
  19850. (if face (overlay-put ovl 'face face))
  19851. (if evap (overlay-put ovl 'evaporate t)))
  19852. (defun org-overlay-before-string (ovl text &optional face evap)
  19853. "Make overlay OVL display TEXT with face FACE."
  19854. (if face (org-add-props text nil 'face face))
  19855. (overlay-put ovl 'before-string text)
  19856. (if evap (overlay-put ovl 'evaporate t)))
  19857. (defun org-find-overlays (prop &optional pos delete)
  19858. "Find all overlays specifying PROP at POS or point.
  19859. If DELETE is non-nil, delete all those overlays."
  19860. (let (found)
  19861. (dolist (ov (overlays-at (or pos (point))) found)
  19862. (cond ((not (overlay-get ov prop)))
  19863. (delete (delete-overlay ov))
  19864. (t (push ov found))))))
  19865. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  19866. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  19867. (if (and marker (marker-buffer marker)
  19868. (buffer-live-p (marker-buffer marker)))
  19869. (progn
  19870. (pop-to-buffer-same-window (marker-buffer marker))
  19871. (when (or (> marker (point-max)) (< marker (point-min)))
  19872. (widen))
  19873. (goto-char marker)
  19874. (org-show-context 'org-goto))
  19875. (if bookmark
  19876. (bookmark-jump bookmark)
  19877. (error "Cannot find location"))))
  19878. (defun org-quote-csv-field (s)
  19879. "Quote field for inclusion in CSV material."
  19880. (if (string-match "[\",]" s)
  19881. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  19882. s))
  19883. (defun org-force-self-insert (N)
  19884. "Needed to enforce self-insert under remapping."
  19885. (interactive "p")
  19886. (self-insert-command N))
  19887. (defun org-string-width (s)
  19888. "Compute width of string, ignoring invisible characters.
  19889. This ignores character with invisibility property `org-link', and also
  19890. characters with property `org-cwidth', because these will become invisible
  19891. upon the next fontification round."
  19892. (let (b l)
  19893. (when (or (eq t buffer-invisibility-spec)
  19894. (assq 'org-link buffer-invisibility-spec))
  19895. (while (setq b (text-property-any 0 (length s)
  19896. 'invisible 'org-link s))
  19897. (setq s (concat (substring s 0 b)
  19898. (substring s (or (next-single-property-change
  19899. b 'invisible s)
  19900. (length s)))))))
  19901. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  19902. (setq s (concat (substring s 0 b)
  19903. (substring s (or (next-single-property-change
  19904. b 'org-cwidth s)
  19905. (length s))))))
  19906. (setq l (string-width s) b -1)
  19907. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  19908. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  19909. l))
  19910. (defun org-shorten-string (s maxlength)
  19911. "Shorten string S so that it is no longer than MAXLENGTH characters.
  19912. If the string is shorter or has length MAXLENGTH, just return the
  19913. original string. If it is longer, the functions finds a space in the
  19914. string, breaks this string off at that locations and adds three dots
  19915. as ellipsis. Including the ellipsis, the string will not be longer
  19916. than MAXLENGTH. If finding a good breaking point in the string does
  19917. not work, the string is just chopped off in the middle of a word
  19918. if necessary."
  19919. (if (<= (length s) maxlength)
  19920. s
  19921. (let* ((n (max (- maxlength 4) 1))
  19922. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  19923. (if (string-match re s)
  19924. (concat (match-string 1 s) "...")
  19925. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  19926. (defun org-get-indentation (&optional line)
  19927. "Get the indentation of the current line, interpreting tabs.
  19928. When LINE is given, assume it represents a line and compute its indentation."
  19929. (if line
  19930. (when (string-match "^ *" (org-remove-tabs line))
  19931. (match-end 0))
  19932. (save-excursion
  19933. (beginning-of-line 1)
  19934. (skip-chars-forward " \t")
  19935. (current-column))))
  19936. (defun org-get-string-indentation (s)
  19937. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  19938. (let ((n -1) (i 0) (w tab-width) c)
  19939. (catch 'exit
  19940. (while (< (setq n (1+ n)) (length s))
  19941. (setq c (aref s n))
  19942. (cond ((= c ?\ ) (setq i (1+ i)))
  19943. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  19944. (t (throw 'exit t)))))
  19945. i))
  19946. (defun org-remove-tabs (s &optional width)
  19947. "Replace tabulators in S with spaces.
  19948. Assumes that s is a single line, starting in column 0."
  19949. (setq width (or width tab-width))
  19950. (while (string-match "\t" s)
  19951. (setq s (replace-match
  19952. (make-string
  19953. (- (* width (/ (+ (match-beginning 0) width) width))
  19954. (match-beginning 0)) ?\ )
  19955. t t s)))
  19956. s)
  19957. (defun org-fix-indentation (line ind)
  19958. "Fix indentation in LINE.
  19959. IND is a cons cell with target and minimum indentation.
  19960. If the current indentation in LINE is smaller than the minimum,
  19961. leave it alone. If it is larger than ind, set it to the target."
  19962. (let* ((l (org-remove-tabs line))
  19963. (i (org-get-indentation l))
  19964. (i1 (car ind)) (i2 (cdr ind)))
  19965. (when (>= i i2) (setq l (substring line i2)))
  19966. (if (> i1 0)
  19967. (concat (make-string i1 ?\ ) l)
  19968. l)))
  19969. (defun org-remove-indentation (code &optional n)
  19970. "Remove maximum common indentation in string CODE and return it.
  19971. N may optionally be the number of columns to remove. Return CODE
  19972. as-is if removal failed."
  19973. (with-temp-buffer
  19974. (insert code)
  19975. (if (org-do-remove-indentation n) (buffer-string) code)))
  19976. (defun org-do-remove-indentation (&optional n)
  19977. "Remove the maximum common indentation from the buffer.
  19978. When optional argument N is a positive integer, remove exactly
  19979. that much characters from indentation, if possible. Return nil
  19980. if it fails."
  19981. (catch :exit
  19982. (goto-char (point-min))
  19983. ;; Find maximum common indentation, if not specified.
  19984. (let ((n (or n
  19985. (let ((min-ind (point-max)))
  19986. (save-excursion
  19987. (while (re-search-forward "^[ \t]*\\S-" nil t)
  19988. (let ((ind (1- (current-column))))
  19989. (if (zerop ind) (throw :exit nil)
  19990. (setq min-ind (min min-ind ind))))))
  19991. min-ind))))
  19992. (if (zerop n) (throw :exit nil)
  19993. ;; Remove exactly N indentation, but give up if not possible.
  19994. (while (not (eobp))
  19995. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  19996. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  19997. ((< ind n) (throw :exit nil))
  19998. (t (indent-line-to (- ind n))))
  19999. (forward-line)))
  20000. ;; Signal success.
  20001. t))))
  20002. (defun org-fill-template (template alist)
  20003. "Find each %key of ALIST in TEMPLATE and replace it."
  20004. (let ((case-fold-search nil))
  20005. (dolist (entry (sort (copy-sequence alist)
  20006. (lambda (a b) (< (length (car a)) (length (car b))))))
  20007. (setq template
  20008. (replace-regexp-in-string
  20009. (concat "%" (regexp-quote (car entry)))
  20010. (or (cdr entry) "") template t t)))
  20011. template))
  20012. (defun org-base-buffer (buffer)
  20013. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20014. (if (not buffer)
  20015. buffer
  20016. (or (buffer-base-buffer buffer)
  20017. buffer)))
  20018. (defun org-wrap (string &optional width lines)
  20019. "Wrap string to either a number of lines, or a width in characters.
  20020. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20021. that costs. If there is a word longer than WIDTH, the text is actually
  20022. wrapped to the length of that word.
  20023. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20024. many lines, whatever width that takes.
  20025. The return value is a list of lines, without newlines at the end."
  20026. (let* ((words (org-split-string string "[ \t\n]+"))
  20027. (maxword (apply 'max (mapcar 'org-string-width words)))
  20028. w ll)
  20029. (cond (width
  20030. (org-do-wrap words (max maxword width)))
  20031. (lines
  20032. (setq w maxword)
  20033. (setq ll (org-do-wrap words maxword))
  20034. (if (<= (length ll) lines)
  20035. ll
  20036. (setq ll words)
  20037. (while (> (length ll) lines)
  20038. (setq w (1+ w))
  20039. (setq ll (org-do-wrap words w)))
  20040. ll))
  20041. (t (error "Cannot wrap this")))))
  20042. (defun org-do-wrap (words width)
  20043. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20044. (let (lines line)
  20045. (while words
  20046. (setq line (pop words))
  20047. (while (and words (< (+ (length line) (length (car words))) width))
  20048. (setq line (concat line " " (pop words))))
  20049. (setq lines (push line lines)))
  20050. (nreverse lines)))
  20051. (defun org-split-string (string &optional separators)
  20052. "Splits STRING into substrings at SEPARATORS.
  20053. SEPARATORS is a regular expression.
  20054. No empty strings are returned if there are matches at the beginning
  20055. and end of string."
  20056. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20057. (let ((start 0) notfirst list)
  20058. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20059. (if (and notfirst
  20060. (= start (match-beginning 0))
  20061. (< start (length string)))
  20062. (1+ start) start))
  20063. (< (match-beginning 0) (length string)))
  20064. (setq notfirst t)
  20065. (or (eq (match-beginning 0) 0)
  20066. (and (eq (match-beginning 0) (match-end 0))
  20067. (eq (match-beginning 0) start))
  20068. (push (substring string start (match-beginning 0)) list))
  20069. (setq start (match-end 0)))
  20070. (or (eq start (length string))
  20071. (push (substring string start) list))
  20072. (nreverse list)))
  20073. (defun org-quote-vert (s)
  20074. "Replace \"|\" with \"\\vert\"."
  20075. (while (string-match "|" s)
  20076. (setq s (replace-match "\\vert" t t s)))
  20077. s)
  20078. (defun org-uuidgen-p (s)
  20079. "Is S an ID created by UUIDGEN?"
  20080. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20081. (defun org-in-src-block-p (&optional inside)
  20082. "Whether point is in a code source block.
  20083. When INSIDE is non-nil, don't consider we are within a src block
  20084. when point is at #+BEGIN_SRC or #+END_SRC."
  20085. (let ((case-fold-search t))
  20086. (or (and (eq (get-char-property (point) 'src-block) t))
  20087. (and (not inside)
  20088. (save-match-data
  20089. (save-excursion
  20090. (beginning-of-line)
  20091. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20092. (defun org-context ()
  20093. "Return a list of contexts of the current cursor position.
  20094. If several contexts apply, all are returned.
  20095. Each context entry is a list with a symbol naming the context, and
  20096. two positions indicating start and end of the context. Possible
  20097. contexts are:
  20098. :headline anywhere in a headline
  20099. :headline-stars on the leading stars in a headline
  20100. :todo-keyword on a TODO keyword (including DONE) in a headline
  20101. :tags on the TAGS in a headline
  20102. :priority on the priority cookie in a headline
  20103. :item on the first line of a plain list item
  20104. :item-bullet on the bullet/number of a plain list item
  20105. :checkbox on the checkbox in a plain list item
  20106. :table in an Org table
  20107. :table-special on a special filed in a table
  20108. :table-table in a table.el table
  20109. :clocktable in a clocktable
  20110. :src-block in a source block
  20111. :link on a hyperlink
  20112. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20113. :target on a <<target>>
  20114. :radio-target on a <<<radio-target>>>
  20115. :latex-fragment on a LaTeX fragment
  20116. :latex-preview on a LaTeX fragment with overlaid preview image
  20117. This function expects the position to be visible because it uses font-lock
  20118. faces as a help to recognize the following contexts: :table-special, :link,
  20119. and :keyword."
  20120. (let* ((f (get-text-property (point) 'face))
  20121. (faces (if (listp f) f (list f)))
  20122. (case-fold-search t)
  20123. (p (point)) clist o)
  20124. ;; First the large context
  20125. (cond
  20126. ((org-at-heading-p t)
  20127. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20128. (when (progn
  20129. (beginning-of-line 1)
  20130. (looking-at org-todo-line-tags-regexp))
  20131. (push (org-point-in-group p 1 :headline-stars) clist)
  20132. (push (org-point-in-group p 2 :todo-keyword) clist)
  20133. (push (org-point-in-group p 4 :tags) clist))
  20134. (goto-char p)
  20135. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20136. (when (looking-at "\\[#[A-Z0-9]\\]")
  20137. (push (org-point-in-group p 0 :priority) clist)))
  20138. ((org-at-item-p)
  20139. (push (org-point-in-group p 2 :item-bullet) clist)
  20140. (push (list :item (point-at-bol)
  20141. (save-excursion (org-end-of-item) (point)))
  20142. clist)
  20143. (and (org-at-item-checkbox-p)
  20144. (push (org-point-in-group p 0 :checkbox) clist)))
  20145. ((org-at-table-p)
  20146. (push (list :table (org-table-begin) (org-table-end)) clist)
  20147. (when (memq 'org-formula faces)
  20148. (push (list :table-special
  20149. (previous-single-property-change p 'face)
  20150. (next-single-property-change p 'face)) clist)))
  20151. ((org-at-table-p 'any)
  20152. (push (list :table-table) clist)))
  20153. (goto-char p)
  20154. (let ((case-fold-search t))
  20155. ;; New the "medium" contexts: clocktables, source blocks
  20156. (cond ((org-in-clocktable-p)
  20157. (push (list :clocktable
  20158. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20159. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20160. (match-beginning 1))
  20161. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20162. (match-end 0))) clist))
  20163. ((org-in-src-block-p)
  20164. (push (list :src-block
  20165. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20166. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20167. (match-beginning 1))
  20168. (and (search-forward "#+END_SRC" nil t)
  20169. (match-beginning 0))) clist))))
  20170. (goto-char p)
  20171. ;; Now the small context
  20172. (cond
  20173. ((org-at-timestamp-p)
  20174. (push (org-point-in-group p 0 :timestamp) clist))
  20175. ((memq 'org-link faces)
  20176. (push (list :link
  20177. (previous-single-property-change p 'face)
  20178. (next-single-property-change p 'face)) clist))
  20179. ((memq 'org-special-keyword faces)
  20180. (push (list :keyword
  20181. (previous-single-property-change p 'face)
  20182. (next-single-property-change p 'face)) clist))
  20183. ((org-at-target-p)
  20184. (push (org-point-in-group p 0 :target) clist)
  20185. (goto-char (1- (match-beginning 0)))
  20186. (when (looking-at org-radio-target-regexp)
  20187. (push (org-point-in-group p 0 :radio-target) clist))
  20188. (goto-char p))
  20189. ((setq o (cl-some
  20190. (lambda (o)
  20191. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20192. o))
  20193. (overlays-at (point))))
  20194. (push (list :latex-fragment
  20195. (overlay-start o) (overlay-end o)) clist)
  20196. (push (list :latex-preview
  20197. (overlay-start o) (overlay-end o)) clist))
  20198. ((org-inside-LaTeX-fragment-p)
  20199. ;; FIXME: positions wrong.
  20200. (push (list :latex-fragment (point) (point)) clist)))
  20201. (setq clist (nreverse (delq nil clist)))
  20202. clist))
  20203. (defun org-in-regexp (regexp &optional nlines visually)
  20204. "Check if point is inside a match of REGEXP.
  20205. Normally only the current line is checked, but you can include
  20206. NLINES extra lines around point into the search. If VISUALLY is
  20207. set, require that the cursor is not after the match but really
  20208. on, so that the block visually is on the match.
  20209. Return nil or a cons cell (BEG . END) where BEG and END are,
  20210. respectively, the positions at the beginning and the end of the
  20211. match."
  20212. (catch :exit
  20213. (let ((pos (point))
  20214. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20215. (save-excursion
  20216. (beginning-of-line (- 1 (or nlines 0)))
  20217. (while (and (re-search-forward regexp eol t)
  20218. (<= (match-beginning 0) pos))
  20219. (let ((end (match-end 0)))
  20220. (when (or (> end pos) (and (= end pos) (not visually)))
  20221. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20222. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20223. "Non-nil when point is between matches of START-RE and END-RE.
  20224. Also return a non-nil value when point is on one of the matches.
  20225. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20226. buffer positions. Default values are the positions of headlines
  20227. surrounding the point.
  20228. The functions returns a cons cell whose car (resp. cdr) is the
  20229. position before START-RE (resp. after END-RE)."
  20230. (save-match-data
  20231. (let ((pos (point))
  20232. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20233. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20234. beg end)
  20235. (save-excursion
  20236. ;; Point is on a block when on START-RE or if START-RE can be
  20237. ;; found before it...
  20238. (and (or (org-in-regexp start-re)
  20239. (re-search-backward start-re limit-up t))
  20240. (setq beg (match-beginning 0))
  20241. ;; ... and END-RE after it...
  20242. (goto-char (match-end 0))
  20243. (re-search-forward end-re limit-down t)
  20244. (> (setq end (match-end 0)) pos)
  20245. ;; ... without another START-RE in-between.
  20246. (goto-char (match-beginning 0))
  20247. (not (re-search-backward start-re (1+ beg) t))
  20248. ;; Return value.
  20249. (cons beg end))))))
  20250. (defun org-in-block-p (names)
  20251. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20252. NAMES is a list of strings containing names of blocks.
  20253. Return first block name matched, or nil. Beware that in case of
  20254. nested blocks, the returned name may not belong to the closest
  20255. block from point."
  20256. (save-match-data
  20257. (catch 'exit
  20258. (let ((case-fold-search t)
  20259. (lim-up (save-excursion (outline-previous-heading)))
  20260. (lim-down (save-excursion (outline-next-heading))))
  20261. (dolist (name names)
  20262. (let ((n (regexp-quote name)))
  20263. (when (org-between-regexps-p
  20264. (concat "^[ \t]*#\\+begin_" n)
  20265. (concat "^[ \t]*#\\+end_" n)
  20266. lim-up lim-down)
  20267. (throw 'exit n)))))
  20268. nil)))
  20269. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20270. "Call `multi-occur' with buffers for all agenda files."
  20271. (interactive "sOrg-files matching: ")
  20272. (let* ((files (org-agenda-files))
  20273. (tnames (mapcar #'file-truename files))
  20274. (extra org-agenda-text-search-extra-files))
  20275. (when (eq (car extra) 'agenda-archives)
  20276. (setq extra (cdr extra))
  20277. (setq files (org-add-archive-files files)))
  20278. (dolist (f extra)
  20279. (unless (member (file-truename f) tnames)
  20280. (unless (member f files) (setq files (append files (list f))))
  20281. (setq tnames (append tnames (list (file-truename f))))))
  20282. (multi-occur
  20283. (mapcar (lambda (x)
  20284. (with-current-buffer
  20285. ;; FIXME: Why not just (find-file-noselect x)?
  20286. ;; Is it to avoid the "revert buffer" prompt?
  20287. (or (get-file-buffer x) (find-file-noselect x))
  20288. (widen)
  20289. (current-buffer)))
  20290. files)
  20291. regexp)))
  20292. (add-hook 'occur-mode-find-occurrence-hook
  20293. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20294. (defun org-occur-link-in-agenda-files ()
  20295. "Create a link and search for it in the agendas.
  20296. The link is not stored in `org-stored-links', it is just created
  20297. for the search purpose."
  20298. (interactive)
  20299. (let ((link (condition-case nil
  20300. (org-store-link nil)
  20301. (error "Unable to create a link to here"))))
  20302. (org-occur-in-agenda-files (regexp-quote link))))
  20303. (defun org-reverse-string (string)
  20304. "Return the reverse of STRING."
  20305. (apply 'string (reverse (string-to-list string))))
  20306. ;; defsubst org-uniquify must be defined before first use
  20307. (defun org-uniquify-alist (alist)
  20308. "Merge elements of ALIST with the same key.
  20309. For example, in this alist:
  20310. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20311. => \\='((a 1 3) (b 2))
  20312. merge (a 1) and (a 3) into (a 1 3).
  20313. The function returns the new ALIST."
  20314. (let (rtn)
  20315. (dolist (e alist rtn)
  20316. (let (n)
  20317. (if (not (assoc (car e) rtn))
  20318. (push e rtn)
  20319. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20320. (setq rtn (assq-delete-all (car e) rtn))
  20321. (push n rtn))))))
  20322. (defun org-delete-all (elts list)
  20323. "Remove all elements in ELTS from LIST.
  20324. Comparison is done with `equal'. It is a destructive operation
  20325. that may remove elements by altering the list structure."
  20326. (while elts
  20327. (setq list (delete (pop elts) list)))
  20328. list)
  20329. (defun org-back-over-empty-lines ()
  20330. "Move backwards over whitespace, to the beginning of the first empty line.
  20331. Returns the number of empty lines passed."
  20332. (let ((pos (point)))
  20333. (if (cdr (assq 'heading org-blank-before-new-entry))
  20334. (skip-chars-backward " \t\n\r")
  20335. (unless (eobp)
  20336. (forward-line -1)))
  20337. (beginning-of-line 2)
  20338. (goto-char (min (point) pos))
  20339. (count-lines (point) pos)))
  20340. (defun org-skip-whitespace ()
  20341. (skip-chars-forward " \t\n\r"))
  20342. (defun org-point-in-group (point group &optional context)
  20343. "Check if POINT is in match-group GROUP.
  20344. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20345. match. If the match group does not exist or point is not inside it,
  20346. return nil."
  20347. (and (match-beginning group)
  20348. (>= point (match-beginning group))
  20349. (<= point (match-end group))
  20350. (if context
  20351. (list context (match-beginning group) (match-end group))
  20352. t)))
  20353. (defun org-switch-to-buffer-other-window (&rest args)
  20354. "Switch to buffer in a second window on the current frame.
  20355. In particular, do not allow pop-up frames.
  20356. Returns the newly created buffer."
  20357. (org-no-popups
  20358. (apply 'switch-to-buffer-other-window args)))
  20359. (defun org-combine-plists (&rest plists)
  20360. "Create a single property list from all plists in PLISTS.
  20361. The process starts by copying the first list, and then setting properties
  20362. from the other lists. Settings in the last list are the most significant
  20363. ones and overrule settings in the other lists."
  20364. (let ((rtn (copy-sequence (pop plists)))
  20365. p v ls)
  20366. (while plists
  20367. (setq ls (pop plists))
  20368. (while ls
  20369. (setq p (pop ls) v (pop ls))
  20370. (setq rtn (plist-put rtn p v))))
  20371. rtn))
  20372. (defun org-replace-escapes (string table)
  20373. "Replace %-escapes in STRING with values in TABLE.
  20374. TABLE is an association list with keys like \"%a\" and string values.
  20375. The sequences in STRING may contain normal field width and padding information,
  20376. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20377. so values can contain further %-escapes if they are define later in TABLE."
  20378. (let ((tbl (copy-alist table))
  20379. (case-fold-search nil)
  20380. (pchg 0)
  20381. re rpl)
  20382. (dolist (e tbl)
  20383. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20384. (when (and (cdr e) (string-match re (cdr e)))
  20385. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20386. (safe "SREF"))
  20387. (add-text-properties 0 3 (list 'sref sref) safe)
  20388. (setcdr e (replace-match safe t t (cdr e)))))
  20389. (while (string-match re string)
  20390. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20391. (cdr e)))
  20392. (setq string (replace-match rpl t t string))))
  20393. (while (setq pchg (next-property-change pchg string))
  20394. (let ((sref (get-text-property pchg 'sref string)))
  20395. (when (and sref (string-match "SREF" string pchg))
  20396. (setq string (replace-match sref t t string)))))
  20397. string))
  20398. (defun org-find-base-buffer-visiting (file)
  20399. "Like `find-buffer-visiting' but always return the base buffer and
  20400. not an indirect buffer."
  20401. (let ((buf (or (get-file-buffer file)
  20402. (find-buffer-visiting file))))
  20403. (if buf
  20404. (or (buffer-base-buffer buf) buf)
  20405. nil)))
  20406. ;;; TODO: Only called once, from ox-odt which should probably use
  20407. ;;; org-export-inline-image-p or something.
  20408. (defun org-file-image-p (file)
  20409. "Return non-nil if FILE is an image."
  20410. (save-match-data
  20411. (string-match (image-file-name-regexp) file)))
  20412. (defun org-get-cursor-date (&optional with-time)
  20413. "Return the date at cursor in as a time.
  20414. This works in the calendar and in the agenda, anywhere else it just
  20415. returns the current time.
  20416. If WITH-TIME is non-nil, returns the time of the event at point (in
  20417. the agenda) or the current time of the day."
  20418. (let (date day defd tp hod mod)
  20419. (when with-time
  20420. (setq tp (get-text-property (point) 'time))
  20421. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20422. (setq hod (string-to-number (match-string 1 tp))
  20423. mod (string-to-number (match-string 2 tp))))
  20424. (or tp (let ((now (decode-time)))
  20425. (setq hod (nth 2 now)
  20426. mod (nth 1 now)))))
  20427. (cond
  20428. ((eq major-mode 'calendar-mode)
  20429. (setq date (calendar-cursor-to-date)
  20430. defd (encode-time 0 (or mod 0) (or hod 0)
  20431. (nth 1 date) (nth 0 date) (nth 2 date))))
  20432. ((eq major-mode 'org-agenda-mode)
  20433. (setq day (get-text-property (point) 'day))
  20434. (when day
  20435. (setq date (calendar-gregorian-from-absolute day)
  20436. defd (encode-time 0 (or mod 0) (or hod 0)
  20437. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20438. (or defd (current-time))))
  20439. (defun org-mark-subtree (&optional up)
  20440. "Mark the current subtree.
  20441. This puts point at the start of the current subtree, and mark at
  20442. the end. If a numeric prefix UP is given, move up into the
  20443. hierarchy of headlines by UP levels before marking the subtree."
  20444. (interactive "P")
  20445. (org-with-limited-levels
  20446. (cond ((org-at-heading-p) (beginning-of-line))
  20447. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20448. (t (outline-previous-visible-heading 1))))
  20449. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20450. (if (called-interactively-p 'any)
  20451. (call-interactively 'org-mark-element)
  20452. (org-mark-element)))
  20453. (defun org-file-newer-than-p (file time)
  20454. "Non-nil if FILE is newer than TIME.
  20455. FILE is a filename, as a string, TIME is a list of integers, as
  20456. returned by, e.g., `current-time'."
  20457. (and (file-exists-p file)
  20458. ;; Only compare times up to whole seconds as some file-systems
  20459. ;; (e.g. HFS+) do not retain any finer granularity. As
  20460. ;; a consequence, make sure we return non-nil when the two
  20461. ;; times are equal.
  20462. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20463. (cl-subseq time 0 2)))))
  20464. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20465. "Compile a SOURCE file using PROCESS.
  20466. PROCESS is either a function or a list of shell commands, as
  20467. strings. EXT is a file extension, without the leading dot, as
  20468. a string. It is used to check if the process actually succeeded.
  20469. PROCESS must create a file with the same base name and directory
  20470. as SOURCE, but ending with EXT. The function then returns its
  20471. filename. Otherwise, it raises an error. The error message can
  20472. then be refined by providing string ERR-MSG, which is appended to
  20473. the standard message.
  20474. If PROCESS is a function, it is called with a single argument:
  20475. the SOURCE file.
  20476. If it is a list of commands, each of them is called using
  20477. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20478. %O are replaced with, respectively, SOURCE base name, name, full
  20479. name, directory and absolute output file name. It is possible,
  20480. however, to use more place-holders by specifying them in optional
  20481. argument SPEC, as an alist following the pattern
  20482. (CHARACTER . REPLACEMENT-STRING).
  20483. When PROCESS is a list of commands, optional argument LOG-BUF can
  20484. be set to a buffer or a buffer name. `shell-command' then uses
  20485. it for output."
  20486. (let* ((base-name (file-name-base source))
  20487. (full-name (file-truename source))
  20488. (out-dir (or (file-name-directory source) "./"))
  20489. (output (expand-file-name (concat base-name "." ext) out-dir))
  20490. (time (current-time))
  20491. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20492. (save-window-excursion
  20493. (pcase process
  20494. ((pred functionp) (funcall process (shell-quote-argument source)))
  20495. ((pred consp)
  20496. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20497. (spec (append spec
  20498. `((?b . ,(shell-quote-argument base-name))
  20499. (?f . ,(shell-quote-argument source))
  20500. (?F . ,(shell-quote-argument full-name))
  20501. (?o . ,(shell-quote-argument out-dir))
  20502. (?O . ,(shell-quote-argument output))))))
  20503. (dolist (command process)
  20504. (shell-command (format-spec command spec) log-buf))
  20505. (when log-buf (with-current-buffer log-buf (compilation-mode)))))
  20506. (_ (error "No valid command to process %S%s" source err-msg))))
  20507. ;; Check for process failure. Output file is expected to be
  20508. ;; located in the same directory as SOURCE.
  20509. (unless (org-file-newer-than-p output time)
  20510. (error (format "File %S wasn't produced%s" output err-msg)))
  20511. output))
  20512. ;;; Indentation
  20513. (defvar org-element-greater-elements)
  20514. (defun org--get-expected-indentation (element contentsp)
  20515. "Expected indentation column for current line, according to ELEMENT.
  20516. ELEMENT is an element containing point. CONTENTSP is non-nil
  20517. when indentation is to be computed according to contents of
  20518. ELEMENT."
  20519. (let ((type (org-element-type element))
  20520. (start (org-element-property :begin element))
  20521. (post-affiliated (org-element-property :post-affiliated element)))
  20522. (org-with-wide-buffer
  20523. (cond
  20524. (contentsp
  20525. (cl-case type
  20526. ((diary-sexp footnote-definition) 0)
  20527. ((headline inlinetask nil)
  20528. (if (not org-adapt-indentation) 0
  20529. (let ((level (org-current-level)))
  20530. (if level (1+ level) 0))))
  20531. ((item plain-list) (org-list-item-body-column post-affiliated))
  20532. (t
  20533. (goto-char start)
  20534. (org-get-indentation))))
  20535. ((memq type '(headline inlinetask nil))
  20536. (if (org-match-line "[ \t]*$")
  20537. (org--get-expected-indentation element t)
  20538. 0))
  20539. ((memq type '(diary-sexp footnote-definition)) 0)
  20540. ;; First paragraph of a footnote definition or an item.
  20541. ;; Indent like parent.
  20542. ((< (line-beginning-position) start)
  20543. (org--get-expected-indentation
  20544. (org-element-property :parent element) t))
  20545. ;; At first line: indent according to previous sibling, if any,
  20546. ;; ignoring footnote definitions and inline tasks, or parent's
  20547. ;; contents.
  20548. ((= (line-beginning-position) start)
  20549. (catch 'exit
  20550. (while t
  20551. (if (= (point-min) start) (throw 'exit 0)
  20552. (goto-char (1- start))
  20553. (let* ((previous (org-element-at-point))
  20554. (parent previous))
  20555. (while (and parent (<= (org-element-property :end parent) start))
  20556. (setq previous parent
  20557. parent (org-element-property :parent parent)))
  20558. (cond
  20559. ((not previous) (throw 'exit 0))
  20560. ((> (org-element-property :end previous) start)
  20561. (throw 'exit (org--get-expected-indentation previous t)))
  20562. ((memq (org-element-type previous)
  20563. '(footnote-definition inlinetask))
  20564. (setq start (org-element-property :begin previous)))
  20565. (t (goto-char (org-element-property :begin previous))
  20566. (throw 'exit
  20567. (if (bolp) (org-get-indentation)
  20568. ;; At first paragraph in an item or
  20569. ;; a footnote definition.
  20570. (org--get-expected-indentation
  20571. (org-element-property :parent previous) t))))))))))
  20572. ;; Otherwise, move to the first non-blank line above.
  20573. (t
  20574. (beginning-of-line)
  20575. (let ((pos (point)))
  20576. (skip-chars-backward " \r\t\n")
  20577. (cond
  20578. ;; Two blank lines end a footnote definition or a plain
  20579. ;; list. When we indent an empty line after them, the
  20580. ;; containing list or footnote definition is over, so it
  20581. ;; qualifies as a previous sibling. Therefore, we indent
  20582. ;; like its first line.
  20583. ((and (memq type '(footnote-definition plain-list))
  20584. (> (count-lines (point) pos) 2))
  20585. (goto-char start)
  20586. (org-get-indentation))
  20587. ;; Line above is the first one of a paragraph at the
  20588. ;; beginning of an item or a footnote definition. Indent
  20589. ;; like parent.
  20590. ((< (line-beginning-position) start)
  20591. (org--get-expected-indentation
  20592. (org-element-property :parent element) t))
  20593. ;; Line above is the beginning of an element, i.e., point
  20594. ;; was originally on the blank lines between element's start
  20595. ;; and contents.
  20596. ((= (line-beginning-position) post-affiliated)
  20597. (org--get-expected-indentation element t))
  20598. ;; POS is after contents in a greater element. Indent like
  20599. ;; the beginning of the element.
  20600. ((and (memq type org-element-greater-elements)
  20601. (let ((cend (org-element-property :contents-end element)))
  20602. (and cend (<= cend pos))))
  20603. ;; As a special case, if point is at the end of a footnote
  20604. ;; definition or an item, indent like the very last element
  20605. ;; within. If that last element is an item, indent like
  20606. ;; its contents.
  20607. (if (memq type '(footnote-definition item plain-list))
  20608. (let ((last (org-element-at-point)))
  20609. (goto-char pos)
  20610. (org--get-expected-indentation
  20611. last (eq (org-element-type last) 'item)))
  20612. (goto-char start)
  20613. (org-get-indentation)))
  20614. ;; In any other case, indent like the current line.
  20615. (t (org-get-indentation)))))))))
  20616. (defun org--align-node-property ()
  20617. "Align node property at point.
  20618. Alignment is done according to `org-property-format', which see."
  20619. (when (save-excursion
  20620. (beginning-of-line)
  20621. (looking-at org-property-re))
  20622. (replace-match
  20623. (concat (match-string 4)
  20624. (org-trim
  20625. (format org-property-format (match-string 1) (match-string 3))))
  20626. t t)))
  20627. (defun org-indent-line ()
  20628. "Indent line depending on context.
  20629. Indentation is done according to the following rules:
  20630. - Footnote definitions, diary sexps, headlines and inline tasks
  20631. have to start at column 0.
  20632. - On the very first line of an element, consider, in order, the
  20633. next rules until one matches:
  20634. 1. If there's a sibling element before, ignoring footnote
  20635. definitions and inline tasks, indent like its first line.
  20636. 2. If element has a parent, indent like its contents. More
  20637. precisely, if parent is an item, indent after the
  20638. description part, if any, or the bullet (see
  20639. `org-list-description-max-indent'). Else, indent like
  20640. parent's first line.
  20641. 3. Otherwise, indent relatively to current level, if
  20642. `org-adapt-indentation' is non-nil, or to left margin.
  20643. - On a blank line at the end of an element, indent according to
  20644. the type of the element. More precisely
  20645. 1. If element is a plain list, an item, or a footnote
  20646. definition, indent like the very last element within.
  20647. 2. If element is a paragraph, indent like its last non blank
  20648. line.
  20649. 3. Otherwise, indent like its very first line.
  20650. - In the code part of a source block, use language major mode
  20651. to indent current line if `org-src-tab-acts-natively' is
  20652. non-nil. If it is nil, do nothing.
  20653. - Otherwise, indent like the first non-blank line above.
  20654. The function doesn't indent an item as it could break the whole
  20655. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20656. `\\[org-shiftmetaright]'.
  20657. Also align node properties according to `org-property-format'."
  20658. (interactive)
  20659. (cond
  20660. (orgstruct-is-++
  20661. (let ((indent-line-function
  20662. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20663. (indent-according-to-mode)))
  20664. ((org-at-heading-p) 'noindent)
  20665. (t
  20666. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20667. (type (org-element-type element)))
  20668. (cond ((and (memq type '(plain-list item))
  20669. (= (line-beginning-position)
  20670. (org-element-property :post-affiliated element)))
  20671. 'noindent)
  20672. ((and (eq type 'latex-environment)
  20673. (>= (point) (org-element-property :post-affiliated element))
  20674. (< (point) (org-with-wide-buffer
  20675. (goto-char (org-element-property :end element))
  20676. (skip-chars-backward " \r\t\n")
  20677. (line-beginning-position 2))))
  20678. 'noindent)
  20679. ((and (eq type 'src-block)
  20680. org-src-tab-acts-natively
  20681. (> (line-beginning-position)
  20682. (org-element-property :post-affiliated element))
  20683. (< (line-beginning-position)
  20684. (org-with-wide-buffer
  20685. (goto-char (org-element-property :end element))
  20686. (skip-chars-backward " \r\t\n")
  20687. (line-beginning-position))))
  20688. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20689. (t
  20690. (let ((column (org--get-expected-indentation element nil)))
  20691. ;; Preserve current column.
  20692. (if (<= (current-column) (current-indentation))
  20693. (indent-line-to column)
  20694. (save-excursion (indent-line-to column))))
  20695. ;; Align node property. Also preserve current column.
  20696. (when (eq type 'node-property)
  20697. (let ((column (current-column)))
  20698. (org--align-node-property)
  20699. (org-move-to-column column)))))))))
  20700. (defun org-indent-region (start end)
  20701. "Indent each non-blank line in the region.
  20702. Called from a program, START and END specify the region to
  20703. indent. The function will not indent contents of example blocks,
  20704. verse blocks and export blocks as leading white spaces are
  20705. assumed to be significant there."
  20706. (interactive "r")
  20707. (save-excursion
  20708. (goto-char start)
  20709. (skip-chars-forward " \r\t\n")
  20710. (unless (eobp) (beginning-of-line))
  20711. (let ((indent-to
  20712. (lambda (ind pos)
  20713. ;; Set IND as indentation for all lines between point and
  20714. ;; POS. Blank lines are ignored. Leave point after POS
  20715. ;; once done.
  20716. (let ((limit (copy-marker pos)))
  20717. (while (< (point) limit)
  20718. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20719. (forward-line))
  20720. (set-marker limit nil))))
  20721. (end (copy-marker end)))
  20722. (while (< (point) end)
  20723. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20724. (let* ((element (org-element-at-point))
  20725. (type (org-element-type element))
  20726. (element-end (copy-marker (org-element-property :end element)))
  20727. (ind (org--get-expected-indentation element nil)))
  20728. (cond
  20729. ;; Element indented as a single block. Example blocks
  20730. ;; preserving indentation are a special case since the
  20731. ;; "contents" must not be indented whereas the block
  20732. ;; boundaries can.
  20733. ((or (memq type '(export-block latex-environment))
  20734. (and (eq type 'example-block)
  20735. (not
  20736. (or org-src-preserve-indentation
  20737. (org-element-property :preserve-indent element)))))
  20738. (let ((offset (- ind (org-get-indentation))))
  20739. (unless (zerop offset)
  20740. (indent-rigidly (org-element-property :begin element)
  20741. (org-element-property :end element)
  20742. offset)))
  20743. (goto-char element-end))
  20744. ;; Elements indented line wise. Be sure to exclude
  20745. ;; example blocks (preserving indentation) and source
  20746. ;; blocks from this category as they are treated
  20747. ;; specially later.
  20748. ((or (memq type '(paragraph table table-row))
  20749. (not (or (org-element-property :contents-begin element)
  20750. (memq type '(example-block src-block)))))
  20751. (when (eq type 'node-property)
  20752. (org--align-node-property)
  20753. (beginning-of-line))
  20754. (funcall indent-to ind (min element-end end)))
  20755. ;; Elements consisting of three parts: before the
  20756. ;; contents, the contents, and after the contents. The
  20757. ;; contents are treated specially, according to the
  20758. ;; element type, or not indented at all. Other parts are
  20759. ;; indented as a single block.
  20760. (t
  20761. (let* ((post (copy-marker
  20762. (org-element-property :post-affiliated element)))
  20763. (cbeg
  20764. (copy-marker
  20765. (cond
  20766. ((not (org-element-property :contents-begin element))
  20767. ;; Fake contents for source blocks.
  20768. (org-with-wide-buffer
  20769. (goto-char post)
  20770. (line-beginning-position 2)))
  20771. ((memq type '(footnote-definition item plain-list))
  20772. ;; Contents in these elements could start on
  20773. ;; the same line as the beginning of the
  20774. ;; element. Make sure we start indenting
  20775. ;; from the second line.
  20776. (org-with-wide-buffer
  20777. (goto-char post)
  20778. (end-of-line)
  20779. (skip-chars-forward " \r\t\n")
  20780. (if (eobp) (point) (line-beginning-position))))
  20781. (t (org-element-property :contents-begin element)))))
  20782. (cend (copy-marker
  20783. (or (org-element-property :contents-end element)
  20784. ;; Fake contents for source blocks.
  20785. (org-with-wide-buffer
  20786. (goto-char element-end)
  20787. (skip-chars-backward " \r\t\n")
  20788. (line-beginning-position)))
  20789. t)))
  20790. ;; Do not change items indentation individually as it
  20791. ;; might break the list as a whole. On the other
  20792. ;; hand, when at a plain list, indent it as a whole.
  20793. (cond ((eq type 'plain-list)
  20794. (let ((offset (- ind (org-get-indentation))))
  20795. (unless (zerop offset)
  20796. (indent-rigidly (org-element-property :begin element)
  20797. (org-element-property :end element)
  20798. offset))
  20799. (goto-char cbeg)))
  20800. ((eq type 'item) (goto-char cbeg))
  20801. (t (funcall indent-to ind (min cbeg end))))
  20802. (when (< (point) end)
  20803. (cl-case type
  20804. ((example-block verse-block))
  20805. (src-block
  20806. ;; In a source block, indent source code
  20807. ;; according to language major mode, but only if
  20808. ;; `org-src-tab-acts-natively' is non-nil.
  20809. (when (and (< (point) end) org-src-tab-acts-natively)
  20810. (ignore-errors
  20811. (org-babel-do-in-edit-buffer
  20812. (indent-region (point-min) (point-max))))))
  20813. (t (org-indent-region (point) (min cend end))))
  20814. (goto-char (min cend end))
  20815. (when (< (point) end)
  20816. (funcall indent-to ind (min element-end end))))
  20817. (set-marker post nil)
  20818. (set-marker cbeg nil)
  20819. (set-marker cend nil))))
  20820. (set-marker element-end nil))))
  20821. (set-marker end nil))))
  20822. (defun org-indent-drawer ()
  20823. "Indent the drawer at point."
  20824. (interactive)
  20825. (unless (save-excursion
  20826. (beginning-of-line)
  20827. (looking-at-p org-drawer-regexp))
  20828. (user-error "Not at a drawer"))
  20829. (let ((element (org-element-at-point)))
  20830. (unless (memq (org-element-type element) '(drawer property-drawer))
  20831. (user-error "Not at a drawer"))
  20832. (org-with-wide-buffer
  20833. (org-indent-region (org-element-property :begin element)
  20834. (org-element-property :end element))))
  20835. (message "Drawer at point indented"))
  20836. (defun org-indent-block ()
  20837. "Indent the block at point."
  20838. (interactive)
  20839. (unless (save-excursion
  20840. (beginning-of-line)
  20841. (let ((case-fold-search t))
  20842. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  20843. (user-error "Not at a block"))
  20844. (let ((element (org-element-at-point)))
  20845. (unless (memq (org-element-type element)
  20846. '(comment-block center-block dynamic-block example-block
  20847. export-block quote-block special-block
  20848. src-block verse-block))
  20849. (user-error "Not at a block"))
  20850. (org-with-wide-buffer
  20851. (org-indent-region (org-element-property :begin element)
  20852. (org-element-property :end element))))
  20853. (message "Block at point indented"))
  20854. ;;; Filling
  20855. ;; We use our own fill-paragraph and auto-fill functions.
  20856. ;; `org-fill-paragraph' relies on adaptive filling and context
  20857. ;; checking. Appropriate `fill-prefix' is computed with
  20858. ;; `org-adaptive-fill-function'.
  20859. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  20860. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  20861. ;; `org-adaptive-fill-function' value. Internally,
  20862. ;; `org-comment-line-break-function' breaks the line.
  20863. ;; `org-setup-filling' installs filling and auto-filling related
  20864. ;; variables during `org-mode' initialization.
  20865. (defvar org-element-paragraph-separate) ; org-element.el
  20866. (defun org-setup-filling ()
  20867. (require 'org-element)
  20868. ;; Prevent auto-fill from inserting unwanted new items.
  20869. (when (boundp 'fill-nobreak-predicate)
  20870. (setq-local
  20871. fill-nobreak-predicate
  20872. (org-uniquify
  20873. (append fill-nobreak-predicate
  20874. '(org-fill-line-break-nobreak-p
  20875. org-fill-n-macro-as-item-nobreak-p
  20876. org-fill-paragraph-with-timestamp-nobreak-p)))))
  20877. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  20878. (setq-local paragraph-start paragraph-ending)
  20879. (setq-local paragraph-separate paragraph-ending))
  20880. (setq-local fill-paragraph-function 'org-fill-paragraph)
  20881. (setq-local auto-fill-inhibit-regexp nil)
  20882. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  20883. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  20884. (setq-local comment-line-break-function 'org-comment-line-break-function))
  20885. (defun org-fill-line-break-nobreak-p ()
  20886. "Non-nil when a new line at point would create an Org line break."
  20887. (save-excursion
  20888. (skip-chars-backward "[ \t]")
  20889. (skip-chars-backward "\\\\")
  20890. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  20891. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  20892. "Non-nil when a new line at point would split a timestamp."
  20893. (and (org-at-timestamp-p 'lax)
  20894. (not (looking-at org-ts-regexp-both))))
  20895. (defun org-fill-n-macro-as-item-nobreak-p ()
  20896. "Non-nil when a new line at point would create a new list."
  20897. ;; During export, a "n" macro followed by a dot or a closing
  20898. ;; parenthesis can end up being parsed as a new list item.
  20899. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  20900. (declare-function message-in-body-p "message" ())
  20901. (defvar orgtbl-line-start-regexp) ; From org-table.el
  20902. (defun org-adaptive-fill-function ()
  20903. "Compute a fill prefix for the current line.
  20904. Return fill prefix, as a string, or nil if current line isn't
  20905. meant to be filled. For convenience, if `adaptive-fill-regexp'
  20906. matches in paragraphs or comments, use it."
  20907. (catch 'exit
  20908. (when (derived-mode-p 'message-mode)
  20909. (save-excursion
  20910. (beginning-of-line)
  20911. (cond ((not (message-in-body-p)) (throw 'exit nil))
  20912. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  20913. ((looking-at message-cite-prefix-regexp)
  20914. (throw 'exit (match-string-no-properties 0)))
  20915. ((looking-at org-outline-regexp)
  20916. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  20917. (org-with-wide-buffer
  20918. (unless (org-at-heading-p)
  20919. (let* ((p (line-beginning-position))
  20920. (element (save-excursion
  20921. (beginning-of-line)
  20922. (org-element-at-point)))
  20923. (type (org-element-type element))
  20924. (post-affiliated (org-element-property :post-affiliated element)))
  20925. (unless (< p post-affiliated)
  20926. (cl-case type
  20927. (comment
  20928. (save-excursion
  20929. (beginning-of-line)
  20930. (looking-at "[ \t]*")
  20931. (concat (match-string 0) "# ")))
  20932. (footnote-definition "")
  20933. ((item plain-list)
  20934. (make-string (org-list-item-body-column post-affiliated) ?\s))
  20935. (paragraph
  20936. ;; Fill prefix is usually the same as the current line,
  20937. ;; unless the paragraph is at the beginning of an item.
  20938. (let ((parent (org-element-property :parent element)))
  20939. (save-excursion
  20940. (beginning-of-line)
  20941. (cond ((eq (org-element-type parent) 'item)
  20942. (make-string (org-list-item-body-column
  20943. (org-element-property :begin parent))
  20944. ?\s))
  20945. ((and adaptive-fill-regexp
  20946. ;; Locally disable
  20947. ;; `adaptive-fill-function' to let
  20948. ;; `fill-context-prefix' handle
  20949. ;; `adaptive-fill-regexp' variable.
  20950. (let (adaptive-fill-function)
  20951. (fill-context-prefix
  20952. post-affiliated
  20953. (org-element-property :end element)))))
  20954. ((looking-at "[ \t]+") (match-string 0))
  20955. (t "")))))
  20956. (comment-block
  20957. ;; Only fill contents if P is within block boundaries.
  20958. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  20959. (forward-line)
  20960. (point)))
  20961. (cend (save-excursion
  20962. (goto-char (org-element-property :end element))
  20963. (skip-chars-backward " \r\t\n")
  20964. (line-beginning-position))))
  20965. (when (and (>= p cbeg) (< p cend))
  20966. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  20967. (match-string 0)
  20968. "")))))))))))
  20969. (declare-function message-goto-body "message" ())
  20970. (defvar message-cite-prefix-regexp) ; From message.el
  20971. (defun org-fill-element (&optional justify)
  20972. "Fill element at point, when applicable.
  20973. This function only applies to comment blocks, comments, example
  20974. blocks and paragraphs. Also, as a special case, re-align table
  20975. when point is at one.
  20976. If JUSTIFY is non-nil (interactively, with prefix argument),
  20977. justify as well. If `sentence-end-double-space' is non-nil, then
  20978. period followed by one space does not end a sentence, so don't
  20979. break a line there. The variable `fill-column' controls the
  20980. width for filling.
  20981. For convenience, when point is at a plain list, an item or
  20982. a footnote definition, try to fill the first paragraph within."
  20983. (with-syntax-table org-mode-transpose-word-syntax-table
  20984. ;; Move to end of line in order to get the first paragraph within
  20985. ;; a plain list or a footnote definition.
  20986. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  20987. ;; First check if point is in a blank line at the beginning of
  20988. ;; the buffer. In that case, ignore filling.
  20989. (cl-case (org-element-type element)
  20990. ;; Use major mode filling function is src blocks.
  20991. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  20992. ;; Align Org tables, leave table.el tables as-is.
  20993. (table-row (org-table-align) t)
  20994. (table
  20995. (when (eq (org-element-property :type element) 'org)
  20996. (save-excursion
  20997. (goto-char (org-element-property :post-affiliated element))
  20998. (org-table-align)))
  20999. t)
  21000. (paragraph
  21001. ;; Paragraphs may contain `line-break' type objects.
  21002. (let ((beg (max (point-min)
  21003. (org-element-property :contents-begin element)))
  21004. (end (min (point-max)
  21005. (org-element-property :contents-end element))))
  21006. ;; Do nothing if point is at an affiliated keyword.
  21007. (if (< (line-end-position) beg) t
  21008. (when (derived-mode-p 'message-mode)
  21009. ;; In `message-mode', do not fill following citation
  21010. ;; in current paragraph nor text before message body.
  21011. (let ((body-start (save-excursion (message-goto-body))))
  21012. (when body-start (setq beg (max body-start beg))))
  21013. (when (save-excursion
  21014. (re-search-forward
  21015. (concat "^" message-cite-prefix-regexp) end t))
  21016. (setq end (match-beginning 0))))
  21017. ;; Fill paragraph, taking line breaks into account.
  21018. (save-excursion
  21019. (goto-char beg)
  21020. (let ((cuts (list beg)))
  21021. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21022. (when (eq 'line-break
  21023. (org-element-type
  21024. (save-excursion (backward-char)
  21025. (org-element-context))))
  21026. (push (point) cuts)))
  21027. (dolist (c (delq end cuts))
  21028. (fill-region-as-paragraph c end justify)
  21029. (setq end c))))
  21030. t)))
  21031. ;; Contents of `comment-block' type elements should be
  21032. ;; filled as plain text, but only if point is within block
  21033. ;; markers.
  21034. (comment-block
  21035. (let* ((case-fold-search t)
  21036. (beg (save-excursion
  21037. (goto-char (org-element-property :begin element))
  21038. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21039. (forward-line)
  21040. (point)))
  21041. (end (save-excursion
  21042. (goto-char (org-element-property :end element))
  21043. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21044. (line-beginning-position))))
  21045. (if (or (< (point) beg) (> (point) end)) t
  21046. (fill-region-as-paragraph
  21047. (save-excursion (end-of-line)
  21048. (re-search-backward "^[ \t]*$" beg 'move)
  21049. (line-beginning-position))
  21050. (save-excursion (beginning-of-line)
  21051. (re-search-forward "^[ \t]*$" end 'move)
  21052. (line-beginning-position))
  21053. justify))))
  21054. ;; Fill comments.
  21055. (comment
  21056. (let ((begin (org-element-property :post-affiliated element))
  21057. (end (org-element-property :end element)))
  21058. (when (and (>= (point) begin) (<= (point) end))
  21059. (let ((begin (save-excursion
  21060. (end-of-line)
  21061. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21062. (progn (forward-line) (point))
  21063. begin)))
  21064. (end (save-excursion
  21065. (end-of-line)
  21066. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21067. (1- (line-beginning-position))
  21068. (skip-chars-backward " \r\t\n")
  21069. (line-end-position)))))
  21070. ;; Do not fill comments when at a blank line.
  21071. (when (> end begin)
  21072. (let ((fill-prefix
  21073. (save-excursion
  21074. (beginning-of-line)
  21075. (looking-at "[ \t]*#")
  21076. (let ((comment-prefix (match-string 0)))
  21077. (goto-char (match-end 0))
  21078. (if (looking-at adaptive-fill-regexp)
  21079. (concat comment-prefix (match-string 0))
  21080. (concat comment-prefix " "))))))
  21081. (save-excursion
  21082. (fill-region-as-paragraph begin end justify))))))
  21083. t))
  21084. ;; Ignore every other element.
  21085. (otherwise t)))))
  21086. (defun org-fill-paragraph (&optional justify region)
  21087. "Fill element at point, when applicable.
  21088. This function only applies to comment blocks, comments, example
  21089. blocks and paragraphs. Also, as a special case, re-align table
  21090. when point is at one.
  21091. For convenience, when point is at a plain list, an item or
  21092. a footnote definition, try to fill the first paragraph within.
  21093. If JUSTIFY is non-nil (interactively, with prefix argument),
  21094. justify as well. If `sentence-end-double-space' is non-nil, then
  21095. period followed by one space does not end a sentence, so don't
  21096. break a line there. The variable `fill-column' controls the
  21097. width for filling.
  21098. The REGION argument is non-nil if called interactively; in that
  21099. case, if Transient Mark mode is enabled and the mark is active,
  21100. fill each of the elements in the active region, instead of just
  21101. filling the current element."
  21102. (interactive (progn
  21103. (barf-if-buffer-read-only)
  21104. (list (if current-prefix-arg 'full) t)))
  21105. (cond
  21106. ((and (derived-mode-p 'message-mode)
  21107. (or (not (message-in-body-p))
  21108. (save-excursion (move-beginning-of-line 1)
  21109. (looking-at message-cite-prefix-regexp))))
  21110. ;; First ensure filling is correct in message-mode.
  21111. (let ((fill-paragraph-function
  21112. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21113. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21114. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21115. (paragraph-separate
  21116. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21117. (fill-paragraph nil)))
  21118. ((and region transient-mark-mode mark-active
  21119. (not (eq (region-beginning) (region-end))))
  21120. (let ((origin (point-marker))
  21121. (start (region-beginning)))
  21122. (unwind-protect
  21123. (progn
  21124. (goto-char (region-end))
  21125. (while (> (point) start)
  21126. (org-backward-paragraph)
  21127. (org-fill-element justify)))
  21128. (goto-char origin)
  21129. (set-marker origin nil))))
  21130. (t (org-fill-element justify))))
  21131. (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
  21132. (defun org-auto-fill-function ()
  21133. "Auto-fill function."
  21134. ;; Check if auto-filling is meaningful.
  21135. (let ((fc (current-fill-column)))
  21136. (when (and fc (> (current-column) fc))
  21137. (let* ((fill-prefix (org-adaptive-fill-function))
  21138. ;; Enforce empty fill prefix, if required. Otherwise, it
  21139. ;; will be computed again.
  21140. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21141. (when fill-prefix (do-auto-fill))))))
  21142. (defun org-comment-line-break-function (&optional soft)
  21143. "Break line at point and indent, continuing comment if within one.
  21144. The inserted newline is marked hard if variable
  21145. `use-hard-newlines' is true, unless optional argument SOFT is
  21146. non-nil."
  21147. (if soft (insert-and-inherit ?\n) (newline 1))
  21148. (save-excursion (forward-char -1) (delete-horizontal-space))
  21149. (delete-horizontal-space)
  21150. (indent-to-left-margin)
  21151. (insert-before-markers-and-inherit fill-prefix))
  21152. ;;; Fixed Width Areas
  21153. (defun org-toggle-fixed-width ()
  21154. "Toggle fixed-width markup.
  21155. Add or remove fixed-width markup on current line, whenever it
  21156. makes sense. Return an error otherwise.
  21157. If a region is active and if it contains only fixed-width areas
  21158. or blank lines, remove all fixed-width markup in it. If the
  21159. region contains anything else, convert all non-fixed-width lines
  21160. to fixed-width ones.
  21161. Blank lines at the end of the region are ignored unless the
  21162. region only contains such lines."
  21163. (interactive)
  21164. (if (not (org-region-active-p))
  21165. ;; No region:
  21166. ;;
  21167. ;; Remove fixed width marker only in a fixed-with element.
  21168. ;;
  21169. ;; Add fixed width maker in paragraphs, in blank lines after
  21170. ;; elements or at the beginning of a headline or an inlinetask,
  21171. ;; and before any one-line elements (e.g., a clock).
  21172. (progn
  21173. (beginning-of-line)
  21174. (let* ((element (org-element-at-point))
  21175. (type (org-element-type element)))
  21176. (cond
  21177. ((and (eq type 'fixed-width)
  21178. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21179. (replace-match
  21180. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21181. ((and (memq type '(babel-call clock comment diary-sexp headline
  21182. horizontal-rule keyword paragraph
  21183. planning))
  21184. (<= (org-element-property :post-affiliated element) (point)))
  21185. (skip-chars-forward " \t")
  21186. (insert ": "))
  21187. ((and (looking-at-p "[ \t]*$")
  21188. (or (eq type 'inlinetask)
  21189. (save-excursion
  21190. (skip-chars-forward " \r\t\n")
  21191. (<= (org-element-property :end element) (point)))))
  21192. (delete-region (point) (line-end-position))
  21193. (org-indent-line)
  21194. (insert ": "))
  21195. (t (user-error "Cannot insert a fixed-width line here")))))
  21196. ;; Region active.
  21197. (let* ((begin (save-excursion
  21198. (goto-char (region-beginning))
  21199. (line-beginning-position)))
  21200. (end (copy-marker
  21201. (save-excursion
  21202. (goto-char (region-end))
  21203. (unless (eolp) (beginning-of-line))
  21204. (if (save-excursion (re-search-backward "\\S-" begin t))
  21205. (progn (skip-chars-backward " \r\t\n") (point))
  21206. (point)))))
  21207. (all-fixed-width-p
  21208. (catch 'not-all-p
  21209. (save-excursion
  21210. (goto-char begin)
  21211. (skip-chars-forward " \r\t\n")
  21212. (when (eobp) (throw 'not-all-p nil))
  21213. (while (< (point) end)
  21214. (let ((element (org-element-at-point)))
  21215. (if (eq (org-element-type element) 'fixed-width)
  21216. (goto-char (org-element-property :end element))
  21217. (throw 'not-all-p nil))))
  21218. t))))
  21219. (if all-fixed-width-p
  21220. (save-excursion
  21221. (goto-char begin)
  21222. (while (< (point) end)
  21223. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21224. (replace-match
  21225. "" nil nil nil
  21226. (if (= (line-end-position) (match-end 0)) 0 1)))
  21227. (forward-line)))
  21228. (let ((min-ind (point-max)))
  21229. ;; Find minimum indentation across all lines.
  21230. (save-excursion
  21231. (goto-char begin)
  21232. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21233. (setq min-ind 0)
  21234. (catch 'zerop
  21235. (while (< (point) end)
  21236. (unless (looking-at-p "[ \t]*$")
  21237. (let ((ind (org-get-indentation)))
  21238. (setq min-ind (min min-ind ind))
  21239. (when (zerop ind) (throw 'zerop t))))
  21240. (forward-line)))))
  21241. ;; Loop over all lines and add fixed-width markup everywhere
  21242. ;; but in fixed-width lines.
  21243. (save-excursion
  21244. (goto-char begin)
  21245. (while (< (point) end)
  21246. (cond
  21247. ((org-at-heading-p)
  21248. (insert ": ")
  21249. (forward-line)
  21250. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21251. (insert ":")
  21252. (forward-line)))
  21253. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21254. (let* ((element (org-element-at-point))
  21255. (element-end (org-element-property :end element)))
  21256. (if (eq (org-element-type element) 'fixed-width)
  21257. (progn (goto-char element-end)
  21258. (skip-chars-backward " \r\t\n")
  21259. (forward-line))
  21260. (let ((limit (min end element-end)))
  21261. (while (< (point) limit)
  21262. (org-move-to-column min-ind t)
  21263. (insert ": ")
  21264. (forward-line))))))
  21265. (t
  21266. (org-move-to-column min-ind t)
  21267. (insert ": ")
  21268. (forward-line)))))))
  21269. (set-marker end nil))))
  21270. ;;; Comments
  21271. ;; Org comments syntax is quite complex. It requires the entire line
  21272. ;; to be just a comment. Also, even with the right syntax at the
  21273. ;; beginning of line, some elements (e.g., verse-block or
  21274. ;; example-block) don't accept comments. Usual Emacs comment commands
  21275. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21276. ;; Org still relies on `comment-dwim', but cannot trust
  21277. ;; `comment-only-p'. So, `comment-region-function' and
  21278. ;; `uncomment-region-function' both point
  21279. ;; to`org-comment-or-uncomment-region'. Eventually,
  21280. ;; `org-insert-comment' takes care of insertion of comments at the
  21281. ;; beginning of line.
  21282. ;; `org-setup-comments-handling' install comments related variables
  21283. ;; during `org-mode' initialization.
  21284. (defun org-setup-comments-handling ()
  21285. (interactive)
  21286. (setq-local comment-use-syntax nil)
  21287. (setq-local comment-start "# ")
  21288. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21289. (setq-local comment-insert-comment-function 'org-insert-comment)
  21290. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21291. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21292. (defun org-insert-comment ()
  21293. "Insert an empty comment above current line.
  21294. If the line is empty, insert comment at its beginning. When
  21295. point is within a source block, comment according to the related
  21296. major mode."
  21297. (if (let ((element (org-element-at-point)))
  21298. (and (eq (org-element-type element) 'src-block)
  21299. (< (save-excursion
  21300. (goto-char (org-element-property :post-affiliated element))
  21301. (line-end-position))
  21302. (point))
  21303. (> (save-excursion
  21304. (goto-char (org-element-property :end element))
  21305. (skip-chars-backward " \r\t\n")
  21306. (line-beginning-position))
  21307. (point))))
  21308. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21309. (beginning-of-line)
  21310. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21311. (open-line 1))
  21312. (org-indent-line)
  21313. (insert "# ")))
  21314. (defvar comment-empty-lines) ; From newcomment.el.
  21315. (defun org-comment-or-uncomment-region (beg end &rest _)
  21316. "Comment or uncomment each non-blank line in the region.
  21317. Uncomment each non-blank line between BEG and END if it only
  21318. contains commented lines. Otherwise, comment them. If region is
  21319. strictly within a source block, use appropriate comment syntax."
  21320. (if (let ((element (org-element-at-point)))
  21321. (and (eq (org-element-type element) 'src-block)
  21322. (< (save-excursion
  21323. (goto-char (org-element-property :post-affiliated element))
  21324. (line-end-position))
  21325. beg)
  21326. (>= (save-excursion
  21327. (goto-char (org-element-property :end element))
  21328. (skip-chars-backward " \r\t\n")
  21329. (line-beginning-position))
  21330. end)))
  21331. ;; Translate region boundaries for the Org buffer to the source
  21332. ;; buffer.
  21333. (let ((offset (- end beg)))
  21334. (save-excursion
  21335. (goto-char beg)
  21336. (org-babel-do-in-edit-buffer
  21337. (comment-or-uncomment-region (point) (+ offset (point))))))
  21338. (save-restriction
  21339. ;; Restrict region
  21340. (narrow-to-region (save-excursion (goto-char beg)
  21341. (skip-chars-forward " \r\t\n" end)
  21342. (line-beginning-position))
  21343. (save-excursion (goto-char end)
  21344. (skip-chars-backward " \r\t\n" beg)
  21345. (line-end-position)))
  21346. (let ((uncommentp
  21347. ;; UNCOMMENTP is non-nil when every non blank line between
  21348. ;; BEG and END is a comment.
  21349. (save-excursion
  21350. (goto-char (point-min))
  21351. (while (and (not (eobp))
  21352. (let ((element (org-element-at-point)))
  21353. (and (eq (org-element-type element) 'comment)
  21354. (goto-char (min (point-max)
  21355. (org-element-property
  21356. :end element)))))))
  21357. (eobp))))
  21358. (if uncommentp
  21359. ;; Only blank lines and comments in region: uncomment it.
  21360. (save-excursion
  21361. (goto-char (point-min))
  21362. (while (not (eobp))
  21363. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21364. (replace-match "" nil nil nil 1))
  21365. (forward-line)))
  21366. ;; Comment each line in region.
  21367. (let ((min-indent (point-max)))
  21368. ;; First find the minimum indentation across all lines.
  21369. (save-excursion
  21370. (goto-char (point-min))
  21371. (while (and (not (eobp)) (not (zerop min-indent)))
  21372. (unless (looking-at "[ \t]*$")
  21373. (setq min-indent (min min-indent (current-indentation))))
  21374. (forward-line)))
  21375. ;; Then loop over all lines.
  21376. (save-excursion
  21377. (goto-char (point-min))
  21378. (while (not (eobp))
  21379. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21380. ;; Don't get fooled by invisible text (e.g. link path)
  21381. ;; when moving to column MIN-INDENT.
  21382. (let ((buffer-invisibility-spec nil))
  21383. (org-move-to-column min-indent t))
  21384. (insert comment-start))
  21385. (forward-line)))))))))
  21386. (defun org-comment-dwim (_arg)
  21387. "Call `comment-dwim' within a source edit buffer if needed."
  21388. (interactive "*P")
  21389. (if (org-in-src-block-p)
  21390. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21391. (call-interactively 'comment-dwim)))
  21392. ;;; Timestamps API
  21393. ;; This section contains tools to operate on timestamp objects, as
  21394. ;; returned by, e.g. `org-element-context'.
  21395. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21396. "Encode TIMESTAMP object into Emacs internal time.
  21397. Use end of date range or time range when END is non-nil."
  21398. (apply #'encode-time
  21399. (cons 0
  21400. (mapcar
  21401. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21402. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21403. '(:minute-start :hour-start :day-start :month-start
  21404. :year-start))))))
  21405. (defun org-timestamp-has-time-p (timestamp)
  21406. "Non-nil when TIMESTAMP has a time specified."
  21407. (org-element-property :hour-start timestamp))
  21408. (defun org-timestamp-format (timestamp format &optional end utc)
  21409. "Format a TIMESTAMP object into a string.
  21410. FORMAT is a format specifier to be passed to
  21411. `format-time-string'.
  21412. When optional argument END is non-nil, use end of date-range or
  21413. time-range, if possible.
  21414. When optional argument UTC is non-nil, time will be expressed as
  21415. Universal Time."
  21416. (format-time-string
  21417. format (org-timestamp--to-internal-time timestamp end)
  21418. (and utc t)))
  21419. (defun org-timestamp-split-range (timestamp &optional end)
  21420. "Extract a TIMESTAMP object from a date or time range.
  21421. END, when non-nil, means extract the end of the range.
  21422. Otherwise, extract its start.
  21423. Return a new timestamp object."
  21424. (let ((type (org-element-property :type timestamp)))
  21425. (if (memq type '(active inactive diary)) timestamp
  21426. (let ((split-ts (org-element-copy timestamp)))
  21427. ;; Set new type.
  21428. (org-element-put-property
  21429. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21430. ;; Copy start properties over end properties if END is
  21431. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21432. (let ((p-alist '((:minute-start . :minute-end)
  21433. (:hour-start . :hour-end)
  21434. (:day-start . :day-end)
  21435. (:month-start . :month-end)
  21436. (:year-start . :year-end))))
  21437. (dolist (p-cell p-alist)
  21438. (org-element-put-property
  21439. split-ts
  21440. (funcall (if end #'car #'cdr) p-cell)
  21441. (org-element-property
  21442. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21443. ;; Eventually refresh `:raw-value'.
  21444. (org-element-put-property split-ts :raw-value nil)
  21445. (org-element-put-property
  21446. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21447. (defun org-timestamp-translate (timestamp &optional boundary)
  21448. "Translate TIMESTAMP object to custom format.
  21449. Format string is defined in `org-time-stamp-custom-formats',
  21450. which see.
  21451. When optional argument BOUNDARY is non-nil, it is either the
  21452. symbol `start' or `end'. In this case, only translate the
  21453. starting or ending part of TIMESTAMP if it is a date or time
  21454. range. Otherwise, translate both parts.
  21455. Return timestamp as-is if `org-display-custom-times' is nil or if
  21456. it has a `diary' type."
  21457. (let ((type (org-element-property :type timestamp)))
  21458. (if (or (not org-display-custom-times) (eq type 'diary))
  21459. (org-element-interpret-data timestamp)
  21460. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21461. org-time-stamp-custom-formats)))
  21462. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21463. (concat (org-timestamp-format timestamp fmt)
  21464. "--"
  21465. (org-timestamp-format timestamp fmt t))
  21466. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21467. ;;; Other stuff.
  21468. (defvar reftex-docstruct-symbol)
  21469. (defvar org--rds)
  21470. (defun org-reftex-citation ()
  21471. "Use reftex-citation to insert a citation into the buffer.
  21472. This looks for a line like
  21473. #+BIBLIOGRAPHY: foo plain option:-d
  21474. and derives from it that foo.bib is the bibliography file relevant
  21475. for this document. It then installs the necessary environment for RefTeX
  21476. to work in this buffer and calls `reftex-citation' to insert a citation
  21477. into the buffer.
  21478. Export of such citations to both LaTeX and HTML is handled by the contributed
  21479. package ox-bibtex by Taru Karttunen."
  21480. (interactive)
  21481. (let ((reftex-docstruct-symbol 'org--rds)
  21482. org--rds bib)
  21483. (org-with-wide-buffer
  21484. (let ((case-fold-search t)
  21485. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21486. (if (not (save-excursion
  21487. (or (re-search-forward re nil t)
  21488. (re-search-backward re nil t))))
  21489. (user-error "No bibliography defined in file")
  21490. (setq bib (concat (match-string 1) ".bib")
  21491. org--rds (list (list 'bib bib))))))
  21492. (call-interactively 'reftex-citation)))
  21493. ;;;; Functions extending outline functionality
  21494. (defun org-beginning-of-line (&optional n)
  21495. "Go to the beginning of the current visible line.
  21496. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21497. tags on the first attempt, and only move to after the tags when
  21498. the cursor is already beyond the end of the headline.
  21499. With argument N not nil or 1, move forward N - 1 lines first."
  21500. (interactive "^p")
  21501. (let ((origin (point))
  21502. (special (pcase org-special-ctrl-a/e
  21503. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21504. deactivate-mark)
  21505. ;; First move to a visible line.
  21506. (if (bound-and-true-p visual-line-mode)
  21507. (beginning-of-visual-line n)
  21508. (move-beginning-of-line n)
  21509. ;; `move-beginning-of-line' may leave point after invisible
  21510. ;; characters if line starts with such of these (e.g., with
  21511. ;; a link at column 0). Really move to the beginning of the
  21512. ;; current visible line.
  21513. (beginning-of-line))
  21514. (cond
  21515. ;; No special behavior. Point is already at the beginning of
  21516. ;; a line, logical or visual.
  21517. ((not special))
  21518. ;; `beginning-of-visual-line' left point before logical beginning
  21519. ;; of line: point is at the beginning of a visual line. Bail
  21520. ;; out.
  21521. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21522. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21523. ;; At a headline, special position is before the title, but
  21524. ;; after any TODO keyword or priority cookie.
  21525. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21526. (line-end-position)))
  21527. (bol (point)))
  21528. (if (eq special 'reversed)
  21529. (when (and (= origin bol) (eq last-command this-command))
  21530. (goto-char refpos))
  21531. (when (or (> origin refpos) (= origin bol))
  21532. (goto-char refpos)))))
  21533. ((and (looking-at org-list-full-item-re)
  21534. (memq (org-element-type (save-match-data (org-element-at-point)))
  21535. '(item plain-list)))
  21536. ;; Set special position at first white space character after
  21537. ;; bullet, and check-box, if any.
  21538. (let ((after-bullet
  21539. (let ((box (match-end 3)))
  21540. (cond ((not box) (match-end 1))
  21541. ((eq (char-after box) ?\s) (1+ box))
  21542. (t box)))))
  21543. (if (eq special 'reversed)
  21544. (when (and (= (point) origin) (eq last-command this-command))
  21545. (goto-char after-bullet))
  21546. (when (or (> origin after-bullet) (= (point) origin))
  21547. (goto-char after-bullet)))))
  21548. ;; No special context. Point is already at beginning of line.
  21549. (t nil))))
  21550. (defun org-end-of-line (&optional n)
  21551. "Go to the end of the line, but before ellipsis, if any.
  21552. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21553. tags on the first attempt, and only move to after the tags when
  21554. the cursor is already beyond the end of the headline.
  21555. With argument N not nil or 1, move forward N - 1 lines first."
  21556. (interactive "^p")
  21557. (let ((origin (point))
  21558. (special (pcase org-special-ctrl-a/e
  21559. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21560. deactivate-mark)
  21561. ;; First move to a visible line.
  21562. (if (bound-and-true-p visual-line-mode)
  21563. (beginning-of-visual-line n)
  21564. (move-beginning-of-line n))
  21565. (cond
  21566. ;; At a headline, with tags.
  21567. ((and special
  21568. (save-excursion
  21569. (beginning-of-line)
  21570. (let ((case-fold-search nil))
  21571. (looking-at org-complex-heading-regexp)))
  21572. (match-end 5))
  21573. (let ((tags (save-excursion
  21574. (goto-char (match-beginning 5))
  21575. (skip-chars-backward " \t")
  21576. (point)))
  21577. (visual-end (and (bound-and-true-p visual-line-mode)
  21578. (save-excursion
  21579. (end-of-visual-line)
  21580. (point)))))
  21581. ;; If `end-of-visual-line' brings us before end of line or
  21582. ;; even tags, i.e., the headline spans over multiple visual
  21583. ;; lines, move there.
  21584. (cond ((and visual-end
  21585. (< visual-end tags)
  21586. (<= origin visual-end))
  21587. (goto-char visual-end))
  21588. ((eq special 'reversed)
  21589. (if (and (= origin (line-end-position))
  21590. (eq this-command last-command))
  21591. (goto-char tags)
  21592. (end-of-line)))
  21593. (t
  21594. (if (or (< origin tags) (= origin (line-end-position)))
  21595. (goto-char tags)
  21596. (end-of-line))))))
  21597. ((bound-and-true-p visual-line-mode)
  21598. (let ((bol (line-beginning-position)))
  21599. (end-of-visual-line)
  21600. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21601. ;; end of a line, backtrack and use `end-of-line' instead.
  21602. (when (/= bol (line-beginning-position))
  21603. (goto-char bol)
  21604. (end-of-line))))
  21605. (t (end-of-line)))))
  21606. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21607. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21608. (defun org-backward-sentence (&optional _arg)
  21609. "Go to beginning of sentence, or beginning of table field.
  21610. This will call `backward-sentence' or `org-table-beginning-of-field',
  21611. depending on context."
  21612. (interactive)
  21613. (let* ((element (org-element-at-point))
  21614. (contents-begin (org-element-property :contents-begin element))
  21615. (table (org-element-lineage element '(table) t)))
  21616. (if (and table
  21617. (> (point) contents-begin)
  21618. (<= (point) (org-element-property :contents-end table)))
  21619. (call-interactively #'org-table-beginning-of-field)
  21620. (save-restriction
  21621. (when (and contents-begin
  21622. (< (point-min) contents-begin)
  21623. (> (point) contents-begin))
  21624. (narrow-to-region contents-begin
  21625. (org-element-property :contents-end element)))
  21626. (call-interactively #'backward-sentence)))))
  21627. (defun org-forward-sentence (&optional _arg)
  21628. "Go to end of sentence, or end of table field.
  21629. This will call `forward-sentence' or `org-table-end-of-field',
  21630. depending on context."
  21631. (interactive)
  21632. (let* ((element (org-element-at-point))
  21633. (contents-end (org-element-property :contents-end element))
  21634. (table (org-element-lineage element '(table) t)))
  21635. (if (and table
  21636. (>= (point) (org-element-property :contents-begin table))
  21637. (< (point) contents-end))
  21638. (call-interactively #'org-table-end-of-field)
  21639. (save-restriction
  21640. (when (and contents-end
  21641. (> (point-max) contents-end)
  21642. ;; Skip blank lines between elements.
  21643. (< (org-element-property :end element)
  21644. (save-excursion (goto-char contents-end)
  21645. (skip-chars-forward " \r\t\n"))))
  21646. (narrow-to-region (org-element-property :contents-begin element)
  21647. contents-end))
  21648. (call-interactively #'forward-sentence)))))
  21649. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21650. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21651. (defun org-kill-line (&optional _arg)
  21652. "Kill line, to tags or end of line."
  21653. (interactive)
  21654. (cond
  21655. ((or (not org-special-ctrl-k)
  21656. (bolp)
  21657. (not (org-at-heading-p)))
  21658. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21659. org-ctrl-k-protect-subtree
  21660. (or (eq org-ctrl-k-protect-subtree 'error)
  21661. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21662. (user-error "C-k aborted as it would kill a hidden subtree"))
  21663. (call-interactively
  21664. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21665. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21666. (kill-region (point) (match-beginning 1))
  21667. (org-set-tags nil t))
  21668. (t (kill-region (point) (point-at-eol)))))
  21669. (define-key org-mode-map "\C-k" 'org-kill-line)
  21670. (defun org-yank (&optional arg)
  21671. "Yank. If the kill is a subtree, treat it specially.
  21672. This command will look at the current kill and check if is a single
  21673. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21674. cursor is at the beginning of a line or after the stars of a currently
  21675. empty headline, then the yank is handled specially. How exactly depends
  21676. on the value of the following variables.
  21677. `org-yank-folded-subtrees'
  21678. By default, this variable is non-nil, which results in
  21679. subtree(s) being folded after insertion, except if doing so
  21680. would swallow text after the yanked text.
  21681. `org-yank-adjusted-subtrees'
  21682. When non-nil (the default value is nil), the subtree will be
  21683. promoted or demoted in order to fit into the local outline tree
  21684. structure, which means that the level will be adjusted so that it
  21685. becomes the smaller one of the two *visible* surrounding headings.
  21686. Any prefix to this command will cause `yank' to be called directly with
  21687. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21688. will just
  21689. plainly yank the text as it is.
  21690. \[1] The test checks if the first non-white line is a heading
  21691. and if there are no other headings with fewer stars."
  21692. (interactive "P")
  21693. (org-yank-generic 'yank arg))
  21694. (defun org-yank-generic (command arg)
  21695. "Perform some yank-like command.
  21696. This function implements the behavior described in the `org-yank'
  21697. documentation. However, it has been generalized to work for any
  21698. interactive command with similar behavior."
  21699. ;; pretend to be command COMMAND
  21700. (setq this-command command)
  21701. (if arg
  21702. (call-interactively command)
  21703. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21704. (and (org-kill-is-subtree-p)
  21705. (or (bolp)
  21706. (and (looking-at "[ \t]*$")
  21707. (string-match
  21708. "\\`\\*+\\'"
  21709. (buffer-substring (point-at-bol) (point)))))))
  21710. swallowp)
  21711. (cond
  21712. ((and subtreep org-yank-folded-subtrees)
  21713. (let ((beg (point))
  21714. end)
  21715. (if (and subtreep org-yank-adjusted-subtrees)
  21716. (org-paste-subtree nil nil 'for-yank)
  21717. (call-interactively command))
  21718. (setq end (point))
  21719. (goto-char beg)
  21720. (when (and (bolp) subtreep
  21721. (not (setq swallowp
  21722. (org-yank-folding-would-swallow-text beg end))))
  21723. (org-with-limited-levels
  21724. (or (looking-at org-outline-regexp)
  21725. (re-search-forward org-outline-regexp-bol end t))
  21726. (while (and (< (point) end) (looking-at org-outline-regexp))
  21727. (outline-hide-subtree)
  21728. (org-cycle-show-empty-lines 'folded)
  21729. (condition-case nil
  21730. (outline-forward-same-level 1)
  21731. (error (goto-char end))))))
  21732. (when swallowp
  21733. (message
  21734. "Inserted text not folded because that would swallow text"))
  21735. (goto-char end)
  21736. (skip-chars-forward " \t\n\r")
  21737. (beginning-of-line 1)
  21738. (push-mark beg 'nomsg)))
  21739. ((and subtreep org-yank-adjusted-subtrees)
  21740. (let ((beg (point-at-bol)))
  21741. (org-paste-subtree nil nil 'for-yank)
  21742. (push-mark beg 'nomsg)))
  21743. (t
  21744. (call-interactively command))))))
  21745. (defun org-yank-folding-would-swallow-text (beg end)
  21746. "Would hide-subtree at BEG swallow any text after END?"
  21747. (let (level)
  21748. (org-with-limited-levels
  21749. (save-excursion
  21750. (goto-char beg)
  21751. (when (or (looking-at org-outline-regexp)
  21752. (re-search-forward org-outline-regexp-bol end t))
  21753. (setq level (org-outline-level)))
  21754. (goto-char end)
  21755. (skip-chars-forward " \t\r\n\v\f")
  21756. (not (or (eobp)
  21757. (and (bolp) (looking-at-p org-outline-regexp)
  21758. (<= (org-outline-level) level))))))))
  21759. (define-key org-mode-map "\C-y" 'org-yank)
  21760. (defun org-truely-invisible-p ()
  21761. "Check if point is at a character currently not visible.
  21762. This version does not only check the character property, but also
  21763. `visible-mode'."
  21764. ;; Early versions of noutline don't have `outline-invisible-p'.
  21765. (unless (bound-and-true-p visible-mode)
  21766. (outline-invisible-p)))
  21767. (defun org-invisible-p2 ()
  21768. "Check if point is at a character currently not visible."
  21769. (save-excursion
  21770. (when (and (eolp) (not (bobp))) (backward-char 1))
  21771. ;; Early versions of noutline don't have `outline-invisible-p'.
  21772. (outline-invisible-p)))
  21773. (defun org-back-to-heading (&optional invisible-ok)
  21774. "Call `outline-back-to-heading', but provide a better error message."
  21775. (condition-case nil
  21776. (outline-back-to-heading invisible-ok)
  21777. (error (error "Before first headline at position %d in buffer %s"
  21778. (point) (current-buffer)))))
  21779. (defun org-before-first-heading-p ()
  21780. "Before first heading?"
  21781. (save-excursion
  21782. (end-of-line)
  21783. (null (re-search-backward org-outline-regexp-bol nil t))))
  21784. (defun org-at-heading-p (&optional ignored)
  21785. (outline-on-heading-p t))
  21786. (defun org-in-commented-heading-p (&optional no-inheritance)
  21787. "Non-nil if point is under a commented heading.
  21788. This function also checks ancestors of the current headline,
  21789. unless optional argument NO-INHERITANCE is non-nil."
  21790. (cond
  21791. ((org-before-first-heading-p) nil)
  21792. ((let ((headline (nth 4 (org-heading-components))))
  21793. (and headline
  21794. (let ((case-fold-search nil))
  21795. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  21796. headline)))))
  21797. (no-inheritance nil)
  21798. (t
  21799. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  21800. (defun org-at-comment-p nil
  21801. "Is cursor in a commented line?"
  21802. (save-excursion
  21803. (save-match-data
  21804. (beginning-of-line)
  21805. (looking-at "^[ \t]*# "))))
  21806. (defun org-at-drawer-p nil
  21807. "Is cursor at a drawer keyword?"
  21808. (save-excursion
  21809. (move-beginning-of-line 1)
  21810. (looking-at org-drawer-regexp)))
  21811. (defun org-at-block-p nil
  21812. "Is cursor at a block keyword?"
  21813. (save-excursion
  21814. (move-beginning-of-line 1)
  21815. (looking-at org-block-regexp)))
  21816. (defun org-point-at-end-of-empty-headline ()
  21817. "If point is at the end of an empty headline, return t, else nil.
  21818. If the heading only contains a TODO keyword, it is still still considered
  21819. empty."
  21820. (let ((case-fold-search nil))
  21821. (and (looking-at "[ \t]*$")
  21822. org-todo-line-regexp
  21823. (save-excursion
  21824. (beginning-of-line)
  21825. (looking-at org-todo-line-regexp)
  21826. (string= (match-string 3) "")))))
  21827. (defun org-at-heading-or-item-p ()
  21828. (or (org-at-heading-p) (org-at-item-p)))
  21829. (defun org-at-target-p ()
  21830. (or (org-in-regexp org-radio-target-regexp)
  21831. (org-in-regexp org-target-regexp)))
  21832. ;; Compatibility alias with Org versions < 7.8.03
  21833. (defalias 'org-on-target-p 'org-at-target-p)
  21834. (defun org-up-heading-all (arg)
  21835. "Move to the heading line of which the present line is a subheading.
  21836. This function considers both visible and invisible heading lines.
  21837. With argument, move up ARG levels."
  21838. (outline-up-heading arg t))
  21839. (defun org-up-heading-safe ()
  21840. "Move to the heading line of which the present line is a subheading.
  21841. This version will not throw an error. It will return the level of the
  21842. headline found, or nil if no higher level is found.
  21843. Also, this function will be a lot faster than `outline-up-heading',
  21844. because it relies on stars being the outline starters. This can really
  21845. make a significant difference in outlines with very many siblings."
  21846. (when (ignore-errors (org-back-to-heading t))
  21847. (let ((level-up (1- (funcall outline-level))))
  21848. (and (> level-up 0)
  21849. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  21850. (funcall outline-level)))))
  21851. (defun org-first-sibling-p ()
  21852. "Is this heading the first child of its parents?"
  21853. (interactive)
  21854. (let ((re org-outline-regexp-bol)
  21855. level l)
  21856. (unless (org-at-heading-p t)
  21857. (user-error "Not at a heading"))
  21858. (setq level (funcall outline-level))
  21859. (save-excursion
  21860. (if (not (re-search-backward re nil t))
  21861. t
  21862. (setq l (funcall outline-level))
  21863. (< l level)))))
  21864. (defun org-goto-sibling (&optional previous)
  21865. "Goto the next sibling, even if it is invisible.
  21866. When PREVIOUS is set, go to the previous sibling instead. Returns t
  21867. when a sibling was found. When none is found, return nil and don't
  21868. move point."
  21869. (let ((fun (if previous 're-search-backward 're-search-forward))
  21870. (pos (point))
  21871. (re org-outline-regexp-bol)
  21872. level l)
  21873. (when (ignore-errors (org-back-to-heading t))
  21874. (setq level (funcall outline-level))
  21875. (catch 'exit
  21876. (or previous (forward-char 1))
  21877. (while (funcall fun re nil t)
  21878. (setq l (funcall outline-level))
  21879. (when (< l level) (goto-char pos) (throw 'exit nil))
  21880. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  21881. (goto-char pos)
  21882. nil))))
  21883. (defun org-show-siblings ()
  21884. "Show all siblings of the current headline."
  21885. (save-excursion
  21886. (while (org-goto-sibling) (org-flag-heading nil)))
  21887. (save-excursion
  21888. (while (org-goto-sibling 'previous)
  21889. (org-flag-heading nil))))
  21890. (defun org-goto-first-child ()
  21891. "Goto the first child, even if it is invisible.
  21892. Return t when a child was found. Otherwise don't move point and
  21893. return nil."
  21894. (let (level (pos (point)) (re org-outline-regexp-bol))
  21895. (when (ignore-errors (org-back-to-heading t))
  21896. (setq level (outline-level))
  21897. (forward-char 1)
  21898. (if (and (re-search-forward re nil t) (> (outline-level) level))
  21899. (progn (goto-char (match-beginning 0)) t)
  21900. (goto-char pos) nil))))
  21901. (defun org-show-hidden-entry ()
  21902. "Show an entry where even the heading is hidden."
  21903. (save-excursion
  21904. (org-show-entry)))
  21905. (defun org-flag-heading (flag &optional entry)
  21906. "Flag the current heading. FLAG non-nil means make invisible.
  21907. When ENTRY is non-nil, show the entire entry."
  21908. (save-excursion
  21909. (org-back-to-heading t)
  21910. ;; Check if we should show the entire entry
  21911. (if entry
  21912. (progn
  21913. (org-show-entry)
  21914. (save-excursion
  21915. (and (outline-next-heading)
  21916. (org-flag-heading nil))))
  21917. (outline-flag-region (max (point-min) (1- (point)))
  21918. (save-excursion (outline-end-of-heading) (point))
  21919. flag))))
  21920. (defun org-get-next-sibling ()
  21921. "Move to next heading of the same level, and return point.
  21922. If there is no such heading, return nil.
  21923. This is like outline-next-sibling, but invisible headings are ok."
  21924. (let ((level (funcall outline-level)))
  21925. (outline-next-heading)
  21926. (while (and (not (eobp)) (> (funcall outline-level) level))
  21927. (outline-next-heading))
  21928. (unless (or (eobp) (< (funcall outline-level) level))
  21929. (point))))
  21930. (defun org-get-last-sibling ()
  21931. "Move to previous heading of the same level, and return point.
  21932. If there is no such heading, return nil."
  21933. (let ((opoint (point))
  21934. (level (funcall outline-level)))
  21935. (outline-previous-heading)
  21936. (when (and (/= (point) opoint) (outline-on-heading-p t))
  21937. (while (and (> (funcall outline-level) level)
  21938. (not (bobp)))
  21939. (outline-previous-heading))
  21940. (unless (< (funcall outline-level) level)
  21941. (point)))))
  21942. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  21943. "Goto to the end of a subtree."
  21944. ;; This contains an exact copy of the original function, but it uses
  21945. ;; `org-back-to-heading', to make it work also in invisible
  21946. ;; trees. And is uses an invisible-ok argument.
  21947. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  21948. ;; Furthermore, when used inside Org, finding the end of a large subtree
  21949. ;; with many children and grandchildren etc, this can be much faster
  21950. ;; than the outline version.
  21951. (org-back-to-heading invisible-ok)
  21952. (let ((first t)
  21953. (level (funcall outline-level)))
  21954. (if (and (derived-mode-p 'org-mode) (< level 1000))
  21955. ;; A true heading (not a plain list item), in Org
  21956. ;; This means we can easily find the end by looking
  21957. ;; only for the right number of stars. Using a regexp to do
  21958. ;; this is so much faster than using a Lisp loop.
  21959. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  21960. (forward-char 1)
  21961. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  21962. ;; something else, do it the slow way
  21963. (while (and (not (eobp))
  21964. (or first (> (funcall outline-level) level)))
  21965. (setq first nil)
  21966. (outline-next-heading)))
  21967. (unless to-heading
  21968. (when (memq (preceding-char) '(?\n ?\^M))
  21969. ;; Go to end of line before heading
  21970. (forward-char -1)
  21971. (when (memq (preceding-char) '(?\n ?\^M))
  21972. ;; leave blank line before heading
  21973. (forward-char -1)))))
  21974. (point))
  21975. (defun org-end-of-meta-data (&optional full)
  21976. "Skip planning line and properties drawer in current entry.
  21977. When optional argument FULL is non-nil, also skip empty lines,
  21978. clocking lines and regular drawers at the beginning of the
  21979. entry."
  21980. (org-back-to-heading t)
  21981. (forward-line)
  21982. (when (looking-at-p org-planning-line-re) (forward-line))
  21983. (when (looking-at org-property-drawer-re)
  21984. (goto-char (match-end 0))
  21985. (forward-line))
  21986. (when (and full (not (org-at-heading-p)))
  21987. (catch 'exit
  21988. (let ((end (save-excursion (outline-next-heading) (point)))
  21989. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  21990. (while (not (eobp))
  21991. (cond ((looking-at-p org-drawer-regexp)
  21992. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  21993. (forward-line)
  21994. (throw 'exit t)))
  21995. ((looking-at-p re) (forward-line))
  21996. (t (throw 'exit t))))))))
  21997. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  21998. "Move forward to the ARG'th subheading at same level as this one.
  21999. Stop at the first and last subheadings of a superior heading.
  22000. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22001. non-nil it will also look at invisible ones."
  22002. (interactive "p")
  22003. (let ((backward? (and arg (< arg 0))))
  22004. (if (org-before-first-heading-p)
  22005. (if backward? (goto-char (point-min)) (outline-next-heading))
  22006. (org-back-to-heading invisible-ok)
  22007. (unless backward? (end-of-line)) ;do not match current headline
  22008. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22009. (f (if backward? #'re-search-backward #'re-search-forward))
  22010. (count (if arg (abs arg) 1))
  22011. (result (point)))
  22012. (while (and (> count 0)
  22013. (funcall f org-outline-regexp-bol nil 'move))
  22014. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22015. (cond ((< l level) (setq count 0))
  22016. ((and (= l level)
  22017. (or invisible-ok
  22018. (not (outline-invisible-p
  22019. (line-beginning-position)))))
  22020. (cl-decf count)
  22021. (when (= l level) (setq result (point)))))))
  22022. (goto-char result))
  22023. (beginning-of-line))))
  22024. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22025. "Move backward to the ARG'th subheading at same level as this one.
  22026. Stop at the first and last subheadings of a superior heading."
  22027. (interactive "p")
  22028. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22029. (defun org-next-visible-heading (arg)
  22030. "Move to the next visible heading.
  22031. This function wraps `outline-next-visible-heading' with
  22032. `org-with-limited-levels' in order to skip over inline tasks and
  22033. respect customization of `org-odd-levels-only'."
  22034. (interactive "p")
  22035. (org-with-limited-levels
  22036. (outline-next-visible-heading arg)))
  22037. (defun org-previous-visible-heading (arg)
  22038. "Move to the previous visible heading.
  22039. This function wraps `outline-previous-visible-heading' with
  22040. `org-with-limited-levels' in order to skip over inline tasks and
  22041. respect customization of `org-odd-levels-only'."
  22042. (interactive "p")
  22043. (org-with-limited-levels
  22044. (outline-previous-visible-heading arg)))
  22045. (defun org-next-block (arg &optional backward block-regexp)
  22046. "Jump to the next block.
  22047. With a prefix argument ARG, jump forward ARG many blocks.
  22048. When BACKWARD is non-nil, jump to the previous block.
  22049. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22050. Match data is set according to this regexp when the function
  22051. returns.
  22052. Return point at beginning of the opening line of found block.
  22053. Throw an error if no block is found."
  22054. (interactive "p")
  22055. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22056. (case-fold-search t)
  22057. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22058. (count (or arg 1))
  22059. (origin (point))
  22060. last-element)
  22061. (if backward (beginning-of-line) (end-of-line))
  22062. (while (and (> count 0) (funcall search-fn re nil t))
  22063. (let ((element (save-excursion
  22064. (goto-char (match-beginning 0))
  22065. (save-match-data (org-element-at-point)))))
  22066. (when (and (memq (org-element-type element)
  22067. '(center-block comment-block dynamic-block
  22068. example-block export-block quote-block
  22069. special-block src-block verse-block))
  22070. (<= (match-beginning 0)
  22071. (org-element-property :post-affiliated element)))
  22072. (setq last-element element)
  22073. (cl-decf count))))
  22074. (if (= count 0)
  22075. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22076. (save-match-data (org-show-context)))
  22077. (goto-char origin)
  22078. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22079. (defun org-previous-block (arg &optional block-regexp)
  22080. "Jump to the previous block.
  22081. With a prefix argument ARG, jump backward ARG many source blocks.
  22082. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22083. (interactive "p")
  22084. (org-next-block arg t block-regexp))
  22085. (defun org-forward-paragraph ()
  22086. "Move forward to beginning of next paragraph or equivalent.
  22087. The function moves point to the beginning of the next visible
  22088. structural element, which can be a paragraph, a table, a list
  22089. item, etc. It also provides some special moves for convenience:
  22090. - On an affiliated keyword, jump to the beginning of the
  22091. relative element.
  22092. - On an item or a footnote definition, move to the second
  22093. element inside, if any.
  22094. - On a table or a property drawer, jump after it.
  22095. - On a verse or source block, stop after blank lines."
  22096. (interactive)
  22097. (when (eobp) (user-error "Cannot move further down"))
  22098. (let* ((deactivate-mark nil)
  22099. (element (org-element-at-point))
  22100. (type (org-element-type element))
  22101. (post-affiliated (org-element-property :post-affiliated element))
  22102. (contents-begin (org-element-property :contents-begin element))
  22103. (contents-end (org-element-property :contents-end element))
  22104. (end (let ((end (org-element-property :end element)) (parent element))
  22105. (while (and (setq parent (org-element-property :parent parent))
  22106. (= (org-element-property :contents-end parent) end))
  22107. (setq end (org-element-property :end parent)))
  22108. end)))
  22109. (cond ((not element)
  22110. (skip-chars-forward " \r\t\n")
  22111. (or (eobp) (beginning-of-line)))
  22112. ;; On affiliated keywords, move to element's beginning.
  22113. ((< (point) post-affiliated)
  22114. (goto-char post-affiliated))
  22115. ;; At a table row, move to the end of the table. Similarly,
  22116. ;; at a node property, move to the end of the property
  22117. ;; drawer.
  22118. ((memq type '(node-property table-row))
  22119. (goto-char (org-element-property
  22120. :end (org-element-property :parent element))))
  22121. ((memq type '(property-drawer table)) (goto-char end))
  22122. ;; Consider blank lines as separators in verse and source
  22123. ;; blocks to ease editing.
  22124. ((memq type '(src-block verse-block))
  22125. (when (eq type 'src-block)
  22126. (setq contents-end
  22127. (save-excursion (goto-char end)
  22128. (skip-chars-backward " \r\t\n")
  22129. (line-beginning-position))))
  22130. (beginning-of-line)
  22131. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22132. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22133. (goto-char end)
  22134. (skip-chars-forward " \r\t\n")
  22135. (if (= (point) contents-end) (goto-char end)
  22136. (beginning-of-line))))
  22137. ;; With no contents, just skip element.
  22138. ((not contents-begin) (goto-char end))
  22139. ;; If contents are invisible, skip the element altogether.
  22140. ((outline-invisible-p (line-end-position))
  22141. (cl-case type
  22142. (headline
  22143. (org-with-limited-levels (outline-next-visible-heading 1)))
  22144. ;; At a plain list, make sure we move to the next item
  22145. ;; instead of skipping the whole list.
  22146. (plain-list (forward-char)
  22147. (org-forward-paragraph))
  22148. (otherwise (goto-char end))))
  22149. ((>= (point) contents-end) (goto-char end))
  22150. ((>= (point) contents-begin)
  22151. ;; This can only happen on paragraphs and plain lists.
  22152. (cl-case type
  22153. (paragraph (goto-char end))
  22154. ;; At a plain list, try to move to second element in
  22155. ;; first item, if possible.
  22156. (plain-list (end-of-line)
  22157. (org-forward-paragraph))))
  22158. ;; When contents start on the middle of a line (e.g. in
  22159. ;; items and footnote definitions), try to reach first
  22160. ;; element starting after current line.
  22161. ((> (line-end-position) contents-begin)
  22162. (end-of-line)
  22163. (org-forward-paragraph))
  22164. (t (goto-char contents-begin)))))
  22165. (defun org-backward-paragraph ()
  22166. "Move backward to start of previous paragraph or equivalent.
  22167. The function moves point to the beginning of the current
  22168. structural element, which can be a paragraph, a table, a list
  22169. item, etc., or to the beginning of the previous visible one if
  22170. point is already there. It also provides some special moves for
  22171. convenience:
  22172. - On an affiliated keyword, jump to the first one.
  22173. - On a table or a property drawer, move to its beginning.
  22174. - On a verse or source block, stop before blank lines."
  22175. (interactive)
  22176. (when (bobp) (user-error "Cannot move further up"))
  22177. (let* ((deactivate-mark nil)
  22178. (element (org-element-at-point))
  22179. (type (org-element-type element))
  22180. (contents-begin (org-element-property :contents-begin element))
  22181. (contents-end (org-element-property :contents-end element))
  22182. (post-affiliated (org-element-property :post-affiliated element))
  22183. (begin (org-element-property :begin element)))
  22184. (cond
  22185. ((not element) (goto-char (point-min)))
  22186. ((= (point) begin)
  22187. (backward-char)
  22188. (org-backward-paragraph))
  22189. ((<= (point) post-affiliated) (goto-char begin))
  22190. ((memq type '(node-property table-row))
  22191. (goto-char (org-element-property
  22192. :post-affiliated (org-element-property :parent element))))
  22193. ((memq type '(property-drawer table)) (goto-char begin))
  22194. ((memq type '(src-block verse-block))
  22195. (when (eq type 'src-block)
  22196. (setq contents-begin
  22197. (save-excursion (goto-char begin) (forward-line) (point))))
  22198. (if (= (point) contents-begin) (goto-char post-affiliated)
  22199. ;; Inside a verse block, see blank lines as paragraph
  22200. ;; separators.
  22201. (let ((origin (point)))
  22202. (skip-chars-backward " \r\t\n" contents-begin)
  22203. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22204. (skip-chars-forward " \r\t\n" origin)
  22205. (if (= (point) origin) (goto-char contents-begin)
  22206. (beginning-of-line))))))
  22207. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22208. ((eq type 'paragraph)
  22209. (goto-char contents-begin)
  22210. ;; When at first paragraph in an item or a footnote definition,
  22211. ;; move directly to beginning of line.
  22212. (let ((parent-contents
  22213. (org-element-property
  22214. :contents-begin (org-element-property :parent element))))
  22215. (when (and parent-contents (= parent-contents contents-begin))
  22216. (beginning-of-line))))
  22217. ;; At the end of a greater element, move to the beginning of the
  22218. ;; last element within.
  22219. ((>= (point) contents-end)
  22220. (goto-char (1- contents-end))
  22221. (org-backward-paragraph))
  22222. (t (goto-char (or post-affiliated begin))))
  22223. ;; Ensure we never leave point invisible.
  22224. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22225. (defun org-forward-element ()
  22226. "Move forward by one element.
  22227. Move to the next element at the same level, when possible."
  22228. (interactive)
  22229. (cond ((eobp) (user-error "Cannot move further down"))
  22230. ((org-with-limited-levels (org-at-heading-p))
  22231. (let ((origin (point)))
  22232. (goto-char (org-end-of-subtree nil t))
  22233. (unless (org-with-limited-levels (org-at-heading-p))
  22234. (goto-char origin)
  22235. (user-error "Cannot move further down"))))
  22236. (t
  22237. (let* ((elem (org-element-at-point))
  22238. (end (org-element-property :end elem))
  22239. (parent (org-element-property :parent elem)))
  22240. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22241. (goto-char (org-element-property :end parent)))
  22242. ((integer-or-marker-p end) (goto-char end))
  22243. (t (message "No element at point")))))))
  22244. (defun org-backward-element ()
  22245. "Move backward by one element.
  22246. Move to the previous element at the same level, when possible."
  22247. (interactive)
  22248. (cond ((bobp) (user-error "Cannot move further up"))
  22249. ((org-with-limited-levels (org-at-heading-p))
  22250. ;; At a headline, move to the previous one, if any, or stay
  22251. ;; here.
  22252. (let ((origin (point)))
  22253. (org-with-limited-levels (org-backward-heading-same-level 1))
  22254. ;; When current headline has no sibling above, move to its
  22255. ;; parent.
  22256. (when (= (point) origin)
  22257. (or (org-with-limited-levels (org-up-heading-safe))
  22258. (progn (goto-char origin)
  22259. (user-error "Cannot move further up"))))))
  22260. (t
  22261. (let* ((elem (org-element-at-point))
  22262. (beg (org-element-property :begin elem)))
  22263. (cond
  22264. ;; Move to beginning of current element if point isn't
  22265. ;; there already.
  22266. ((null beg) (message "No element at point"))
  22267. ((/= (point) beg) (goto-char beg))
  22268. (t (goto-char beg)
  22269. (skip-chars-backward " \r\t\n")
  22270. (unless (bobp)
  22271. (let ((prev (org-element-at-point)))
  22272. (goto-char (org-element-property :begin prev))
  22273. (while (and (setq prev (org-element-property :parent prev))
  22274. (<= (org-element-property :end prev) beg))
  22275. (goto-char (org-element-property :begin prev)))))))))))
  22276. (defun org-up-element ()
  22277. "Move to upper element."
  22278. (interactive)
  22279. (if (org-with-limited-levels (org-at-heading-p))
  22280. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22281. (let* ((elem (org-element-at-point))
  22282. (parent (org-element-property :parent elem)))
  22283. (if parent (goto-char (org-element-property :begin parent))
  22284. (if (org-with-limited-levels (org-before-first-heading-p))
  22285. (user-error "No surrounding element")
  22286. (org-with-limited-levels (org-back-to-heading)))))))
  22287. (defun org-down-element ()
  22288. "Move to inner element."
  22289. (interactive)
  22290. (let ((element (org-element-at-point)))
  22291. (cond
  22292. ((memq (org-element-type element) '(plain-list table))
  22293. (goto-char (org-element-property :contents-begin element))
  22294. (forward-char))
  22295. ((memq (org-element-type element) org-element-greater-elements)
  22296. ;; If contents are hidden, first disclose them.
  22297. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22298. (goto-char (or (org-element-property :contents-begin element)
  22299. (user-error "No content for this element"))))
  22300. (t (user-error "No inner element")))))
  22301. (defun org-drag-element-backward ()
  22302. "Move backward element at point."
  22303. (interactive)
  22304. (let ((elem (or (org-element-at-point)
  22305. (user-error "No element at point"))))
  22306. (if (eq (org-element-type elem) 'headline)
  22307. ;; Preserve point when moving a whole tree, even if point was
  22308. ;; on blank lines below the headline.
  22309. (let ((offset (skip-chars-backward " \t\n")))
  22310. (unwind-protect (org-move-subtree-up)
  22311. (forward-char (- offset))))
  22312. (let ((prev-elem
  22313. (save-excursion
  22314. (goto-char (org-element-property :begin elem))
  22315. (skip-chars-backward " \r\t\n")
  22316. (unless (bobp)
  22317. (let* ((beg (org-element-property :begin elem))
  22318. (prev (org-element-at-point))
  22319. (up prev))
  22320. (while (and (setq up (org-element-property :parent up))
  22321. (<= (org-element-property :end up) beg))
  22322. (setq prev up))
  22323. prev)))))
  22324. ;; Error out if no previous element or previous element is
  22325. ;; a parent of the current one.
  22326. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22327. (user-error "Cannot drag element backward")
  22328. (let ((pos (point)))
  22329. (org-element-swap-A-B prev-elem elem)
  22330. (goto-char (+ (org-element-property :begin prev-elem)
  22331. (- pos (org-element-property :begin elem))))))))))
  22332. (defun org-drag-element-forward ()
  22333. "Move forward element at point."
  22334. (interactive)
  22335. (let* ((pos (point))
  22336. (elem (or (org-element-at-point)
  22337. (user-error "No element at point"))))
  22338. (when (= (point-max) (org-element-property :end elem))
  22339. (user-error "Cannot drag element forward"))
  22340. (goto-char (org-element-property :end elem))
  22341. (let ((next-elem (org-element-at-point)))
  22342. (when (or (org-element-nested-p elem next-elem)
  22343. (and (eq (org-element-type next-elem) 'headline)
  22344. (not (eq (org-element-type elem) 'headline))))
  22345. (goto-char pos)
  22346. (user-error "Cannot drag element forward"))
  22347. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22348. ;; body's length (without final blanks) and by the length of
  22349. ;; blanks between ELEM and NEXT-ELEM.
  22350. (let ((size-next (- (save-excursion
  22351. (goto-char (org-element-property :end next-elem))
  22352. (skip-chars-backward " \r\t\n")
  22353. (forward-line)
  22354. ;; Small correction if buffer doesn't end
  22355. ;; with a newline character.
  22356. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22357. (org-element-property :begin next-elem)))
  22358. (size-blank (- (org-element-property :end elem)
  22359. (save-excursion
  22360. (goto-char (org-element-property :end elem))
  22361. (skip-chars-backward " \r\t\n")
  22362. (forward-line)
  22363. (point)))))
  22364. (org-element-swap-A-B elem next-elem)
  22365. (goto-char (+ pos size-next size-blank))))))
  22366. (defun org-drag-line-forward (arg)
  22367. "Drag the line at point ARG lines forward."
  22368. (interactive "p")
  22369. (dotimes (_ (abs arg))
  22370. (let ((c (current-column)))
  22371. (if (< 0 arg)
  22372. (progn
  22373. (beginning-of-line 2)
  22374. (transpose-lines 1)
  22375. (beginning-of-line 0))
  22376. (transpose-lines 1)
  22377. (beginning-of-line -1))
  22378. (org-move-to-column c))))
  22379. (defun org-drag-line-backward (arg)
  22380. "Drag the line at point ARG lines backward."
  22381. (interactive "p")
  22382. (org-drag-line-forward (- arg)))
  22383. (defun org-mark-element ()
  22384. "Put point at beginning of this element, mark at end.
  22385. Interactively, if this command is repeated or (in Transient Mark
  22386. mode) if the mark is active, it marks the next element after the
  22387. ones already marked."
  22388. (interactive)
  22389. (let (deactivate-mark)
  22390. (if (and (called-interactively-p 'any)
  22391. (or (and (eq last-command this-command) (mark t))
  22392. (and transient-mark-mode mark-active)))
  22393. (set-mark
  22394. (save-excursion
  22395. (goto-char (mark))
  22396. (goto-char (org-element-property :end (org-element-at-point)))))
  22397. (let ((element (org-element-at-point)))
  22398. (end-of-line)
  22399. (push-mark (org-element-property :end element) t t)
  22400. (goto-char (org-element-property :begin element))))))
  22401. (defun org-narrow-to-element ()
  22402. "Narrow buffer to current element."
  22403. (interactive)
  22404. (let ((elem (org-element-at-point)))
  22405. (cond
  22406. ((eq (car elem) 'headline)
  22407. (narrow-to-region
  22408. (org-element-property :begin elem)
  22409. (org-element-property :end elem)))
  22410. ((memq (car elem) org-element-greater-elements)
  22411. (narrow-to-region
  22412. (org-element-property :contents-begin elem)
  22413. (org-element-property :contents-end elem)))
  22414. (t
  22415. (narrow-to-region
  22416. (org-element-property :begin elem)
  22417. (org-element-property :end elem))))))
  22418. (defun org-transpose-element ()
  22419. "Transpose current and previous elements, keeping blank lines between.
  22420. Point is moved after both elements."
  22421. (interactive)
  22422. (org-skip-whitespace)
  22423. (let ((end (org-element-property :end (org-element-at-point))))
  22424. (org-drag-element-backward)
  22425. (goto-char end)))
  22426. (defun org-unindent-buffer ()
  22427. "Un-indent the visible part of the buffer.
  22428. Relative indentation (between items, inside blocks, etc.) isn't
  22429. modified."
  22430. (interactive)
  22431. (unless (eq major-mode 'org-mode)
  22432. (user-error "Cannot un-indent a buffer not in Org mode"))
  22433. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22434. (unindent-tree
  22435. (lambda (contents)
  22436. (dolist (element (reverse contents))
  22437. (if (memq (org-element-type element) '(headline section))
  22438. (funcall unindent-tree (org-element-contents element))
  22439. (save-excursion
  22440. (save-restriction
  22441. (narrow-to-region
  22442. (org-element-property :begin element)
  22443. (org-element-property :end element))
  22444. (org-do-remove-indentation))))))))
  22445. (funcall unindent-tree (org-element-contents parse-tree))))
  22446. (defun org-show-children (&optional level)
  22447. "Show all direct subheadings of this heading.
  22448. Prefix arg LEVEL is how many levels below the current level
  22449. should be shown. Default is enough to cause the following
  22450. heading to appear."
  22451. (interactive "p")
  22452. ;; If `orgstruct-mode' is active, use the slower version.
  22453. (if orgstruct-mode (call-interactively #'outline-show-children)
  22454. (save-excursion
  22455. (org-back-to-heading t)
  22456. (let* ((current-level (funcall outline-level))
  22457. (max-level (org-get-valid-level
  22458. current-level
  22459. (if level (prefix-numeric-value level) 1)))
  22460. (end (save-excursion (org-end-of-subtree t t)))
  22461. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22462. (past-first-child nil)
  22463. ;; Make sure to skip inlinetasks.
  22464. (re (format regexp-fmt
  22465. current-level
  22466. (cond
  22467. ((not (featurep 'org-inlinetask)) "")
  22468. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22469. 3))
  22470. (t (1- org-inlinetask-min-level))))))
  22471. ;; Display parent heading.
  22472. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22473. (forward-line)
  22474. ;; Display children. First child may be deeper than expected
  22475. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22476. ;; MAX-LEVEL accordingly.
  22477. (while (re-search-forward re end t)
  22478. (unless past-first-child
  22479. (setq re (format regexp-fmt
  22480. current-level
  22481. (max (funcall outline-level) max-level)))
  22482. (setq past-first-child t))
  22483. (outline-flag-region
  22484. (line-end-position 0) (line-end-position) nil))))))
  22485. (defun org-show-subtree ()
  22486. "Show everything after this heading at deeper levels."
  22487. (interactive)
  22488. (outline-flag-region
  22489. (point)
  22490. (save-excursion
  22491. (org-end-of-subtree t t))
  22492. nil))
  22493. (defun org-show-entry ()
  22494. "Show the body directly following this heading.
  22495. Show the heading too, if it is currently invisible."
  22496. (interactive)
  22497. (save-excursion
  22498. (ignore-errors
  22499. (org-back-to-heading t)
  22500. (outline-flag-region
  22501. (max (point-min) (1- (point)))
  22502. (save-excursion
  22503. (if (re-search-forward
  22504. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22505. (match-beginning 1)
  22506. (point-max)))
  22507. nil)
  22508. (org-cycle-hide-drawers 'children))))
  22509. (defun org-make-options-regexp (kwds &optional extra)
  22510. "Make a regular expression for keyword lines.
  22511. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22512. when non-nil, is a regexp matching keywords names."
  22513. (concat "^[ \t]*#\\+\\("
  22514. (regexp-opt kwds)
  22515. (and extra (concat (and kwds "\\|") extra))
  22516. "\\):[ \t]*\\(.*\\)"))
  22517. ;;;; Integration with and fixes for other packages
  22518. ;;; Imenu support
  22519. (defvar-local org-imenu-markers nil
  22520. "All markers currently used by Imenu.")
  22521. (defun org-imenu-new-marker (&optional pos)
  22522. "Return a new marker for use by Imenu, and remember the marker."
  22523. (let ((m (make-marker)))
  22524. (move-marker m (or pos (point)))
  22525. (push m org-imenu-markers)
  22526. m))
  22527. (defun org-imenu-get-tree ()
  22528. "Produce the index for Imenu."
  22529. (dolist (x org-imenu-markers) (move-marker x nil))
  22530. (setq org-imenu-markers nil)
  22531. (let* ((case-fold-search nil)
  22532. (n org-imenu-depth)
  22533. (re (concat "^" (org-get-limited-outline-regexp)))
  22534. (subs (make-vector (1+ n) nil))
  22535. (last-level 0)
  22536. m level head0 head)
  22537. (org-with-wide-buffer
  22538. (goto-char (point-max))
  22539. (while (re-search-backward re nil t)
  22540. (setq level (org-reduced-level (funcall outline-level)))
  22541. (when (and (<= level n)
  22542. (looking-at org-complex-heading-regexp)
  22543. (setq head0 (match-string-no-properties 4)))
  22544. (setq head (org-link-display-format head0)
  22545. m (org-imenu-new-marker))
  22546. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22547. (if (>= level last-level)
  22548. (push (cons head m) (aref subs level))
  22549. (push (cons head (aref subs (1+ level))) (aref subs level))
  22550. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22551. (setq last-level level))))
  22552. (aref subs 1)))
  22553. (eval-after-load "imenu"
  22554. '(progn
  22555. (add-hook 'imenu-after-jump-hook
  22556. (lambda ()
  22557. (when (derived-mode-p 'org-mode)
  22558. (org-show-context 'org-goto))))))
  22559. (defun org-link-display-format (s)
  22560. "Replace links in string S with their description.
  22561. If there is no description, use the link target."
  22562. (save-match-data
  22563. (replace-regexp-in-string
  22564. org-bracket-link-analytic-regexp
  22565. (lambda (m)
  22566. (if (match-end 5) (match-string 5 m)
  22567. (concat (match-string 1 m) (match-string 3 m))))
  22568. s nil t)))
  22569. (defun org-toggle-link-display ()
  22570. "Toggle the literal or descriptive display of links."
  22571. (interactive)
  22572. (if org-descriptive-links
  22573. (progn (org-remove-from-invisibility-spec '(org-link))
  22574. (org-restart-font-lock)
  22575. (setq org-descriptive-links nil))
  22576. (progn (add-to-invisibility-spec '(org-link))
  22577. (org-restart-font-lock)
  22578. (setq org-descriptive-links t))))
  22579. ;; Speedbar support
  22580. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22581. "Overlay marking the agenda restriction line in speedbar.")
  22582. (overlay-put org-speedbar-restriction-lock-overlay
  22583. 'face 'org-agenda-restriction-lock)
  22584. (overlay-put org-speedbar-restriction-lock-overlay
  22585. 'help-echo "Agendas are currently limited to this item.")
  22586. (delete-overlay org-speedbar-restriction-lock-overlay)
  22587. (defun org-speedbar-set-agenda-restriction ()
  22588. "Restrict future agenda commands to the location at point in speedbar.
  22589. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22590. (interactive)
  22591. (require 'org-agenda)
  22592. (let (p m tp np dir txt)
  22593. (cond
  22594. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22595. 'org-imenu t))
  22596. (setq m (get-text-property p 'org-imenu-marker))
  22597. (with-current-buffer (marker-buffer m)
  22598. (goto-char m)
  22599. (org-agenda-set-restriction-lock 'subtree)))
  22600. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22601. 'speedbar-function 'speedbar-find-file))
  22602. (setq tp (previous-single-property-change
  22603. (1+ p) 'speedbar-function)
  22604. np (next-single-property-change
  22605. tp 'speedbar-function)
  22606. dir (speedbar-line-directory)
  22607. txt (buffer-substring-no-properties (or tp (point-min))
  22608. (or np (point-max))))
  22609. (with-current-buffer (find-file-noselect
  22610. (let ((default-directory dir))
  22611. (expand-file-name txt)))
  22612. (unless (derived-mode-p 'org-mode)
  22613. (user-error "Cannot restrict to non-Org mode file"))
  22614. (org-agenda-set-restriction-lock 'file)))
  22615. (t (user-error "Don't know how to restrict Org mode agenda")))
  22616. (move-overlay org-speedbar-restriction-lock-overlay
  22617. (point-at-bol) (point-at-eol))
  22618. (setq current-prefix-arg nil)
  22619. (org-agenda-maybe-redo)))
  22620. (defvar speedbar-file-key-map)
  22621. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22622. (eval-after-load "speedbar"
  22623. '(progn
  22624. (speedbar-add-supported-extension ".org")
  22625. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22626. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22627. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22628. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22629. (add-hook 'speedbar-visiting-tag-hook
  22630. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22631. ;;; Fixes and Hacks for problems with other packages
  22632. (defun org--flyspell-object-check-p (element)
  22633. "Non-nil when Flyspell can check object at point.
  22634. ELEMENT is the element at point."
  22635. (let ((object (save-excursion
  22636. (when (looking-at-p "\\>") (backward-char))
  22637. (org-element-context element))))
  22638. (cl-case (org-element-type object)
  22639. ;; Prevent checks in links due to keybinding conflict with
  22640. ;; Flyspell.
  22641. ((code entity export-snippet inline-babel-call
  22642. inline-src-block line-break latex-fragment link macro
  22643. statistics-cookie target timestamp verbatim)
  22644. nil)
  22645. (footnote-reference
  22646. ;; Only in inline footnotes, within the definition.
  22647. (and (eq (org-element-property :type object) 'inline)
  22648. (< (save-excursion
  22649. (goto-char (org-element-property :begin object))
  22650. (search-forward ":" nil t 2))
  22651. (point))))
  22652. (otherwise t))))
  22653. (defun org-mode-flyspell-verify ()
  22654. "Function used for `flyspell-generic-check-word-predicate'."
  22655. (if (org-at-heading-p)
  22656. ;; At a headline or an inlinetask, check title only. This is
  22657. ;; faster than relying on `org-element-at-point'.
  22658. (and (save-excursion (beginning-of-line)
  22659. (and (let ((case-fold-search t))
  22660. (not (looking-at-p "\\*+ END[ \t]*$")))
  22661. (let ((case-fold-search nil))
  22662. (looking-at org-complex-heading-regexp))))
  22663. (match-beginning 4)
  22664. (>= (point) (match-beginning 4))
  22665. (or (not (match-beginning 5))
  22666. (< (point) (match-beginning 5))))
  22667. (let* ((element (org-element-at-point))
  22668. (post-affiliated (org-element-property :post-affiliated element)))
  22669. (cond
  22670. ;; Ignore checks in all affiliated keywords but captions.
  22671. ((< (point) post-affiliated)
  22672. (and (save-excursion
  22673. (beginning-of-line)
  22674. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22675. (> (point) (match-end 0))
  22676. (org--flyspell-object-check-p element)))
  22677. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22678. ((let ((log (org-log-into-drawer)))
  22679. (and log
  22680. (let ((drawer (org-element-lineage element '(drawer))))
  22681. (and drawer
  22682. (eq (compare-strings
  22683. log nil nil
  22684. (org-element-property :drawer-name drawer) nil nil t)
  22685. t)))))
  22686. nil)
  22687. (t
  22688. (cl-case (org-element-type element)
  22689. ((comment quote-section) t)
  22690. (comment-block
  22691. ;; Allow checks between block markers, not on them.
  22692. (and (> (line-beginning-position) post-affiliated)
  22693. (save-excursion
  22694. (end-of-line)
  22695. (skip-chars-forward " \r\t\n")
  22696. (< (point) (org-element-property :end element)))))
  22697. ;; Arbitrary list of keywords where checks are meaningful.
  22698. ;; Make sure point is on the value part of the element.
  22699. (keyword
  22700. (and (member (org-element-property :key element)
  22701. '("DESCRIPTION" "TITLE"))
  22702. (save-excursion
  22703. (search-backward ":" (line-beginning-position) t))))
  22704. ;; Check is globally allowed in paragraphs verse blocks and
  22705. ;; table rows (after affiliated keywords) but some objects
  22706. ;; must not be affected.
  22707. ((paragraph table-row verse-block)
  22708. (let ((cbeg (org-element-property :contents-begin element))
  22709. (cend (org-element-property :contents-end element)))
  22710. (and cbeg (>= (point) cbeg) (< (point) cend)
  22711. (org--flyspell-object-check-p element))))))))))
  22712. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22713. (defun org-remove-flyspell-overlays-in (beg end)
  22714. "Remove flyspell overlays in region."
  22715. (and (bound-and-true-p flyspell-mode)
  22716. (fboundp 'flyspell-delete-region-overlays)
  22717. (flyspell-delete-region-overlays beg end)))
  22718. (defvar flyspell-delayed-commands)
  22719. (eval-after-load "flyspell"
  22720. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22721. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22722. (eval-after-load "bookmark"
  22723. '(if (boundp 'bookmark-after-jump-hook)
  22724. ;; We can use the hook
  22725. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22726. ;; Hook not available, use advice
  22727. (defadvice bookmark-jump (after org-make-visible activate)
  22728. "Make the position visible."
  22729. (org-bookmark-jump-unhide))))
  22730. ;; Make sure saveplace shows the location if it was hidden
  22731. (eval-after-load "saveplace"
  22732. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22733. "Make the position visible."
  22734. (org-bookmark-jump-unhide)))
  22735. ;; Make sure ecb shows the location if it was hidden
  22736. (eval-after-load "ecb"
  22737. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22738. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22739. (when (derived-mode-p 'org-mode)
  22740. (org-show-context))))
  22741. (defun org-bookmark-jump-unhide ()
  22742. "Unhide the current position, to show the bookmark location."
  22743. (and (derived-mode-p 'org-mode)
  22744. (or (outline-invisible-p)
  22745. (save-excursion (goto-char (max (point-min) (1- (point))))
  22746. (outline-invisible-p)))
  22747. (org-show-context 'bookmark-jump)))
  22748. (defun org-mark-jump-unhide ()
  22749. "Make the point visible with `org-show-context' after jumping to the mark."
  22750. (when (and (derived-mode-p 'org-mode)
  22751. (outline-invisible-p))
  22752. (org-show-context 'mark-goto)))
  22753. (eval-after-load "simple"
  22754. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22755. "Make the point visible with `org-show-context'."
  22756. (org-mark-jump-unhide)))
  22757. (eval-after-load "simple"
  22758. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22759. "Make the point visible with `org-show-context'."
  22760. (org-mark-jump-unhide)))
  22761. (eval-after-load "simple"
  22762. '(defadvice pop-global-mark (after org-make-visible activate)
  22763. "Make the point visible with `org-show-context'."
  22764. (org-mark-jump-unhide)))
  22765. ;; Make session.el ignore our circular variable
  22766. (defvar session-globals-exclude)
  22767. (eval-after-load "session"
  22768. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22769. ;;;; Finish up
  22770. (provide 'org)
  22771. (run-hooks 'org-load-hook)
  22772. ;;; org.el ends here